blob: cd67955a22ace75e889b20edb8c7b5c5d0453dc2 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
John McCall83024632010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCallcc14d1f2010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCallde6836a2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCalla020a012010-10-20 05:44:58 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor7731d3f2010-10-13 00:27:52 +000024#include "clang/AST/TypeVisitor.h"
John McCall8b0666c2010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000027#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000029#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000030using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000032
Douglas Gregorb7bfe792009-09-02 22:59:36 +000033/// \brief Determine whether the declaration found is acceptable as the name
34/// of a template and, if so, return that template declaration. Otherwise,
35/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000036static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
37 NamedDecl *Orig) {
38 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000039
Douglas Gregorb7bfe792009-09-02 22:59:36 +000040 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000041 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000042
Douglas Gregorb7bfe792009-09-02 22:59:36 +000043 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
44 // C++ [temp.local]p1:
45 // Like normal (non-template) classes, class templates have an
46 // injected-class-name (Clause 9). The injected-class-name
47 // can be used with or without a template-argument-list. When
48 // it is used without a template-argument-list, it is
49 // equivalent to the injected-class-name followed by the
50 // template-parameters of the class template enclosed in
51 // <>. When it is used with a template-argument-list, it
52 // refers to the specified class template specialization,
53 // which could be the current specialization or another
54 // specialization.
55 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000056 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000057 if (Record->getDescribedClassTemplate())
58 return Record->getDescribedClassTemplate();
59
60 if (ClassTemplateSpecializationDecl *Spec
61 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
62 return Spec->getSpecializedTemplate();
63 }
Mike Stump11289f42009-09-09 15:08:12 +000064
Douglas Gregorb7bfe792009-09-02 22:59:36 +000065 return 0;
66 }
Mike Stump11289f42009-09-09 15:08:12 +000067
Douglas Gregorb7bfe792009-09-02 22:59:36 +000068 return 0;
69}
70
John McCalle66edc12009-11-24 19:00:30 +000071static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000072 // The set of class templates we've already seen.
73 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000074 LookupResult::Filter filter = R.makeFilter();
75 while (filter.hasNext()) {
76 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000077 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000078 if (!Repl)
79 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000080 else if (Repl != Orig) {
81
82 // C++ [temp.local]p3:
83 // A lookup that finds an injected-class-name (10.2) can result in an
84 // ambiguity in certain cases (for example, if it is found in more than
85 // one base class). If all of the injected-class-names that are found
86 // refer to specializations of the same class template, and if the name
87 // is followed by a template-argument-list, the reference refers to the
88 // class template itself and not a specialization thereof, and is not
89 // ambiguous.
90 //
91 // FIXME: Will we eventually have to do the same for alias templates?
92 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
93 if (!ClassTemplates.insert(ClassTmpl)) {
94 filter.erase();
95 continue;
96 }
John McCallbd8062d2010-08-13 07:02:08 +000097
98 // FIXME: we promote access to public here as a workaround to
99 // the fact that LookupResult doesn't let us remember that we
100 // found this template through a particular injected class name,
101 // which means we end up doing nasty things to the invariants.
102 // Pretending that access is public is *much* safer.
103 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000104 }
John McCalle66edc12009-11-24 19:00:30 +0000105 }
106 filter.done();
107}
108
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000109TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000110 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000111 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000112 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000113 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000114 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000115 TemplateTy &TemplateResult,
116 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000117 assert(getLangOptions().CPlusPlus && "No template names in C!");
118
Douglas Gregor3cf81312009-11-03 23:16:33 +0000119 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000120 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000121
122 switch (Name.getKind()) {
123 case UnqualifiedId::IK_Identifier:
124 TName = DeclarationName(Name.Identifier);
125 break;
126
127 case UnqualifiedId::IK_OperatorFunctionId:
128 TName = Context.DeclarationNames.getCXXOperatorName(
129 Name.OperatorFunctionId.Operator);
130 break;
131
Alexis Hunted0530f2009-11-28 08:58:14 +0000132 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000133 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
134 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000135
Douglas Gregor3cf81312009-11-03 23:16:33 +0000136 default:
137 return TNK_Non_template;
138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
John McCallba7bf592010-08-24 05:47:05 +0000140 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000141
Douglas Gregorff18cc12009-12-31 08:11:17 +0000142 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
143 LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000144 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
145 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000146 if (R.empty()) return TNK_Non_template;
147 if (R.isAmbiguous()) {
148 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000149 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000150
151 // FIXME: we might have ambiguous templates, in which case we
152 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000153 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000154 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000155
John McCalld28ae272009-12-02 08:04:21 +0000156 TemplateName Template;
157 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000158
John McCalld28ae272009-12-02 08:04:21 +0000159 unsigned ResultCount = R.end() - R.begin();
160 if (ResultCount > 1) {
161 // We assume that we'll preserve the qualifier from a function
162 // template name in other ways.
163 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
164 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000165
166 // We'll do this lookup again later.
167 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000168 } else {
John McCalld28ae272009-12-02 08:04:21 +0000169 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
170
171 if (SS.isSet() && !SS.isInvalid()) {
172 NestedNameSpecifier *Qualifier
173 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000174 Template = Context.getQualifiedTemplateName(Qualifier,
175 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000176 } else {
177 Template = TemplateName(TD);
178 }
179
John McCalldcc71402010-08-13 02:23:42 +0000180 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000181 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000182
183 // We'll do this lookup again later.
184 R.suppressDiagnostics();
185 } else {
John McCalld28ae272009-12-02 08:04:21 +0000186 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
187 TemplateKind = TNK_Type_template;
188 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000189 }
Mike Stump11289f42009-09-09 15:08:12 +0000190
John McCalld28ae272009-12-02 08:04:21 +0000191 TemplateResult = TemplateTy::make(Template);
192 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000193}
194
Douglas Gregor18473f32010-01-12 21:28:44 +0000195bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
196 SourceLocation IILoc,
197 Scope *S,
198 const CXXScopeSpec *SS,
199 TemplateTy &SuggestedTemplate,
200 TemplateNameKind &SuggestedKind) {
201 // We can't recover unless there's a dependent scope specifier preceding the
202 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000203 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000204 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
205 computeDeclContext(*SS))
206 return false;
207
208 // The code is missing a 'template' keyword prior to the dependent template
209 // name.
210 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
211 Diag(IILoc, diag::err_template_kw_missing)
212 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000213 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000214 SuggestedTemplate
215 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
216 SuggestedKind = TNK_Dependent_template_name;
217 return true;
218}
219
John McCalle66edc12009-11-24 19:00:30 +0000220void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000221 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000222 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000223 bool EnteringContext,
224 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000225 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000226 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000227 DeclContext *LookupCtx = 0;
228 bool isDependent = false;
229 if (!ObjectType.isNull()) {
230 // This nested-name-specifier occurs in a member access expression, e.g.,
231 // x->B::f, and we are looking into the type of the object.
232 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
233 LookupCtx = computeDeclContext(ObjectType);
234 isDependent = ObjectType->isDependentType();
235 assert((isDependent || !ObjectType->isIncompleteType()) &&
236 "Caller should have completed object type");
237 } else if (SS.isSet()) {
238 // This nested-name-specifier occurs after another nested-name-specifier,
239 // so long into the context associated with the prior nested-name-specifier.
240 LookupCtx = computeDeclContext(SS, EnteringContext);
241 isDependent = isDependentScopeSpecifier(SS);
242
243 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000244 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000245 return;
246 }
247
248 bool ObjectTypeSearchedInScope = false;
249 if (LookupCtx) {
250 // Perform "qualified" name lookup into the declaration context we
251 // computed, which is either the type of the base of a member access
252 // expression or the declaration context associated with a prior
253 // nested-name-specifier.
254 LookupQualifiedName(Found, LookupCtx);
255
256 if (!ObjectType.isNull() && Found.empty()) {
257 // C++ [basic.lookup.classref]p1:
258 // In a class member access expression (5.2.5), if the . or -> token is
259 // immediately followed by an identifier followed by a <, the
260 // identifier must be looked up to determine whether the < is the
261 // beginning of a template argument list (14.2) or a less-than operator.
262 // The identifier is first looked up in the class of the object
263 // expression. If the identifier is not found, it is then looked up in
264 // the context of the entire postfix-expression and shall name a class
265 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000266 if (S) LookupName(Found, S);
267 ObjectTypeSearchedInScope = true;
268 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000269 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000270 // We cannot look into a dependent object type or nested nme
271 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000272 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000273 return;
274 } else {
275 // Perform unqualified name lookup in the current scope.
276 LookupName(Found, S);
277 }
278
Douglas Gregorc119dd52010-01-12 17:06:20 +0000279 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000280 // If we did not find any names, attempt to correct any typos.
281 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000282 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregorc048c522010-06-29 19:27:42 +0000283 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000284 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000285 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000286 if (LookupCtx)
287 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
288 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000289 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000290 Found.getLookupName().getAsString());
291 else
292 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
293 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000294 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000295 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000296 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
297 Diag(Template->getLocation(), diag::note_previous_decl)
298 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000299 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000300 } else {
301 Found.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +0000302 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000303 }
304 }
305
John McCalle66edc12009-11-24 19:00:30 +0000306 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000307 if (Found.empty()) {
308 if (isDependent)
309 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000310 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000311 }
John McCalle66edc12009-11-24 19:00:30 +0000312
313 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
314 // C++ [basic.lookup.classref]p1:
315 // [...] If the lookup in the class of the object expression finds a
316 // template, the name is also looked up in the context of the entire
317 // postfix-expression and [...]
318 //
319 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
320 LookupOrdinaryName);
321 LookupName(FoundOuter, S);
322 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000323
John McCalle66edc12009-11-24 19:00:30 +0000324 if (FoundOuter.empty()) {
325 // - if the name is not found, the name found in the class of the
326 // object expression is used, otherwise
327 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
328 // - if the name is found in the context of the entire
329 // postfix-expression and does not name a class template, the name
330 // found in the class of the object expression is used, otherwise
John McCalle9cccd82010-06-16 08:42:20 +0000331 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000332 // - if the name found is a class template, it must refer to the same
333 // entity as the one found in the class of the object expression,
334 // otherwise the program is ill-formed.
335 if (!Found.isSingleResult() ||
336 Found.getFoundDecl()->getCanonicalDecl()
337 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
338 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000339 diag::ext_nested_name_member_ref_lookup_ambiguous)
340 << Found.getLookupName()
341 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000342 Diag(Found.getRepresentativeDecl()->getLocation(),
343 diag::note_ambig_member_ref_object_type)
344 << ObjectType;
345 Diag(FoundOuter.getFoundDecl()->getLocation(),
346 diag::note_ambig_member_ref_scope);
347
348 // Recover by taking the template that we found in the object
349 // expression's type.
350 }
351 }
352 }
353}
354
John McCallcd4b4772009-12-02 03:53:29 +0000355/// ActOnDependentIdExpression - Handle a dependent id-expression that
356/// was just parsed. This is only possible with an explicit scope
357/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000358ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000359Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000360 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000361 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000362 const TemplateArgumentListInfo *TemplateArgs) {
363 NestedNameSpecifier *Qualifier
364 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000365
366 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000367
John McCallcd4b4772009-12-02 03:53:29 +0000368 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000369 isa<CXXMethodDecl>(DC) &&
370 cast<CXXMethodDecl>(DC)->isInstance()) {
371 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000372
John McCalle66edc12009-11-24 19:00:30 +0000373 // Since the 'this' expression is synthesized, we don't need to
374 // perform the double-lookup check.
375 NamedDecl *FirstQualifierInScope = 0;
376
John McCall2d74de92009-12-01 22:10:20 +0000377 return Owned(CXXDependentScopeMemberExpr::Create(Context,
378 /*This*/ 0, ThisType,
379 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000380 /*Op*/ SourceLocation(),
381 Qualifier, SS.getRange(),
382 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000383 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000384 TemplateArgs));
385 }
386
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000387 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000388}
389
John McCalldadc5752010-08-24 06:29:42 +0000390ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000391Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000392 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000393 const TemplateArgumentListInfo *TemplateArgs) {
394 return Owned(DependentScopeDeclRefExpr::Create(Context,
395 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
396 SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000397 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000398 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000399}
400
Douglas Gregor5101c242008-12-05 18:15:24 +0000401/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
402/// that the template parameter 'PrevDecl' is being shadowed by a new
403/// declaration at location Loc. Returns true to indicate that this is
404/// an error, and false otherwise.
405bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000406 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000407
408 // Microsoft Visual C++ permits template parameters to be shadowed.
409 if (getLangOptions().Microsoft)
410 return false;
411
412 // C++ [temp.local]p4:
413 // A template-parameter shall not be redeclared within its
414 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000415 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000416 << cast<NamedDecl>(PrevDecl)->getDeclName();
417 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
418 return true;
419}
420
Douglas Gregor463421d2009-03-03 04:44:36 +0000421/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000422/// the parameter D to reference the templated declaration and return a pointer
423/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000424TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
425 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
426 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000427 return Temp;
428 }
429 return 0;
430}
431
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000432static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
433 const ParsedTemplateArgument &Arg) {
434
435 switch (Arg.getKind()) {
436 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000437 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000438 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
439 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000440 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000441 return TemplateArgumentLoc(TemplateArgument(T), DI);
442 }
443
444 case ParsedTemplateArgument::NonType: {
445 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
446 return TemplateArgumentLoc(TemplateArgument(E), E);
447 }
448
449 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000450 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000451 return TemplateArgumentLoc(TemplateArgument(Template),
452 Arg.getScopeSpec().getRange(),
453 Arg.getLocation());
454 }
455 }
456
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000457 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000458 return TemplateArgumentLoc();
459}
460
461/// \brief Translates template arguments as provided by the parser
462/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000463void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
464 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000465 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000466 TemplateArgs.addArgument(translateTemplateArgument(*this,
467 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000468}
469
Douglas Gregor5101c242008-12-05 18:15:24 +0000470/// ActOnTypeParameter - Called when a C++ template type parameter
471/// (e.g., "typename T") has been parsed. Typename specifies whether
472/// the keyword "typename" was used to declare the type parameter
473/// (otherwise, "class" was used), and KeyLoc is the location of the
474/// "class" or "typename" keyword. ParamName is the name of the
475/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000476/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000477/// If the type parameter has a default argument, it will be added
478/// later via ActOnTypeParameterDefault.
John McCall48871652010-08-21 09:40:31 +0000479Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
480 SourceLocation EllipsisLoc,
481 SourceLocation KeyLoc,
482 IdentifierInfo *ParamName,
483 SourceLocation ParamNameLoc,
484 unsigned Depth, unsigned Position,
485 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000486 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000487 assert(S->isTemplateParamScope() &&
488 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000489 bool Invalid = false;
490
491 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000492 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000493 LookupOrdinaryName,
494 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000495 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000496 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000497 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000498 }
499
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000500 SourceLocation Loc = ParamNameLoc;
501 if (!ParamName)
502 Loc = KeyLoc;
503
Douglas Gregor5101c242008-12-05 18:15:24 +0000504 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000505 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
506 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000507 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000508 if (Invalid)
509 Param->setInvalidDecl();
510
511 if (ParamName) {
512 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000513 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000514 IdResolver.AddDecl(Param);
515 }
516
Douglas Gregordc13ded2010-07-01 00:00:45 +0000517 // Handle the default argument, if provided.
518 if (DefaultArg) {
519 TypeSourceInfo *DefaultTInfo;
520 GetTypeFromParser(DefaultArg, &DefaultTInfo);
521
522 assert(DefaultTInfo && "expected source information for type");
523
524 // C++0x [temp.param]p9:
525 // A default template-argument may be specified for any kind of
526 // template-parameter that is not a template parameter pack.
527 if (Ellipsis) {
528 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCall48871652010-08-21 09:40:31 +0000529 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000530 }
531
532 // Check the template argument itself.
533 if (CheckTemplateArgument(Param, DefaultTInfo)) {
534 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000535 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000536 }
537
538 Param->setDefaultArgument(DefaultTInfo, false);
539 }
540
John McCall48871652010-08-21 09:40:31 +0000541 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000542}
543
Douglas Gregor463421d2009-03-03 04:44:36 +0000544/// \brief Check that the type of a non-type template parameter is
545/// well-formed.
546///
547/// \returns the (possibly-promoted) parameter type if valid;
548/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000549QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000550Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000551 // We don't allow variably-modified types as the type of non-type template
552 // parameters.
553 if (T->isVariablyModifiedType()) {
554 Diag(Loc, diag::err_variably_modified_nontype_template_param)
555 << T;
556 return QualType();
557 }
558
Douglas Gregor463421d2009-03-03 04:44:36 +0000559 // C++ [temp.param]p4:
560 //
561 // A non-type template-parameter shall have one of the following
562 // (optionally cv-qualified) types:
563 //
564 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000565 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000566 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000567 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000568 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000569 T->isReferenceType() ||
570 // -- pointer to member.
571 T->isMemberPointerType() ||
572 // If T is a dependent type, we can't do the check now, so we
573 // assume that it is well-formed.
574 T->isDependentType())
575 return T;
576 // C++ [temp.param]p8:
577 //
578 // A non-type template-parameter of type "array of T" or
579 // "function returning T" is adjusted to be of type "pointer to
580 // T" or "pointer to function returning T", respectively.
581 else if (T->isArrayType())
582 // FIXME: Keep the type prior to promotion?
583 return Context.getArrayDecayedType(T);
584 else if (T->isFunctionType())
585 // FIXME: Keep the type prior to promotion?
586 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000587
Douglas Gregor463421d2009-03-03 04:44:36 +0000588 Diag(Loc, diag::err_template_nontype_parm_bad_type)
589 << T;
590
591 return QualType();
592}
593
John McCall48871652010-08-21 09:40:31 +0000594Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
595 unsigned Depth,
596 unsigned Position,
597 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000598 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000599 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
600 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000601
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000602 assert(S->isTemplateParamScope() &&
603 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000604 bool Invalid = false;
605
606 IdentifierInfo *ParamName = D.getIdentifier();
607 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000608 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000609 LookupOrdinaryName,
610 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000611 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000612 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000613 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000614 }
615
Douglas Gregor463421d2009-03-03 04:44:36 +0000616 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000617 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000618 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000619 Invalid = true;
620 }
Douglas Gregor81338792009-02-10 17:43:50 +0000621
Douglas Gregor5101c242008-12-05 18:15:24 +0000622 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000623 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
624 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000625 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000626 if (Invalid)
627 Param->setInvalidDecl();
628
629 if (D.getIdentifier()) {
630 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000631 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000632 IdResolver.AddDecl(Param);
633 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000634
635 // Check the well-formedness of the default template argument, if provided.
John McCallb268a282010-08-23 23:25:46 +0000636 if (Default) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000637 TemplateArgument Converted;
638 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
639 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000640 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000641 }
642
John McCallb268a282010-08-23 23:25:46 +0000643 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000644 }
645
John McCall48871652010-08-21 09:40:31 +0000646 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000647}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000648
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000649/// ActOnTemplateTemplateParameter - Called when a C++ template template
650/// parameter (e.g. T in template <template <typename> class T> class array)
651/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000652Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
653 SourceLocation TmpLoc,
654 TemplateParamsTy *Params,
655 IdentifierInfo *Name,
656 SourceLocation NameLoc,
657 unsigned Depth,
658 unsigned Position,
659 SourceLocation EqualLoc,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000660 const ParsedTemplateArgument &Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000661 assert(S->isTemplateParamScope() &&
662 "Template template parameter not in template parameter scope!");
663
664 // Construct the parameter object.
665 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000666 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregor713602b2010-08-31 17:01:39 +0000667 NameLoc.isInvalid()? TmpLoc : NameLoc,
668 Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000669 (TemplateParameterList*)Params);
670
Douglas Gregordc13ded2010-07-01 00:00:45 +0000671 // If the template template parameter has a name, then link the identifier
672 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000673 if (Name) {
John McCall48871652010-08-21 09:40:31 +0000674 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000675 IdResolver.AddDecl(Param);
676 }
677
Douglas Gregordc13ded2010-07-01 00:00:45 +0000678 if (!Default.isInvalid()) {
679 // Check only that we have a template template argument. We don't want to
680 // try to check well-formedness now, because our template template parameter
681 // might have dependent types in its template parameters, which we wouldn't
682 // be able to match now.
683 //
684 // If none of the template template parameter's template arguments mention
685 // other template parameters, we could actually perform more checking here.
686 // However, it isn't worth doing.
687 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
688 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
689 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
690 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000691 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000692 }
693
694 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000695 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000696
John McCall48871652010-08-21 09:40:31 +0000697 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000698}
699
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000700/// ActOnTemplateParameterList - Builds a TemplateParameterList that
701/// contains the template parameters in Params/NumParams.
702Sema::TemplateParamsTy *
703Sema::ActOnTemplateParameterList(unsigned Depth,
704 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000705 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000706 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000707 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000708 SourceLocation RAngleLoc) {
709 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000710 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000711
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000712 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000713 (NamedDecl**)Params, NumParams,
714 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000715}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000716
John McCall3e11ebe2010-03-15 10:12:16 +0000717static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
718 if (SS.isSet())
719 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
720 SS.getRange());
721}
722
John McCallfaf5fb42010-08-26 23:41:50 +0000723DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000724Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000725 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000726 IdentifierInfo *Name, SourceLocation NameLoc,
727 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000728 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000729 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000730 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000731 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000732 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000733 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000734
735 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000736 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000737 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000738
Abramo Bagnara6150c882010-05-11 21:36:43 +0000739 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
740 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000741
742 // There is no such thing as an unnamed class template.
743 if (!Name) {
744 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000745 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000746 }
747
748 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000749 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000750 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000751 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000752 if (SS.isNotEmpty() && !SS.isInvalid()) {
753 SemanticContext = computeDeclContext(SS, true);
754 if (!SemanticContext) {
755 // FIXME: Produce a reasonable diagnostic here
756 return true;
757 }
Mike Stump11289f42009-09-09 15:08:12 +0000758
John McCall0b66eb32010-05-01 00:40:08 +0000759 if (RequireCompleteDeclContext(SS, SemanticContext))
760 return true;
761
John McCall27b18f82009-11-17 02:14:36 +0000762 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000763 } else {
764 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000765 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000766 }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000768 if (Previous.isAmbiguous())
769 return true;
770
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000771 NamedDecl *PrevDecl = 0;
772 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000773 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000774
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000775 // If there is a previous declaration with the same name, check
776 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000777 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000778 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000779
780 // We may have found the injected-class-name of a class template,
781 // class template partial specialization, or class template specialization.
782 // In these cases, grab the template that is being defined or specialized.
783 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
784 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
785 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
786 PrevClassTemplate
787 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
788 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
789 PrevClassTemplate
790 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
791 ->getSpecializedTemplate();
792 }
793 }
794
John McCalld43784f2009-12-18 11:25:59 +0000795 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000796 // C++ [namespace.memdef]p3:
797 // [...] When looking for a prior declaration of a class or a function
798 // declared as a friend, and when the name of the friend class or
799 // function is neither a qualified name nor a template-id, scopes outside
800 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000801 if (!SS.isSet()) {
802 DeclContext *OutermostContext = CurContext;
803 while (!OutermostContext->isFileContext())
804 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000805
Douglas Gregorb74b1032010-04-18 17:37:40 +0000806 if (PrevDecl &&
807 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
808 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
809 SemanticContext = PrevDecl->getDeclContext();
810 } else {
811 // Declarations in outer scopes don't matter. However, the outermost
812 // context we computed is the semantic context for our new
813 // declaration.
814 PrevDecl = PrevClassTemplate = 0;
815 SemanticContext = OutermostContext;
816 }
John McCall90d3bb92009-12-17 23:21:11 +0000817 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000818
John McCall90d3bb92009-12-17 23:21:11 +0000819 if (CurContext->isDependentContext()) {
820 // If this is a dependent context, we don't want to link the friend
821 // class template to the template in scope, because that would perform
822 // checking of the template parameter lists that can't be performed
823 // until the outer context is instantiated.
824 PrevDecl = PrevClassTemplate = 0;
825 }
826 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
827 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000828
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000829 if (PrevClassTemplate) {
830 // Ensure that the template parameter lists are compatible.
831 if (!TemplateParameterListsAreEqual(TemplateParams,
832 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000833 /*Complain=*/true,
834 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000835 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000836
837 // C++ [temp.class]p4:
838 // In a redeclaration, partial specialization, explicit
839 // specialization or explicit instantiation of a class template,
840 // the class-key shall agree in kind with the original class
841 // template declaration (7.1.5.3).
842 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000843 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000844 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000845 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000846 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000847 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000848 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849 }
850
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000851 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000852 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000853 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000854 Diag(NameLoc, diag::err_redefinition) << Name;
855 Diag(Def->getLocation(), diag::note_previous_definition);
856 // FIXME: Would it make sense to try to "forget" the previous
857 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000858 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000859 }
860 }
861 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
862 // Maybe we will complain about the shadowed template parameter.
863 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
864 // Just pretend that we didn't see the previous declaration.
865 PrevDecl = 0;
866 } else if (PrevDecl) {
867 // C++ [temp]p5:
868 // A class template shall not have the same name as any other
869 // template, class, function, object, enumeration, enumerator,
870 // namespace, or type in the same scope (3.3), except as specified
871 // in (14.5.4).
872 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
873 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000874 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000875 }
876
Douglas Gregordba32632009-02-10 19:49:53 +0000877 // Check the template parameter list of this declaration, possibly
878 // merging in the template parameter list from the previous class
879 // template declaration.
880 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000881 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
882 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000883 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000884
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000885 if (SS.isSet()) {
886 // If the name of the template was qualified, we must be defining the
887 // template out-of-line.
888 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
889 !(TUK == TUK_Friend && CurContext->isDependentContext()))
890 Diag(NameLoc, diag::err_member_def_does_not_match)
891 << Name << SemanticContext << SS.getRange();
892 }
893
Mike Stump11289f42009-09-09 15:08:12 +0000894 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000895 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000896 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000897 PrevClassTemplate->getTemplatedDecl() : 0,
898 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000899 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000900
901 ClassTemplateDecl *NewTemplate
902 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
903 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000904 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000905 NewClass->setDescribedClassTemplate(NewTemplate);
906
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000907 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000908 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +0000909 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000910 assert(T->isDependentType() && "Class template type is not dependent?");
911 (void)T;
912
Douglas Gregorcf915552009-10-13 16:30:37 +0000913 // If we are providing an explicit specialization of a member that is a
914 // class template, make a note of that.
915 if (PrevClassTemplate &&
916 PrevClassTemplate->getInstantiatedFromMemberTemplate())
917 PrevClassTemplate->setMemberSpecialization();
918
Anders Carlsson137108d2009-03-26 01:24:28 +0000919 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000920 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000921 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000923 // Set the lexical context of these templates
924 NewClass->setLexicalDeclContext(CurContext);
925 NewTemplate->setLexicalDeclContext(CurContext);
926
John McCall9bb74a52009-07-31 02:45:11 +0000927 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000928 NewClass->startDefinition();
929
930 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000931 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000932
John McCall27b5c252009-09-14 21:59:20 +0000933 if (TUK != TUK_Friend)
934 PushOnScopeChains(NewTemplate, S);
935 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000936 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000937 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000938 NewClass->setAccess(PrevClassTemplate->getAccess());
939 }
John McCall27b5c252009-09-14 21:59:20 +0000940
Douglas Gregor3dad8422009-09-26 06:47:28 +0000941 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
942 PrevClassTemplate != NULL);
943
John McCall27b5c252009-09-14 21:59:20 +0000944 // Friend templates are visible in fairly strange ways.
945 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000946 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall27b5c252009-09-14 21:59:20 +0000947 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
948 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
949 PushOnScopeChains(NewTemplate, EnclosingScope,
950 /* AddToContext = */ false);
951 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000952
953 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
954 NewClass->getLocation(),
955 NewTemplate,
956 /*FIXME:*/NewClass->getLocation());
957 Friend->setAccess(AS_public);
958 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000959 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000960
Douglas Gregordba32632009-02-10 19:49:53 +0000961 if (Invalid) {
962 NewTemplate->setInvalidDecl();
963 NewClass->setInvalidDecl();
964 }
John McCall48871652010-08-21 09:40:31 +0000965 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000966}
967
Douglas Gregored5731f2009-11-25 17:50:39 +0000968/// \brief Diagnose the presence of a default template argument on a
969/// template parameter, which is ill-formed in certain contexts.
970///
971/// \returns true if the default template argument should be dropped.
972static bool DiagnoseDefaultTemplateArgument(Sema &S,
973 Sema::TemplateParamListContext TPC,
974 SourceLocation ParamLoc,
975 SourceRange DefArgRange) {
976 switch (TPC) {
977 case Sema::TPC_ClassTemplate:
978 return false;
979
980 case Sema::TPC_FunctionTemplate:
981 // C++ [temp.param]p9:
982 // A default template-argument shall not be specified in a
983 // function template declaration or a function template
984 // definition [...]
985 // (This sentence is not in C++0x, per DR226).
986 if (!S.getLangOptions().CPlusPlus0x)
987 S.Diag(ParamLoc,
988 diag::err_template_parameter_default_in_function_template)
989 << DefArgRange;
990 return false;
991
992 case Sema::TPC_ClassTemplateMember:
993 // C++0x [temp.param]p9:
994 // A default template-argument shall not be specified in the
995 // template-parameter-lists of the definition of a member of a
996 // class template that appears outside of the member's class.
997 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
998 << DefArgRange;
999 return true;
1000
1001 case Sema::TPC_FriendFunctionTemplate:
1002 // C++ [temp.param]p9:
1003 // A default template-argument shall not be specified in a
1004 // friend template declaration.
1005 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1006 << DefArgRange;
1007 return true;
1008
1009 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1010 // for friend function templates if there is only a single
1011 // declaration (and it is a definition). Strange!
1012 }
1013
1014 return false;
1015}
1016
Douglas Gregordba32632009-02-10 19:49:53 +00001017/// \brief Checks the validity of a template parameter list, possibly
1018/// considering the template parameter list from a previous
1019/// declaration.
1020///
1021/// If an "old" template parameter list is provided, it must be
1022/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1023/// template parameter list.
1024///
1025/// \param NewParams Template parameter list for a new template
1026/// declaration. This template parameter list will be updated with any
1027/// default arguments that are carried through from the previous
1028/// template parameter list.
1029///
1030/// \param OldParams If provided, template parameter list from a
1031/// previous declaration of the same template. Default template
1032/// arguments will be merged from the old template parameter list to
1033/// the new template parameter list.
1034///
Douglas Gregored5731f2009-11-25 17:50:39 +00001035/// \param TPC Describes the context in which we are checking the given
1036/// template parameter list.
1037///
Douglas Gregordba32632009-02-10 19:49:53 +00001038/// \returns true if an error occurred, false otherwise.
1039bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001040 TemplateParameterList *OldParams,
1041 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001042 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001043
Douglas Gregordba32632009-02-10 19:49:53 +00001044 // C++ [temp.param]p10:
1045 // The set of default template-arguments available for use with a
1046 // template declaration or definition is obtained by merging the
1047 // default arguments from the definition (if in scope) and all
1048 // declarations in scope in the same way default function
1049 // arguments are (8.3.6).
1050 bool SawDefaultArgument = false;
1051 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001052
Anders Carlsson327865d2009-06-12 23:20:15 +00001053 bool SawParameterPack = false;
1054 SourceLocation ParameterPackLoc;
1055
Mike Stumpc89c8e32009-02-11 23:03:27 +00001056 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001057 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001058 if (OldParams)
1059 OldParam = OldParams->begin();
1060
1061 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1062 NewParamEnd = NewParams->end();
1063 NewParam != NewParamEnd; ++NewParam) {
1064 // Variables used to diagnose redundant default arguments
1065 bool RedundantDefaultArg = false;
1066 SourceLocation OldDefaultLoc;
1067 SourceLocation NewDefaultLoc;
1068
1069 // Variables used to diagnose missing default arguments
1070 bool MissingDefaultArg = false;
1071
Anders Carlsson327865d2009-06-12 23:20:15 +00001072 // C++0x [temp.param]p11:
1073 // If a template parameter of a class template is a template parameter pack,
1074 // it must be the last template parameter.
1075 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001076 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001077 diag::err_template_param_pack_must_be_last_template_parameter);
1078 Invalid = true;
1079 }
1080
Douglas Gregordba32632009-02-10 19:49:53 +00001081 if (TemplateTypeParmDecl *NewTypeParm
1082 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001083 // Check the presence of a default argument here.
1084 if (NewTypeParm->hasDefaultArgument() &&
1085 DiagnoseDefaultTemplateArgument(*this, TPC,
1086 NewTypeParm->getLocation(),
1087 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001088 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001089 NewTypeParm->removeDefaultArgument();
1090
1091 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001092 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001093 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001094
Anders Carlsson327865d2009-06-12 23:20:15 +00001095 if (NewTypeParm->isParameterPack()) {
1096 assert(!NewTypeParm->hasDefaultArgument() &&
1097 "Parameter packs can't have a default argument!");
1098 SawParameterPack = true;
1099 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001100 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001101 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001102 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1103 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1104 SawDefaultArgument = true;
1105 RedundantDefaultArg = true;
1106 PreviousDefaultArgLoc = NewDefaultLoc;
1107 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1108 // Merge the default argument from the old declaration to the
1109 // new declaration.
1110 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001111 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001112 true);
1113 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1114 } else if (NewTypeParm->hasDefaultArgument()) {
1115 SawDefaultArgument = true;
1116 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1117 } else if (SawDefaultArgument)
1118 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001119 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001120 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001121 // Check the presence of a default argument here.
1122 if (NewNonTypeParm->hasDefaultArgument() &&
1123 DiagnoseDefaultTemplateArgument(*this, TPC,
1124 NewNonTypeParm->getLocation(),
1125 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001126 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001127 }
1128
Mike Stump12b8ce12009-08-04 21:02:39 +00001129 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001130 NonTypeTemplateParmDecl *OldNonTypeParm
1131 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001132 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001133 NewNonTypeParm->hasDefaultArgument()) {
1134 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1135 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1136 SawDefaultArgument = true;
1137 RedundantDefaultArg = true;
1138 PreviousDefaultArgLoc = NewDefaultLoc;
1139 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1140 // Merge the default argument from the old declaration to the
1141 // new declaration.
1142 SawDefaultArgument = true;
1143 // FIXME: We need to create a new kind of "default argument"
1144 // expression that points to a previous template template
1145 // parameter.
1146 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001147 OldNonTypeParm->getDefaultArgument(),
1148 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001149 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1150 } else if (NewNonTypeParm->hasDefaultArgument()) {
1151 SawDefaultArgument = true;
1152 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1153 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001154 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001155 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001156 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001157 TemplateTemplateParmDecl *NewTemplateParm
1158 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001159 if (NewTemplateParm->hasDefaultArgument() &&
1160 DiagnoseDefaultTemplateArgument(*this, TPC,
1161 NewTemplateParm->getLocation(),
1162 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001163 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001164
1165 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001166 TemplateTemplateParmDecl *OldTemplateParm
1167 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001168 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001169 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001170 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1171 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001172 SawDefaultArgument = true;
1173 RedundantDefaultArg = true;
1174 PreviousDefaultArgLoc = NewDefaultLoc;
1175 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1176 // Merge the default argument from the old declaration to the
1177 // new declaration.
1178 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001179 // FIXME: We need to create a new kind of "default argument" expression
1180 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001181 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001182 OldTemplateParm->getDefaultArgument(),
1183 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001184 PreviousDefaultArgLoc
1185 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001186 } else if (NewTemplateParm->hasDefaultArgument()) {
1187 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001188 PreviousDefaultArgLoc
1189 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001190 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001191 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001192 }
1193
1194 if (RedundantDefaultArg) {
1195 // C++ [temp.param]p12:
1196 // A template-parameter shall not be given default arguments
1197 // by two different declarations in the same scope.
1198 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1199 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1200 Invalid = true;
1201 } else if (MissingDefaultArg) {
1202 // C++ [temp.param]p11:
1203 // If a template-parameter has a default template-argument,
1204 // all subsequent template-parameters shall have a default
1205 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001206 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001207 diag::err_template_param_default_arg_missing);
1208 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1209 Invalid = true;
1210 }
1211
1212 // If we have an old template parameter list that we're merging
1213 // in, move on to the next parameter.
1214 if (OldParams)
1215 ++OldParam;
1216 }
1217
1218 return Invalid;
1219}
Douglas Gregord32e0282009-02-09 23:23:08 +00001220
John McCalla020a012010-10-20 05:44:58 +00001221namespace {
1222
1223/// A class which looks for a use of a certain level of template
1224/// parameter.
1225struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1226 typedef RecursiveASTVisitor<DependencyChecker> super;
1227
1228 unsigned Depth;
1229 bool Match;
1230
1231 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1232 NamedDecl *ND = Params->getParam(0);
1233 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1234 Depth = PD->getDepth();
1235 } else if (NonTypeTemplateParmDecl *PD =
1236 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1237 Depth = PD->getDepth();
1238 } else {
1239 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1240 }
1241 }
1242
1243 bool Matches(unsigned ParmDepth) {
1244 if (ParmDepth >= Depth) {
1245 Match = true;
1246 return true;
1247 }
1248 return false;
1249 }
1250
1251 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1252 return !Matches(T->getDepth());
1253 }
1254
1255 bool TraverseTemplateName(TemplateName N) {
1256 if (TemplateTemplateParmDecl *PD =
1257 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1258 if (Matches(PD->getDepth())) return false;
1259 return super::TraverseTemplateName(N);
1260 }
1261
1262 bool VisitDeclRefExpr(DeclRefExpr *E) {
1263 if (NonTypeTemplateParmDecl *PD =
1264 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1265 if (PD->getDepth() == Depth) {
1266 Match = true;
1267 return false;
1268 }
1269 }
1270 return super::VisitDeclRefExpr(E);
1271 }
1272};
1273}
1274
1275/// Determines whether a template-id depends on the given parameter
1276/// list.
1277static bool
1278DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1279 TemplateParameterList *Params) {
1280 DependencyChecker Checker(Params);
1281 Checker.TraverseType(QualType(TemplateId, 0));
1282 return Checker.Match;
1283}
1284
Mike Stump11289f42009-09-09 15:08:12 +00001285/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001286/// specifier, returning the template parameter list that applies to the
1287/// name.
1288///
1289/// \param DeclStartLoc the start of the declaration that has a scope
1290/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001291///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001292/// \param SS the scope specifier that will be matched to the given template
1293/// parameter lists. This scope specifier precedes a qualified name that is
1294/// being declared.
1295///
1296/// \param ParamLists the template parameter lists, from the outermost to the
1297/// innermost template parameter lists.
1298///
1299/// \param NumParamLists the number of template parameter lists in ParamLists.
1300///
John McCalle820e5e2010-04-13 20:37:33 +00001301/// \param IsFriend Whether to apply the slightly different rules for
1302/// matching template parameters to scope specifiers in friend
1303/// declarations.
1304///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001305/// \param IsExplicitSpecialization will be set true if the entity being
1306/// declared is an explicit specialization, false otherwise.
1307///
Mike Stump11289f42009-09-09 15:08:12 +00001308/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001309/// name that is preceded by the scope specifier @p SS. This template
1310/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001311/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001312/// template specialization), or may be NULL (if we were's declaring isn't
1313/// itself a template).
1314TemplateParameterList *
1315Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1316 const CXXScopeSpec &SS,
1317 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001318 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001319 bool IsFriend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001320 bool &IsExplicitSpecialization,
1321 bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001322 IsExplicitSpecialization = false;
1323
Douglas Gregord8d297c2009-07-21 23:53:31 +00001324 // Find the template-ids that occur within the nested-name-specifier. These
1325 // template-ids will match up with the template parameter lists.
1326 llvm::SmallVector<const TemplateSpecializationType *, 4>
1327 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001328 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1329 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001330 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1331 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001332 const Type *T = NNS->getAsType();
1333 if (!T) break;
1334
1335 // C++0x [temp.expl.spec]p17:
1336 // A member or a member template may be nested within many
1337 // enclosing class templates. In an explicit specialization for
1338 // such a member, the member declaration shall be preceded by a
1339 // template<> for each enclosing class template that is
1340 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001341 //
1342 // Following the existing practice of GNU and EDG, we allow a typedef of a
1343 // template specialization type.
1344 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1345 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001346
Mike Stump11289f42009-09-09 15:08:12 +00001347 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001348 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001349 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1350 if (!Template)
1351 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001352
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001353 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001354 ClassTemplateSpecializationDecl *SpecDecl
1355 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1356 // If the nested name specifier refers to an explicit specialization,
1357 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001358 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1359 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001360 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001361 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001362 }
Mike Stump11289f42009-09-09 15:08:12 +00001363
Douglas Gregord8d297c2009-07-21 23:53:31 +00001364 TemplateIdsInSpecifier.push_back(SpecType);
1365 }
1366 }
Mike Stump11289f42009-09-09 15:08:12 +00001367
Douglas Gregord8d297c2009-07-21 23:53:31 +00001368 // Reverse the list of template-ids in the scope specifier, so that we can
1369 // more easily match up the template-ids and the template parameter lists.
1370 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001371
Douglas Gregord8d297c2009-07-21 23:53:31 +00001372 SourceLocation FirstTemplateLoc = DeclStartLoc;
1373 if (NumParamLists)
1374 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001375
Douglas Gregord8d297c2009-07-21 23:53:31 +00001376 // Match the template-ids found in the specifier to the template parameter
1377 // lists.
John McCalla020a012010-10-20 05:44:58 +00001378 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001379 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCalla020a012010-10-20 05:44:58 +00001380 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1381 const TemplateSpecializationType *TemplateId
1382 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregor15301382009-07-30 17:40:51 +00001383 bool DependentTemplateId = TemplateId->isDependentType();
John McCalla020a012010-10-20 05:44:58 +00001384
1385 // In friend declarations we can have template-ids which don't
1386 // depend on the corresponding template parameter lists. But
1387 // assume that empty parameter lists are supposed to match this
1388 // template-id.
1389 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1390 if (!DependentTemplateId ||
1391 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1392 continue;
1393 }
1394
1395 if (ParamIdx >= NumParamLists) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001396 // We have a template-id without a corresponding template parameter
1397 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001398
1399 // ...which is fine if this is a friend declaration.
1400 if (IsFriend) {
1401 IsExplicitSpecialization = true;
1402 break;
1403 }
1404
Douglas Gregord8d297c2009-07-21 23:53:31 +00001405 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001406 // FIXME: the location information here isn't great.
1407 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001408 diag::err_template_spec_needs_template_parameters)
John McCalla020a012010-10-20 05:44:58 +00001409 << QualType(TemplateId, 0)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001410 << SS.getRange();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001411 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001412 } else {
1413 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1414 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001415 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001416 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001417 }
1418 return 0;
1419 }
Mike Stump11289f42009-09-09 15:08:12 +00001420
Douglas Gregord8d297c2009-07-21 23:53:31 +00001421 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001422 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001423 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001424
John McCall2408e322010-04-27 00:57:59 +00001425 // Are there cases in (e.g.) friends where this won't match?
1426 if (const InjectedClassNameType *Injected
1427 = TemplateId->getAs<InjectedClassNameType>()) {
1428 CXXRecordDecl *Record = Injected->getDecl();
1429 if (ClassTemplatePartialSpecializationDecl *Partial =
1430 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1431 ExpectedTemplateParams = Partial->getTemplateParameters();
1432 else
1433 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1434 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001435 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001436
John McCall2408e322010-04-27 00:57:59 +00001437 if (ExpectedTemplateParams)
John McCalla020a012010-10-20 05:44:58 +00001438 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall2408e322010-04-27 00:57:59 +00001439 ExpectedTemplateParams,
1440 true, TPL_TemplateMatch);
1441
John McCalla020a012010-10-20 05:44:58 +00001442 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1443 TPC_ClassTemplateMember);
1444 } else if (ParamLists[ParamIdx]->size() > 0)
1445 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001446 diag::err_template_param_list_matches_nontemplate)
1447 << TemplateId
John McCalla020a012010-10-20 05:44:58 +00001448 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001449 else
1450 IsExplicitSpecialization = true;
John McCalla020a012010-10-20 05:44:58 +00001451
1452 ++ParamIdx;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001453 }
Mike Stump11289f42009-09-09 15:08:12 +00001454
Douglas Gregord8d297c2009-07-21 23:53:31 +00001455 // If there were at least as many template-ids as there were template
1456 // parameter lists, then there are no template parameter lists remaining for
1457 // the declaration itself.
John McCalla020a012010-10-20 05:44:58 +00001458 if (ParamIdx >= NumParamLists)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001459 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001460
Douglas Gregord8d297c2009-07-21 23:53:31 +00001461 // If there were too many template parameter lists, complain about that now.
John McCalla020a012010-10-20 05:44:58 +00001462 if (ParamIdx != NumParamLists - 1) {
1463 while (ParamIdx < NumParamLists - 1) {
1464 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1465 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001466 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1467 : diag::err_template_spec_extra_headers)
John McCalla020a012010-10-20 05:44:58 +00001468 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1469 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001470
1471 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1472 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1473 diag::note_explicit_template_spec_does_not_need_header)
1474 << ExplicitSpecializationsInSpecifier.back();
1475 ExplicitSpecializationsInSpecifier.pop_back();
1476 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00001477
1478 // We have a template parameter list with no corresponding scope, which
1479 // means that the resulting template declaration can't be instantiated
1480 // properly (we'll end up with dependent nodes when we shouldn't).
1481 if (!isExplicitSpecHeader)
1482 Invalid = true;
1483
John McCalla020a012010-10-20 05:44:58 +00001484 ++ParamIdx;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001485 }
1486 }
Mike Stump11289f42009-09-09 15:08:12 +00001487
Douglas Gregord8d297c2009-07-21 23:53:31 +00001488 // Return the last template parameter list, which corresponds to the
1489 // entity being declared.
1490 return ParamLists[NumParamLists - 1];
1491}
1492
Douglas Gregordc572a32009-03-30 22:58:21 +00001493QualType Sema::CheckTemplateIdType(TemplateName Name,
1494 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001495 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001496 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001497 if (!Template) {
1498 // The template name does not resolve to a template, so we just
1499 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001500 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001501 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001502
Douglas Gregorc40290e2009-03-09 23:48:35 +00001503 // Check that the template argument list is well-formed for this
1504 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001505 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001506 TemplateArgs.size());
1507 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001508 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001509 return QualType();
1510
Mike Stump11289f42009-09-09 15:08:12 +00001511 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001512 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001513 "Converted template argument list is too short!");
1514
1515 QualType CanonType;
1516
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001517 if (Name.isDependent() ||
1518 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001519 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001520 // This class template specialization is a dependent
1521 // type. Therefore, its canonical type is another class template
1522 // specialization type that contains all of the converted
1523 // arguments in canonical form. This ensures that, e.g., A<T> and
1524 // A<T, T> have identical types when A is declared as:
1525 //
1526 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001527 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001528 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001529 Converted.getFlatArguments(),
1530 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001531
Douglas Gregora8e02e72009-07-28 23:00:59 +00001532 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001533 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001534 // In the future, we need to teach getTemplateSpecializationType to only
1535 // build the canonical type and return that to us.
1536 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001537
1538 // This might work out to be a current instantiation, in which
1539 // case the canonical type needs to be the InjectedClassNameType.
1540 //
1541 // TODO: in theory this could be a simple hashtable lookup; most
1542 // changes to CurContext don't change the set of current
1543 // instantiations.
1544 if (isa<ClassTemplateDecl>(Template)) {
1545 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1546 // If we get out to a namespace, we're done.
1547 if (Ctx->isFileContext()) break;
1548
1549 // If this isn't a record, keep looking.
1550 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1551 if (!Record) continue;
1552
1553 // Look for one of the two cases with InjectedClassNameTypes
1554 // and check whether it's the same template.
1555 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1556 !Record->getDescribedClassTemplate())
1557 continue;
1558
1559 // Fetch the injected class name type and check whether its
1560 // injected type is equal to the type we just built.
1561 QualType ICNT = Context.getTypeDeclType(Record);
1562 QualType Injected = cast<InjectedClassNameType>(ICNT)
1563 ->getInjectedSpecializationType();
1564
1565 if (CanonType != Injected->getCanonicalTypeInternal())
1566 continue;
1567
1568 // If so, the canonical type of this TST is the injected
1569 // class name type of the record we just found.
1570 assert(ICNT.isCanonical());
1571 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001572 break;
1573 }
1574 }
Mike Stump11289f42009-09-09 15:08:12 +00001575 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001576 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001577 // Find the class template specialization declaration that
1578 // corresponds to these arguments.
Douglas Gregorc40290e2009-03-09 23:48:35 +00001579 void *InsertPos = 0;
1580 ClassTemplateSpecializationDecl *Decl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001581 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1582 Converted.flatSize(), InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001583 if (!Decl) {
1584 // This is the first time we have referenced this class template
1585 // specialization. Create the canonical declaration and add it to
1586 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001587 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001588 ClassTemplate->getTemplatedDecl()->getTagKind(),
1589 ClassTemplate->getDeclContext(),
1590 ClassTemplate->getLocation(),
1591 ClassTemplate,
1592 Converted, 0);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00001593 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001594 Decl->setLexicalDeclContext(CurContext);
1595 }
1596
1597 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001598 assert(isa<RecordType>(CanonType) &&
1599 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001600 }
Mike Stump11289f42009-09-09 15:08:12 +00001601
Douglas Gregorc40290e2009-03-09 23:48:35 +00001602 // Build the fully-sugared type for this class template
1603 // specialization, which refers back to the class template
1604 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001605 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001606}
1607
John McCallfaf5fb42010-08-26 23:41:50 +00001608TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001609Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001610 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001611 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001612 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001613 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001614
Douglas Gregorc40290e2009-03-09 23:48:35 +00001615 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001616 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001617 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001618
John McCall6b51f282009-11-23 01:53:49 +00001619 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001620 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001621
1622 if (Result.isNull())
1623 return true;
1624
John McCallbcd03502009-12-07 02:54:59 +00001625 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001626 TemplateSpecializationTypeLoc TL
1627 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1628 TL.setTemplateNameLoc(TemplateLoc);
1629 TL.setLAngleLoc(LAngleLoc);
1630 TL.setRAngleLoc(RAngleLoc);
1631 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1632 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1633
John McCallba7bf592010-08-24 05:47:05 +00001634 return CreateParsedType(Result, DI);
John McCalld8fe9af2009-09-08 17:47:29 +00001635}
John McCall06f6fe8d2009-09-04 01:14:41 +00001636
John McCallfaf5fb42010-08-26 23:41:50 +00001637TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1638 TagUseKind TUK,
1639 TypeSpecifierType TagSpec,
1640 SourceLocation TagLoc) {
John McCalld8fe9af2009-09-08 17:47:29 +00001641 if (TypeResult.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00001642 return ::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001643
John McCall0ad16662009-10-29 08:12:44 +00001644 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001645 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001646 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001647
John McCalld8fe9af2009-09-08 17:47:29 +00001648 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001649 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001650
John McCalld8fe9af2009-09-08 17:47:29 +00001651 if (const RecordType *RT = Type->getAs<RecordType>()) {
1652 RecordDecl *D = RT->getDecl();
1653
1654 IdentifierInfo *Id = D->getIdentifier();
1655 assert(Id && "templated class must have an identifier");
1656
1657 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1658 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001659 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001660 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001661 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001662 }
1663 }
1664
Abramo Bagnara6150c882010-05-11 21:36:43 +00001665 ElaboratedTypeKeyword Keyword
1666 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1667 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001668
John McCallba7bf592010-08-24 05:47:05 +00001669 return ParsedType::make(ElabType);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001670}
1671
John McCalldadc5752010-08-24 06:29:42 +00001672ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001673 LookupResult &R,
1674 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001675 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001676 // FIXME: Can we do any checking at this point? I guess we could check the
1677 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001678 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001679 // though.
John McCalle66edc12009-11-24 19:00:30 +00001680
1681 // These should be filtered out by our callers.
1682 assert(!R.empty() && "empty lookup results when building templateid");
1683 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1684
1685 NestedNameSpecifier *Qualifier = 0;
1686 SourceRange QualifierRange;
1687 if (SS.isSet()) {
1688 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1689 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001690 }
John McCall58cc69d2010-01-27 01:50:18 +00001691
1692 // We don't want lookup warnings at this point.
1693 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001694
John McCalle66edc12009-11-24 19:00:30 +00001695 bool Dependent
1696 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1697 &TemplateArgs);
1698 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001699 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001700 Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001701 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001702 RequiresADL, TemplateArgs,
1703 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001704
1705 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001706}
1707
John McCalle66edc12009-11-24 19:00:30 +00001708// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00001709ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001710Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001711 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +00001712 const TemplateArgumentListInfo &TemplateArgs) {
1713 DeclContext *DC;
1714 if (!(DC = computeDeclContext(SS, false)) ||
1715 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001716 RequireCompleteDeclContext(SS, DC))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001717 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001718
Douglas Gregor786123d2010-05-21 23:18:07 +00001719 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001720 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001721 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1722 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001723
John McCalle66edc12009-11-24 19:00:30 +00001724 if (R.isAmbiguous())
1725 return ExprError();
1726
1727 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001728 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1729 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001730 return ExprError();
1731 }
1732
1733 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001734 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1735 << (NestedNameSpecifier*) SS.getScopeRep()
1736 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001737 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1738 return ExprError();
1739 }
1740
1741 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001742}
1743
Douglas Gregorb67535d2009-03-31 00:43:58 +00001744/// \brief Form a dependent template name.
1745///
1746/// This action forms a dependent template name given the template
1747/// name and its (presumably dependent) scope specifier. For
1748/// example, given "MetaFun::template apply", the scope specifier \p
1749/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1750/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregorbb119652010-06-16 23:00:59 +00001751TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1752 SourceLocation TemplateKWLoc,
1753 CXXScopeSpec &SS,
1754 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00001755 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00001756 bool EnteringContext,
1757 TemplateTy &Result) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001758 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1759 !getLangOptions().CPlusPlus0x)
1760 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1761 << FixItHint::CreateRemoval(TemplateKWLoc);
1762
Douglas Gregor9abe2372010-01-19 16:01:07 +00001763 DeclContext *LookupCtx = 0;
1764 if (SS.isSet())
1765 LookupCtx = computeDeclContext(SS, EnteringContext);
1766 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00001767 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00001768 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001769 // C++0x [temp.names]p5:
1770 // If a name prefixed by the keyword template is not the name of
1771 // a template, the program is ill-formed. [Note: the keyword
1772 // template may not be applied to non-template members of class
1773 // templates. -end note ] [ Note: as is the case with the
1774 // typename prefix, the template prefix is allowed in cases
1775 // where it is not strictly necessary; i.e., when the
1776 // nested-name-specifier or the expression on the left of the ->
1777 // or . is not dependent on a template-parameter, or the use
1778 // does not appear in the scope of a template. -end note]
1779 //
1780 // Note: C++03 was more strict here, because it banned the use of
1781 // the "template" keyword prior to a template-name that was not a
1782 // dependent name. C++ DR468 relaxed this requirement (the
1783 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001784 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00001785 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001786 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1787 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00001788 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001789 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1790 isa<CXXRecordDecl>(LookupCtx) &&
1791 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregorbb119652010-06-16 23:00:59 +00001792 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00001793 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001794 Diag(Name.getSourceRange().getBegin(),
1795 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001796 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001797 << Name.getSourceRange()
1798 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001799 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00001800 } else {
1801 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00001802 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001803 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001804 }
1805
Mike Stump11289f42009-09-09 15:08:12 +00001806 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001807 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001808
1809 switch (Name.getKind()) {
1810 case UnqualifiedId::IK_Identifier:
Douglas Gregorbb119652010-06-16 23:00:59 +00001811 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1812 Name.Identifier));
1813 return TNK_Dependent_template_name;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001814
Douglas Gregor71395fa2009-11-04 00:56:37 +00001815 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00001816 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001817 Name.OperatorFunctionId.Operator));
Douglas Gregorbb119652010-06-16 23:00:59 +00001818 return TNK_Dependent_template_name;
Alexis Hunted0530f2009-11-28 08:58:14 +00001819
1820 case UnqualifiedId::IK_LiteralOperatorId:
1821 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1822
Douglas Gregor3cf81312009-11-03 23:16:33 +00001823 default:
1824 break;
1825 }
1826
1827 Diag(Name.getSourceRange().getBegin(),
1828 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001829 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00001830 << Name.getSourceRange()
1831 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00001832 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001833}
1834
Mike Stump11289f42009-09-09 15:08:12 +00001835bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001836 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001837 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001838 const TemplateArgument &Arg = AL.getArgument();
1839
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001840 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001841 switch(Arg.getKind()) {
1842 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001843 // C++ [temp.arg.type]p1:
1844 // A template-argument for a template-parameter which is a
1845 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001846 break;
1847 case TemplateArgument::Template: {
1848 // We have a template type parameter but the template argument
1849 // is a template without any arguments.
1850 SourceRange SR = AL.getSourceRange();
1851 TemplateName Name = Arg.getAsTemplate();
1852 Diag(SR.getBegin(), diag::err_template_missing_args)
1853 << Name << SR;
1854 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1855 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001856
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001857 return true;
1858 }
1859 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001860 // We have a template type parameter but the template argument
1861 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001862 SourceRange SR = AL.getSourceRange();
1863 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001864 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001865
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001866 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001867 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001868 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001869
John McCallbcd03502009-12-07 02:54:59 +00001870 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001871 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001872
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001873 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001874 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001875 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001876 return false;
1877}
1878
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001879/// \brief Substitute template arguments into the default template argument for
1880/// the given template type parameter.
1881///
1882/// \param SemaRef the semantic analysis object for which we are performing
1883/// the substitution.
1884///
1885/// \param Template the template that we are synthesizing template arguments
1886/// for.
1887///
1888/// \param TemplateLoc the location of the template name that started the
1889/// template-id we are checking.
1890///
1891/// \param RAngleLoc the location of the right angle bracket ('>') that
1892/// terminates the template-id.
1893///
1894/// \param Param the template template parameter whose default we are
1895/// substituting into.
1896///
1897/// \param Converted the list of template arguments provided for template
1898/// parameters that precede \p Param in the template parameter list.
1899///
1900/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001901static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001902SubstDefaultTemplateArgument(Sema &SemaRef,
1903 TemplateDecl *Template,
1904 SourceLocation TemplateLoc,
1905 SourceLocation RAngleLoc,
1906 TemplateTypeParmDecl *Param,
1907 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001908 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001909
1910 // If the argument type is dependent, instantiate it now based
1911 // on the previously-computed template arguments.
1912 if (ArgType->getType()->isDependentType()) {
1913 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1914 /*TakeArgs=*/false);
1915
1916 MultiLevelTemplateArgumentList AllTemplateArgs
1917 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1918
1919 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1920 Template, Converted.getFlatArguments(),
1921 Converted.flatSize(),
1922 SourceRange(TemplateLoc, RAngleLoc));
1923
1924 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1925 Param->getDefaultArgumentLoc(),
1926 Param->getDeclName());
1927 }
1928
1929 return ArgType;
1930}
1931
1932/// \brief Substitute template arguments into the default template argument for
1933/// the given non-type template parameter.
1934///
1935/// \param SemaRef the semantic analysis object for which we are performing
1936/// the substitution.
1937///
1938/// \param Template the template that we are synthesizing template arguments
1939/// for.
1940///
1941/// \param TemplateLoc the location of the template name that started the
1942/// template-id we are checking.
1943///
1944/// \param RAngleLoc the location of the right angle bracket ('>') that
1945/// terminates the template-id.
1946///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001947/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001948/// substituting into.
1949///
1950/// \param Converted the list of template arguments provided for template
1951/// parameters that precede \p Param in the template parameter list.
1952///
1953/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00001954static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001955SubstDefaultTemplateArgument(Sema &SemaRef,
1956 TemplateDecl *Template,
1957 SourceLocation TemplateLoc,
1958 SourceLocation RAngleLoc,
1959 NonTypeTemplateParmDecl *Param,
1960 TemplateArgumentListBuilder &Converted) {
1961 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1962 /*TakeArgs=*/false);
1963
1964 MultiLevelTemplateArgumentList AllTemplateArgs
1965 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1966
1967 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1968 Template, Converted.getFlatArguments(),
1969 Converted.flatSize(),
1970 SourceRange(TemplateLoc, RAngleLoc));
1971
1972 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1973}
1974
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001975/// \brief Substitute template arguments into the default template argument for
1976/// the given template template parameter.
1977///
1978/// \param SemaRef the semantic analysis object for which we are performing
1979/// the substitution.
1980///
1981/// \param Template the template that we are synthesizing template arguments
1982/// for.
1983///
1984/// \param TemplateLoc the location of the template name that started the
1985/// template-id we are checking.
1986///
1987/// \param RAngleLoc the location of the right angle bracket ('>') that
1988/// terminates the template-id.
1989///
1990/// \param Param the template template parameter whose default we are
1991/// substituting into.
1992///
1993/// \param Converted the list of template arguments provided for template
1994/// parameters that precede \p Param in the template parameter list.
1995///
1996/// \returns the substituted template argument, or NULL if an error occurred.
1997static TemplateName
1998SubstDefaultTemplateArgument(Sema &SemaRef,
1999 TemplateDecl *Template,
2000 SourceLocation TemplateLoc,
2001 SourceLocation RAngleLoc,
2002 TemplateTemplateParmDecl *Param,
2003 TemplateArgumentListBuilder &Converted) {
2004 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
2005 /*TakeArgs=*/false);
2006
2007 MultiLevelTemplateArgumentList AllTemplateArgs
2008 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2009
2010 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2011 Template, Converted.getFlatArguments(),
2012 Converted.flatSize(),
2013 SourceRange(TemplateLoc, RAngleLoc));
2014
2015 return SemaRef.SubstTemplateName(
2016 Param->getDefaultArgument().getArgument().getAsTemplate(),
2017 Param->getDefaultArgument().getTemplateNameLoc(),
2018 AllTemplateArgs);
2019}
2020
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002021/// \brief If the given template parameter has a default template
2022/// argument, substitute into that default template argument and
2023/// return the corresponding template argument.
2024TemplateArgumentLoc
2025Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2026 SourceLocation TemplateLoc,
2027 SourceLocation RAngleLoc,
2028 Decl *Param,
2029 TemplateArgumentListBuilder &Converted) {
2030 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
2031 if (!TypeParm->hasDefaultArgument())
2032 return TemplateArgumentLoc();
2033
John McCallbcd03502009-12-07 02:54:59 +00002034 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002035 TemplateLoc,
2036 RAngleLoc,
2037 TypeParm,
2038 Converted);
2039 if (DI)
2040 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2041
2042 return TemplateArgumentLoc();
2043 }
2044
2045 if (NonTypeTemplateParmDecl *NonTypeParm
2046 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2047 if (!NonTypeParm->hasDefaultArgument())
2048 return TemplateArgumentLoc();
2049
John McCalldadc5752010-08-24 06:29:42 +00002050 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002051 TemplateLoc,
2052 RAngleLoc,
2053 NonTypeParm,
2054 Converted);
2055 if (Arg.isInvalid())
2056 return TemplateArgumentLoc();
2057
2058 Expr *ArgE = Arg.takeAs<Expr>();
2059 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2060 }
2061
2062 TemplateTemplateParmDecl *TempTempParm
2063 = cast<TemplateTemplateParmDecl>(Param);
2064 if (!TempTempParm->hasDefaultArgument())
2065 return TemplateArgumentLoc();
2066
2067 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2068 TemplateLoc,
2069 RAngleLoc,
2070 TempTempParm,
2071 Converted);
2072 if (TName.isNull())
2073 return TemplateArgumentLoc();
2074
2075 return TemplateArgumentLoc(TemplateArgument(TName),
2076 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2077 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2078}
2079
Douglas Gregorda0fb532009-11-11 19:31:23 +00002080/// \brief Check that the given template argument corresponds to the given
2081/// template parameter.
2082bool Sema::CheckTemplateArgument(NamedDecl *Param,
2083 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002084 TemplateDecl *Template,
2085 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002086 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002087 TemplateArgumentListBuilder &Converted,
2088 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002089 // Check template type parameters.
2090 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002091 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002092
Douglas Gregoreebed722009-11-11 19:41:09 +00002093 // Check non-type template parameters.
2094 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002095 // Do substitution on the type of the non-type template parameter
2096 // with the template arguments we've seen thus far.
2097 QualType NTTPType = NTTP->getType();
2098 if (NTTPType->isDependentType()) {
2099 // Do substitution on the type of the non-type template parameter.
2100 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2101 NTTP, Converted.getFlatArguments(),
2102 Converted.flatSize(),
2103 SourceRange(TemplateLoc, RAngleLoc));
2104
2105 TemplateArgumentList TemplateArgs(Context, Converted,
2106 /*TakeArgs=*/false);
2107 NTTPType = SubstType(NTTPType,
2108 MultiLevelTemplateArgumentList(TemplateArgs),
2109 NTTP->getLocation(),
2110 NTTP->getDeclName());
2111 // If that worked, check the non-type template parameter type
2112 // for validity.
2113 if (!NTTPType.isNull())
2114 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2115 NTTP->getLocation());
2116 if (NTTPType.isNull())
2117 return true;
2118 }
2119
2120 switch (Arg.getArgument().getKind()) {
2121 case TemplateArgument::Null:
2122 assert(false && "Should never see a NULL template argument here");
2123 return true;
2124
2125 case TemplateArgument::Expression: {
2126 Expr *E = Arg.getArgument().getAsExpr();
2127 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002128 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002129 return true;
2130
2131 Converted.Append(Result);
2132 break;
2133 }
2134
2135 case TemplateArgument::Declaration:
2136 case TemplateArgument::Integral:
2137 // We've already checked this template argument, so just copy
2138 // it to the list of converted arguments.
2139 Converted.Append(Arg.getArgument());
2140 break;
2141
2142 case TemplateArgument::Template:
2143 // We were given a template template argument. It may not be ill-formed;
2144 // see below.
2145 if (DependentTemplateName *DTN
2146 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2147 // We have a template argument such as \c T::template X, which we
2148 // parsed as a template template argument. However, since we now
2149 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002150 // template name into an expression.
2151
2152 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2153 Arg.getTemplateNameLoc());
2154
John McCalle66edc12009-11-24 19:00:30 +00002155 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2156 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002157 Arg.getTemplateQualifierRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002158 NameInfo);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002159
2160 TemplateArgument Result;
2161 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2162 return true;
2163
2164 Converted.Append(Result);
2165 break;
2166 }
2167
2168 // We have a template argument that actually does refer to a class
2169 // template, template alias, or template template parameter, and
2170 // therefore cannot be a non-type template argument.
2171 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2172 << Arg.getSourceRange();
2173
2174 Diag(Param->getLocation(), diag::note_template_param_here);
2175 return true;
2176
2177 case TemplateArgument::Type: {
2178 // We have a non-type template parameter but the template
2179 // argument is a type.
2180
2181 // C++ [temp.arg]p2:
2182 // In a template-argument, an ambiguity between a type-id and
2183 // an expression is resolved to a type-id, regardless of the
2184 // form of the corresponding template-parameter.
2185 //
2186 // We warn specifically about this case, since it can be rather
2187 // confusing for users.
2188 QualType T = Arg.getArgument().getAsType();
2189 SourceRange SR = Arg.getSourceRange();
2190 if (T->isFunctionType())
2191 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2192 else
2193 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2194 Diag(Param->getLocation(), diag::note_template_param_here);
2195 return true;
2196 }
2197
2198 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002199 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002200 break;
2201 }
2202
2203 return false;
2204 }
2205
2206
2207 // Check template template parameters.
2208 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2209
2210 // Substitute into the template parameter list of the template
2211 // template parameter, since previously-supplied template arguments
2212 // may appear within the template template parameter.
2213 {
2214 // Set up a template instantiation context.
2215 LocalInstantiationScope Scope(*this);
2216 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2217 TempParm, Converted.getFlatArguments(),
2218 Converted.flatSize(),
2219 SourceRange(TemplateLoc, RAngleLoc));
2220
2221 TemplateArgumentList TemplateArgs(Context, Converted,
2222 /*TakeArgs=*/false);
2223 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2224 SubstDecl(TempParm, CurContext,
2225 MultiLevelTemplateArgumentList(TemplateArgs)));
2226 if (!TempParm)
2227 return true;
2228
2229 // FIXME: TempParam is leaked.
2230 }
2231
2232 switch (Arg.getArgument().getKind()) {
2233 case TemplateArgument::Null:
2234 assert(false && "Should never see a NULL template argument here");
2235 return true;
2236
2237 case TemplateArgument::Template:
2238 if (CheckTemplateArgument(TempParm, Arg))
2239 return true;
2240
2241 Converted.Append(Arg.getArgument());
2242 break;
2243
2244 case TemplateArgument::Expression:
2245 case TemplateArgument::Type:
2246 // We have a template template parameter but the template
2247 // argument does not refer to a template.
2248 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2249 return true;
2250
2251 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002252 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002253 "Declaration argument with template template parameter");
2254 break;
2255 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002256 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002257 "Integral argument with template template parameter");
2258 break;
2259
2260 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002261 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002262 break;
2263 }
2264
2265 return false;
2266}
2267
Douglas Gregord32e0282009-02-09 23:23:08 +00002268/// \brief Check that the given template argument list is well-formed
2269/// for specializing the given template.
2270bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2271 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002272 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002273 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002274 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002275 TemplateParameterList *Params = Template->getTemplateParameters();
2276 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002277 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002278 bool Invalid = false;
2279
John McCall6b51f282009-11-23 01:53:49 +00002280 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2281
Mike Stump11289f42009-09-09 15:08:12 +00002282 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002283 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002284
Anders Carlsson15201f12009-06-13 02:08:00 +00002285 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002286 (NumArgs < Params->getMinRequiredArguments() &&
2287 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002288 // FIXME: point at either the first arg beyond what we can handle,
2289 // or the '>', depending on whether we have too many or too few
2290 // arguments.
2291 SourceRange Range;
2292 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002293 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002294 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2295 << (NumArgs > NumParams)
2296 << (isa<ClassTemplateDecl>(Template)? 0 :
2297 isa<FunctionTemplateDecl>(Template)? 1 :
2298 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2299 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002300 Diag(Template->getLocation(), diag::note_template_decl_here)
2301 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002302 Invalid = true;
2303 }
Mike Stump11289f42009-09-09 15:08:12 +00002304
2305 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002306 // [...] The type and form of each template-argument specified in
2307 // a template-id shall match the type and form specified for the
2308 // corresponding parameter declared by the template in its
2309 // template-parameter-list.
2310 unsigned ArgIdx = 0;
2311 for (TemplateParameterList::iterator Param = Params->begin(),
2312 ParamEnd = Params->end();
2313 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002314 if (ArgIdx > NumArgs && PartialTemplateArgs)
2315 break;
Mike Stump11289f42009-09-09 15:08:12 +00002316
Douglas Gregoreebed722009-11-11 19:41:09 +00002317 // If we have a template parameter pack, check every remaining template
2318 // argument against that template parameter pack.
2319 if ((*Param)->isTemplateParameterPack()) {
2320 Converted.BeginPack();
2321 for (; ArgIdx < NumArgs; ++ArgIdx) {
2322 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2323 TemplateLoc, RAngleLoc, Converted)) {
2324 Invalid = true;
2325 break;
2326 }
2327 }
2328 Converted.EndPack();
2329 continue;
2330 }
2331
Douglas Gregor84d49a22009-11-11 21:54:23 +00002332 if (ArgIdx < NumArgs) {
2333 // Check the template argument we were given.
2334 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2335 TemplateLoc, RAngleLoc, Converted))
2336 return true;
2337
2338 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002339 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002340
Douglas Gregor84d49a22009-11-11 21:54:23 +00002341 // We have a default template argument that we will use.
2342 TemplateArgumentLoc Arg;
2343
2344 // Retrieve the default template argument from the template
2345 // parameter. For each kind of template parameter, we substitute the
2346 // template arguments provided thus far and any "outer" template arguments
2347 // (when the template parameter was part of a nested template) into
2348 // the default argument.
2349 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2350 if (!TTP->hasDefaultArgument()) {
2351 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2352 break;
2353 }
2354
John McCallbcd03502009-12-07 02:54:59 +00002355 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002356 Template,
2357 TemplateLoc,
2358 RAngleLoc,
2359 TTP,
2360 Converted);
2361 if (!ArgType)
2362 return true;
2363
2364 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2365 ArgType);
2366 } else if (NonTypeTemplateParmDecl *NTTP
2367 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2368 if (!NTTP->hasDefaultArgument()) {
2369 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2370 break;
2371 }
2372
John McCalldadc5752010-08-24 06:29:42 +00002373 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002374 TemplateLoc,
2375 RAngleLoc,
2376 NTTP,
2377 Converted);
2378 if (E.isInvalid())
2379 return true;
2380
2381 Expr *Ex = E.takeAs<Expr>();
2382 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2383 } else {
2384 TemplateTemplateParmDecl *TempParm
2385 = cast<TemplateTemplateParmDecl>(*Param);
2386
2387 if (!TempParm->hasDefaultArgument()) {
2388 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2389 break;
2390 }
2391
2392 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2393 TemplateLoc,
2394 RAngleLoc,
2395 TempParm,
2396 Converted);
2397 if (Name.isNull())
2398 return true;
2399
2400 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2401 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2402 TempParm->getDefaultArgument().getTemplateNameLoc());
2403 }
2404
2405 // Introduce an instantiation record that describes where we are using
2406 // the default template argument.
2407 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2408 Converted.getFlatArguments(),
2409 Converted.flatSize(),
2410 SourceRange(TemplateLoc, RAngleLoc));
2411
2412 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002413 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002414 RAngleLoc, Converted))
2415 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002416 }
2417
2418 return Invalid;
2419}
2420
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002421namespace {
2422 class UnnamedLocalNoLinkageFinder
2423 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2424 {
2425 Sema &S;
2426 SourceRange SR;
2427
2428 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2429
2430 public:
2431 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2432
2433 bool Visit(QualType T) {
2434 return inherited::Visit(T.getTypePtr());
2435 }
2436
2437#define TYPE(Class, Parent) \
2438 bool Visit##Class##Type(const Class##Type *);
2439#define ABSTRACT_TYPE(Class, Parent) \
2440 bool Visit##Class##Type(const Class##Type *) { return false; }
2441#define NON_CANONICAL_TYPE(Class, Parent) \
2442 bool Visit##Class##Type(const Class##Type *) { return false; }
2443#include "clang/AST/TypeNodes.def"
2444
2445 bool VisitTagDecl(const TagDecl *Tag);
2446 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2447 };
2448}
2449
2450bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2451 return false;
2452}
2453
2454bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2455 return Visit(T->getElementType());
2456}
2457
2458bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2459 return Visit(T->getPointeeType());
2460}
2461
2462bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2463 const BlockPointerType* T) {
2464 return Visit(T->getPointeeType());
2465}
2466
2467bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2468 const LValueReferenceType* T) {
2469 return Visit(T->getPointeeType());
2470}
2471
2472bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2473 const RValueReferenceType* T) {
2474 return Visit(T->getPointeeType());
2475}
2476
2477bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2478 const MemberPointerType* T) {
2479 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2480}
2481
2482bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2483 const ConstantArrayType* T) {
2484 return Visit(T->getElementType());
2485}
2486
2487bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2488 const IncompleteArrayType* T) {
2489 return Visit(T->getElementType());
2490}
2491
2492bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2493 const VariableArrayType* T) {
2494 return Visit(T->getElementType());
2495}
2496
2497bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2498 const DependentSizedArrayType* T) {
2499 return Visit(T->getElementType());
2500}
2501
2502bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2503 const DependentSizedExtVectorType* T) {
2504 return Visit(T->getElementType());
2505}
2506
2507bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2508 return Visit(T->getElementType());
2509}
2510
2511bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2512 return Visit(T->getElementType());
2513}
2514
2515bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2516 const FunctionProtoType* T) {
2517 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2518 AEnd = T->arg_type_end();
2519 A != AEnd; ++A) {
2520 if (Visit(*A))
2521 return true;
2522 }
2523
2524 return Visit(T->getResultType());
2525}
2526
2527bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2528 const FunctionNoProtoType* T) {
2529 return Visit(T->getResultType());
2530}
2531
2532bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2533 const UnresolvedUsingType*) {
2534 return false;
2535}
2536
2537bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2538 return false;
2539}
2540
2541bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2542 return Visit(T->getUnderlyingType());
2543}
2544
2545bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2546 return false;
2547}
2548
2549bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2550 return VisitTagDecl(T->getDecl());
2551}
2552
2553bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2554 return VisitTagDecl(T->getDecl());
2555}
2556
2557bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2558 const TemplateTypeParmType*) {
2559 return false;
2560}
2561
2562bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2563 const TemplateSpecializationType*) {
2564 return false;
2565}
2566
2567bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2568 const InjectedClassNameType* T) {
2569 return VisitTagDecl(T->getDecl());
2570}
2571
2572bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2573 const DependentNameType* T) {
2574 return VisitNestedNameSpecifier(T->getQualifier());
2575}
2576
2577bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2578 const DependentTemplateSpecializationType* T) {
2579 return VisitNestedNameSpecifier(T->getQualifier());
2580}
2581
2582bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2583 return false;
2584}
2585
2586bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2587 const ObjCInterfaceType *) {
2588 return false;
2589}
2590
2591bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2592 const ObjCObjectPointerType *) {
2593 return false;
2594}
2595
2596bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2597 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2598 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2599 << S.Context.getTypeDeclType(Tag) << SR;
2600 return true;
2601 }
2602
2603 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2604 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2605 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2606 return true;
2607 }
2608
2609 return false;
2610}
2611
2612bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2613 NestedNameSpecifier *NNS) {
2614 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2615 return true;
2616
2617 switch (NNS->getKind()) {
2618 case NestedNameSpecifier::Identifier:
2619 case NestedNameSpecifier::Namespace:
2620 case NestedNameSpecifier::Global:
2621 return false;
2622
2623 case NestedNameSpecifier::TypeSpec:
2624 case NestedNameSpecifier::TypeSpecWithTemplate:
2625 return Visit(QualType(NNS->getAsType(), 0));
2626 }
Fariborz Jahanian26d1e2b2010-10-13 16:19:16 +00002627 return false;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002628}
2629
2630
Douglas Gregord32e0282009-02-09 23:23:08 +00002631/// \brief Check a template argument against its corresponding
2632/// template type parameter.
2633///
2634/// This routine implements the semantics of C++ [temp.arg.type]. It
2635/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002636bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002637 TypeSourceInfo *ArgInfo) {
2638 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002639 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00002640 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00002641
2642 if (Arg->isVariablyModifiedType()) {
2643 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002644 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002645 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002646 }
2647
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002648 // C++03 [temp.arg.type]p2:
2649 // A local type, a type with no linkage, an unnamed type or a type
2650 // compounded from any of these types shall not be used as a
2651 // template-argument for a template type-parameter.
2652 //
2653 // C++0x allows these, and even in C++03 we allow them as an extension with
2654 // a warning.
Douglas Gregor52051cb2010-10-13 18:05:20 +00002655 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00002656 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2657 (void)Finder.Visit(Context.getCanonicalType(Arg));
2658 }
2659
Douglas Gregord32e0282009-02-09 23:23:08 +00002660 return false;
2661}
2662
Douglas Gregorccb07762009-02-11 19:52:55 +00002663/// \brief Checks whether the given template argument is the address
2664/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002665static bool
2666CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2667 NonTypeTemplateParmDecl *Param,
2668 QualType ParamType,
2669 Expr *ArgIn,
2670 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002671 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002672 Expr *Arg = ArgIn;
2673 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002674
2675 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002676 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002677 Arg = Cast->getSubExpr();
2678
2679 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002680 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002681 // A template-argument for a non-type, non-template
2682 // template-parameter shall be one of: [...]
2683 //
2684 // -- the address of an object or function with external
2685 // linkage, including function templates and function
2686 // template-ids but excluding non-static class members,
2687 // expressed as & id-expression where the & is optional if
2688 // the name refers to a function or array, or if the
2689 // corresponding template-parameter is a reference; or
2690 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002691
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002692 // In C++98/03 mode, give an extension warning on any extra parentheses.
2693 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2694 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002695 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002696 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002697 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002698 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002699 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002700 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002701 }
2702
2703 Arg = Parens->getSubExpr();
2704 }
2705
Douglas Gregorb242683d2010-04-01 18:32:35 +00002706 bool AddressTaken = false;
2707 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002708 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002709 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002710 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002711 AddressTaken = true;
2712 AddrOpLoc = UnOp->getOperatorLoc();
2713 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002714 } else
2715 DRE = dyn_cast<DeclRefExpr>(Arg);
2716
Douglas Gregorb242683d2010-04-01 18:32:35 +00002717 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002718 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2719 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002720 S.Diag(Param->getLocation(), diag::note_template_param_here);
2721 return true;
2722 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002723
2724 // Stop checking the precise nature of the argument if it is value dependent,
2725 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002726 if (Arg->isValueDependent()) {
2727 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002728 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002729 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002730
Douglas Gregorb242683d2010-04-01 18:32:35 +00002731 if (!isa<ValueDecl>(DRE->getDecl())) {
2732 S.Diag(Arg->getSourceRange().getBegin(),
2733 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002734 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002735 S.Diag(Param->getLocation(), diag::note_template_param_here);
2736 return true;
2737 }
2738
2739 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002740
2741 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002742 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2743 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002744 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002745 S.Diag(Param->getLocation(), diag::note_template_param_here);
2746 return true;
2747 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002748
2749 // Cannot refer to non-static member functions
2750 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002751 if (!Method->isStatic()) {
2752 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002753 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002754 S.Diag(Param->getLocation(), diag::note_template_param_here);
2755 return true;
2756 }
Mike Stump11289f42009-09-09 15:08:12 +00002757
Douglas Gregorccb07762009-02-11 19:52:55 +00002758 // Functions must have external linkage.
2759 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002760 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002761 S.Diag(Arg->getSourceRange().getBegin(),
2762 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002763 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002764 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002765 << true;
2766 return true;
2767 }
2768
2769 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002770 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002771
Douglas Gregorb242683d2010-04-01 18:32:35 +00002772 // If the template parameter has pointer type, the function decays.
2773 if (ParamType->isPointerType() && !AddressTaken)
2774 ArgType = S.Context.getPointerType(Func->getType());
2775 else if (AddressTaken && ParamType->isReferenceType()) {
2776 // If we originally had an address-of operator, but the
2777 // parameter has reference type, complain and (if things look
2778 // like they will work) drop the address-of operator.
2779 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2780 ParamType.getNonReferenceType())) {
2781 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2782 << ParamType;
2783 S.Diag(Param->getLocation(), diag::note_template_param_here);
2784 return true;
2785 }
2786
2787 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2788 << ParamType
2789 << FixItHint::CreateRemoval(AddrOpLoc);
2790 S.Diag(Param->getLocation(), diag::note_template_param_here);
2791
2792 ArgType = Func->getType();
2793 }
2794 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002795 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002796 S.Diag(Arg->getSourceRange().getBegin(),
2797 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002798 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002799 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002800 << true;
2801 return true;
2802 }
2803
Douglas Gregorb242683d2010-04-01 18:32:35 +00002804 // A value of reference type is not an object.
2805 if (Var->getType()->isReferenceType()) {
2806 S.Diag(Arg->getSourceRange().getBegin(),
2807 diag::err_template_arg_reference_var)
2808 << Var->getType() << Arg->getSourceRange();
2809 S.Diag(Param->getLocation(), diag::note_template_param_here);
2810 return true;
2811 }
2812
Douglas Gregorccb07762009-02-11 19:52:55 +00002813 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002814 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002815
2816 // If the template parameter has pointer type, we must have taken
2817 // the address of this object.
2818 if (ParamType->isReferenceType()) {
2819 if (AddressTaken) {
2820 // If we originally had an address-of operator, but the
2821 // parameter has reference type, complain and (if things look
2822 // like they will work) drop the address-of operator.
2823 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2824 ParamType.getNonReferenceType())) {
2825 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2826 << ParamType;
2827 S.Diag(Param->getLocation(), diag::note_template_param_here);
2828 return true;
2829 }
2830
2831 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2832 << ParamType
2833 << FixItHint::CreateRemoval(AddrOpLoc);
2834 S.Diag(Param->getLocation(), diag::note_template_param_here);
2835
2836 ArgType = Var->getType();
2837 }
2838 } else if (!AddressTaken && ParamType->isPointerType()) {
2839 if (Var->getType()->isArrayType()) {
2840 // Array-to-pointer decay.
2841 ArgType = S.Context.getArrayDecayedType(Var->getType());
2842 } else {
2843 // If the template parameter has pointer type but the address of
2844 // this object was not taken, complain and (possibly) recover by
2845 // taking the address of the entity.
2846 ArgType = S.Context.getPointerType(Var->getType());
2847 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2848 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2849 << ParamType;
2850 S.Diag(Param->getLocation(), diag::note_template_param_here);
2851 return true;
2852 }
2853
2854 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2855 << ParamType
2856 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2857
2858 S.Diag(Param->getLocation(), diag::note_template_param_here);
2859 }
2860 }
2861 } else {
2862 // We found something else, but we don't know specifically what it is.
2863 S.Diag(Arg->getSourceRange().getBegin(),
2864 diag::err_template_arg_not_object_or_func)
2865 << Arg->getSourceRange();
2866 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2867 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002868 }
Mike Stump11289f42009-09-09 15:08:12 +00002869
Douglas Gregorb242683d2010-04-01 18:32:35 +00002870 if (ParamType->isPointerType() &&
2871 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2872 S.IsQualificationConversion(ArgType, ParamType)) {
2873 // For pointer-to-object types, qualification conversions are
2874 // permitted.
2875 } else {
2876 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2877 if (!ParamRef->getPointeeType()->isFunctionType()) {
2878 // C++ [temp.arg.nontype]p5b3:
2879 // For a non-type template-parameter of type reference to
2880 // object, no conversions apply. The type referred to by the
2881 // reference may be more cv-qualified than the (otherwise
2882 // identical) type of the template- argument. The
2883 // template-parameter is bound directly to the
2884 // template-argument, which shall be an lvalue.
2885
2886 // FIXME: Other qualifiers?
2887 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2888 unsigned ArgQuals = ArgType.getCVRQualifiers();
2889
2890 if ((ParamQuals | ArgQuals) != ParamQuals) {
2891 S.Diag(Arg->getSourceRange().getBegin(),
2892 diag::err_template_arg_ref_bind_ignores_quals)
2893 << ParamType << Arg->getType()
2894 << Arg->getSourceRange();
2895 S.Diag(Param->getLocation(), diag::note_template_param_here);
2896 return true;
2897 }
2898 }
2899 }
2900
2901 // At this point, the template argument refers to an object or
2902 // function with external linkage. We now need to check whether the
2903 // argument and parameter types are compatible.
2904 if (!S.Context.hasSameUnqualifiedType(ArgType,
2905 ParamType.getNonReferenceType())) {
2906 // We can't perform this conversion or binding.
2907 if (ParamType->isReferenceType())
2908 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2909 << ParamType << Arg->getType() << Arg->getSourceRange();
2910 else
2911 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2912 << Arg->getType() << ParamType << Arg->getSourceRange();
2913 S.Diag(Param->getLocation(), diag::note_template_param_here);
2914 return true;
2915 }
2916 }
2917
2918 // Create the template argument.
2919 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002920 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002921 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002922}
2923
2924/// \brief Checks whether the given template argument is a pointer to
2925/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002926bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2927 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002928 bool Invalid = false;
2929
2930 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002931 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002932 Arg = Cast->getSubExpr();
2933
2934 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002935 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002936 // A template-argument for a non-type, non-template
2937 // template-parameter shall be one of: [...]
2938 //
2939 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002940 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002941
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002942 // In C++98/03 mode, give an extension warning on any extra parentheses.
2943 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2944 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002945 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002946 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump11289f42009-09-09 15:08:12 +00002947 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002948 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002949 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00002950 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002951 }
2952
2953 Arg = Parens->getSubExpr();
2954 }
2955
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002956 // A pointer-to-member constant written &Class::member.
2957 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00002958 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002959 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2960 if (DRE && !DRE->getQualifier())
2961 DRE = 0;
2962 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002963 }
2964 // A constant of pointer-to-member type.
2965 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2966 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2967 if (VD->getType()->isMemberPointerType()) {
2968 if (isa<NonTypeTemplateParmDecl>(VD) ||
2969 (isa<VarDecl>(VD) &&
2970 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2971 if (Arg->isTypeDependent() || Arg->isValueDependent())
2972 Converted = TemplateArgument(Arg->Retain());
2973 else
2974 Converted = TemplateArgument(VD->getCanonicalDecl());
2975 return Invalid;
2976 }
2977 }
2978 }
2979
2980 DRE = 0;
2981 }
2982
Douglas Gregorccb07762009-02-11 19:52:55 +00002983 if (!DRE)
2984 return Diag(Arg->getSourceRange().getBegin(),
2985 diag::err_template_arg_not_pointer_to_member_form)
2986 << Arg->getSourceRange();
2987
2988 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2989 assert((isa<FieldDecl>(DRE->getDecl()) ||
2990 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2991 "Only non-static member pointers can make it here");
2992
2993 // Okay: this is the address of a non-static member, and therefore
2994 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002995 if (Arg->isTypeDependent() || Arg->isValueDependent())
2996 Converted = TemplateArgument(Arg->Retain());
2997 else
2998 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002999 return Invalid;
3000 }
3001
3002 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00003003 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00003004 diag::err_template_arg_not_pointer_to_member_form)
3005 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003006 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00003007 diag::note_template_arg_refers_here);
3008 return true;
3009}
3010
Douglas Gregord32e0282009-02-09 23:23:08 +00003011/// \brief Check a template argument against its corresponding
3012/// non-type template parameter.
3013///
Douglas Gregor463421d2009-03-03 04:44:36 +00003014/// This routine implements the semantics of C++ [temp.arg.nontype].
3015/// It returns true if an error occurred, and false otherwise. \p
3016/// InstantiatedParamType is the type of the non-type template
3017/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003018///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003019/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00003020bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00003021 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003022 TemplateArgument &Converted,
3023 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00003024 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3025
Douglas Gregor86560402009-02-10 23:36:10 +00003026 // If either the parameter has a dependent type or the argument is
3027 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00003028 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3029 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003030 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00003031 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00003032 }
Douglas Gregor86560402009-02-10 23:36:10 +00003033
3034 // C++ [temp.arg.nontype]p5:
3035 // The following conversions are performed on each expression used
3036 // as a non-type template-argument. If a non-type
3037 // template-argument cannot be converted to the type of the
3038 // corresponding template-parameter then the program is
3039 // ill-formed.
3040 //
3041 // -- for a non-type template-parameter of integral or
3042 // enumeration type, integral promotions (4.5) and integral
3043 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00003044 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003045 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00003046 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00003047 // C++ [temp.arg.nontype]p1:
3048 // A template-argument for a non-type, non-template
3049 // template-parameter shall be one of:
3050 //
3051 // -- an integral constant-expression of integral or enumeration
3052 // type; or
3053 // -- the name of a non-type template-parameter; or
3054 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003055 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00003056 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003057 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00003058 diag::err_template_arg_not_integral_or_enumeral)
3059 << ArgType << Arg->getSourceRange();
3060 Diag(Param->getLocation(), diag::note_template_param_here);
3061 return true;
3062 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003063 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00003064 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3065 << ArgType << Arg->getSourceRange();
3066 return true;
3067 }
3068
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003069 // From here on out, all we care about are the unqualified forms
3070 // of the parameter and argument types.
3071 ParamType = ParamType.getUnqualifiedType();
3072 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00003073
3074 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00003075 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00003076 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003077 } else if (CTAK == CTAK_Deduced) {
3078 // C++ [temp.deduct.type]p17:
3079 // If, in the declaration of a function template with a non-type
3080 // template-parameter, the non-type template- parameter is used
3081 // in an expression in the function parameter-list and, if the
3082 // corresponding template-argument is deduced, the
3083 // template-argument type shall match the type of the
3084 // template-parameter exactly, except that a template-argument
3085 // deduced from an array bound may be of any integral type.
3086 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3087 << ArgType << ParamType;
3088 Diag(Param->getLocation(), diag::note_template_param_here);
3089 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00003090 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3091 !ParamType->isEnumeralType()) {
3092 // This is an integral promotion or conversion.
John McCalle3027922010-08-25 11:45:40 +00003093 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00003094 } else {
3095 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003096 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00003097 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003098 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00003099 Diag(Param->getLocation(), diag::note_template_param_here);
3100 return true;
3101 }
3102
Douglas Gregor52aba872009-03-14 00:20:21 +00003103 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00003104 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003105 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00003106
3107 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00003108 llvm::APSInt OldValue = Value;
3109
3110 // Coerce the template argument's value to the value it will have
3111 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003112 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00003113 if (Value.getBitWidth() != AllowedBits)
3114 Value.extOrTrunc(AllowedBits);
3115 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00003116
3117 // Complain if an unsigned parameter received a negative value.
3118 if (IntegerType->isUnsignedIntegerType()
3119 && (OldValue.isSigned() && OldValue.isNegative())) {
3120 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3121 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3122 << Arg->getSourceRange();
3123 Diag(Param->getLocation(), diag::note_template_param_here);
3124 }
3125
3126 // Complain if we overflowed the template parameter's type.
3127 unsigned RequiredBits;
3128 if (IntegerType->isUnsignedIntegerType())
3129 RequiredBits = OldValue.getActiveBits();
3130 else if (OldValue.isUnsigned())
3131 RequiredBits = OldValue.getActiveBits() + 1;
3132 else
3133 RequiredBits = OldValue.getMinSignedBits();
3134 if (RequiredBits > AllowedBits) {
3135 Diag(Arg->getSourceRange().getBegin(),
3136 diag::warn_template_arg_too_large)
3137 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3138 << Arg->getSourceRange();
3139 Diag(Param->getLocation(), diag::note_template_param_here);
3140 }
Douglas Gregor52aba872009-03-14 00:20:21 +00003141 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003142
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003143 // Add the value of this argument to the list of converted
3144 // arguments. We use the bitwidth and signedness of the template
3145 // parameter.
3146 if (Arg->isValueDependent()) {
3147 // The argument is value-dependent. Create a new
3148 // TemplateArgument with the converted expression.
3149 Converted = TemplateArgument(Arg);
3150 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003151 }
3152
John McCall0ad16662009-10-29 08:12:44 +00003153 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00003154 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00003155 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00003156 return false;
3157 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003158
John McCall16df1e52010-03-30 21:47:33 +00003159 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3160
Douglas Gregorb242683d2010-04-01 18:32:35 +00003161 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3162 // from a template argument of type std::nullptr_t to a non-type
3163 // template parameter of type pointer to object, pointer to
3164 // function, or pointer-to-member, respectively.
3165 if (ArgType->isNullPtrType() &&
3166 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3167 Converted = TemplateArgument((NamedDecl *)0);
3168 return false;
3169 }
3170
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003171 // Handle pointer-to-function, reference-to-function, and
3172 // pointer-to-member-function all in (roughly) the same way.
3173 if (// -- For a non-type template-parameter of type pointer to
3174 // function, only the function-to-pointer conversion (4.3) is
3175 // applied. If the template-argument represents a set of
3176 // overloaded functions (or a pointer to such), the matching
3177 // function is selected from the set (13.4).
3178 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003179 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003180 // -- For a non-type template-parameter of type reference to
3181 // function, no conversions apply. If the template-argument
3182 // represents a set of overloaded functions, the matching
3183 // function is selected from the set (13.4).
3184 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003185 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003186 // -- For a non-type template-parameter of type pointer to
3187 // member function, no conversions apply. If the
3188 // template-argument represents a set of overloaded member
3189 // functions, the matching member function is selected from
3190 // the set (13.4).
3191 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003192 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003193 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003194
Douglas Gregor064fdb22010-04-14 23:11:21 +00003195 if (Arg->getType() == Context.OverloadTy) {
3196 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3197 true,
3198 FoundResult)) {
3199 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3200 return true;
3201
3202 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3203 ArgType = Arg->getType();
3204 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00003205 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003206 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00003207
Douglas Gregorb242683d2010-04-01 18:32:35 +00003208 if (!ParamType->isMemberPointerType())
3209 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3210 ParamType,
3211 Arg, Converted);
3212
3213 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCalle3027922010-08-25 11:45:40 +00003214 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb242683d2010-04-01 18:32:35 +00003215 } else if (!Context.hasSameUnqualifiedType(ArgType,
3216 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003217 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003218 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003219 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003220 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003221 Diag(Param->getLocation(), diag::note_template_param_here);
3222 return true;
3223 }
Mike Stump11289f42009-09-09 15:08:12 +00003224
Douglas Gregorb242683d2010-04-01 18:32:35 +00003225 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00003226 }
3227
Chris Lattner696197c2009-02-20 21:37:53 +00003228 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003229 // -- for a non-type template-parameter of type pointer to
3230 // object, qualification conversions (4.4) and the
3231 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00003232 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00003233 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003234 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00003235
Douglas Gregorb242683d2010-04-01 18:32:35 +00003236 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3237 ParamType,
3238 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00003239 }
Mike Stump11289f42009-09-09 15:08:12 +00003240
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003241 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003242 // -- For a non-type template-parameter of type reference to
3243 // object, no conversions apply. The type referred to by the
3244 // reference may be more cv-qualified than the (otherwise
3245 // identical) type of the template-argument. The
3246 // template-parameter is bound directly to the
3247 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00003248 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003249 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00003250
Douglas Gregor064fdb22010-04-14 23:11:21 +00003251 if (Arg->getType() == Context.OverloadTy) {
3252 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3253 ParamRefType->getPointeeType(),
3254 true,
3255 FoundResult)) {
3256 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3257 return true;
3258
3259 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3260 ArgType = Arg->getType();
3261 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00003262 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003263 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00003264
Douglas Gregorb242683d2010-04-01 18:32:35 +00003265 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3266 ParamType,
3267 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00003268 }
Douglas Gregor0e558532009-02-11 16:16:59 +00003269
3270 // -- For a non-type template-parameter of type pointer to data
3271 // member, qualification conversions (4.4) are applied.
3272 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3273
Douglas Gregor1515f762009-02-11 18:22:40 +00003274 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00003275 // Types match exactly: nothing more to do here.
3276 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCalle3027922010-08-25 11:45:40 +00003277 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor0e558532009-02-11 16:16:59 +00003278 } else {
3279 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003280 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00003281 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003282 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00003283 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003284 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003285 }
3286
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003287 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003288}
3289
3290/// \brief Check a template argument against its corresponding
3291/// template template parameter.
3292///
3293/// This routine implements the semantics of C++ [temp.arg.template].
3294/// It returns true if an error occurred, and false otherwise.
3295bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003296 const TemplateArgumentLoc &Arg) {
3297 TemplateName Name = Arg.getArgument().getAsTemplate();
3298 TemplateDecl *Template = Name.getAsTemplateDecl();
3299 if (!Template) {
3300 // Any dependent template name is fine.
3301 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3302 return false;
3303 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003304
3305 // C++ [temp.arg.template]p1:
3306 // A template-argument for a template template-parameter shall be
3307 // the name of a class template, expressed as id-expression. Only
3308 // primary class templates are considered when matching the
3309 // template template argument with the corresponding parameter;
3310 // partial specializations are not considered even if their
3311 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003312 //
3313 // Note that we also allow template template parameters here, which
3314 // will happen when we are dealing with, e.g., class template
3315 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003316 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003317 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003318 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003319 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003320 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003321 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003322 << Template;
3323 }
3324
3325 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3326 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003327 true,
3328 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003329 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003330}
3331
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003332/// \brief Given a non-type template argument that refers to a
3333/// declaration and the type of its corresponding non-type template
3334/// parameter, produce an expression that properly refers to that
3335/// declaration.
John McCalldadc5752010-08-24 06:29:42 +00003336ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003337Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3338 QualType ParamType,
3339 SourceLocation Loc) {
3340 assert(Arg.getKind() == TemplateArgument::Declaration &&
3341 "Only declaration template arguments permitted here");
3342 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3343
3344 if (VD->getDeclContext()->isRecord() &&
3345 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3346 // If the value is a class member, we might have a pointer-to-member.
3347 // Determine whether the non-type template template parameter is of
3348 // pointer-to-member type. If so, we need to build an appropriate
3349 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3350 // would refer to the member itself.
3351 if (ParamType->isMemberPointerType()) {
3352 QualType ClassType
3353 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3354 NestedNameSpecifier *Qualifier
John McCallb268a282010-08-23 23:25:46 +00003355 = NestedNameSpecifier::Create(Context, 0, false,
3356 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003357 CXXScopeSpec SS;
3358 SS.setScopeRep(Qualifier);
John McCalldadc5752010-08-24 06:29:42 +00003359 ExprResult RefExpr = BuildDeclRefExpr(VD,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003360 VD->getType().getNonReferenceType(),
3361 Loc,
3362 &SS);
3363 if (RefExpr.isInvalid())
3364 return ExprError();
3365
John McCalle3027922010-08-25 11:45:40 +00003366 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003367
3368 // We might need to perform a trailing qualification conversion, since
3369 // the element type on the parameter could be more qualified than the
3370 // element type in the expression we constructed.
3371 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3372 ParamType.getUnqualifiedType())) {
3373 Expr *RefE = RefExpr.takeAs<Expr>();
John McCalle3027922010-08-25 11:45:40 +00003374 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003375 RefExpr = Owned(RefE);
3376 }
3377
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003378 assert(!RefExpr.isInvalid() &&
3379 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003380 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003381 return move(RefExpr);
3382 }
3383 }
3384
3385 QualType T = VD->getType().getNonReferenceType();
3386 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003387 // When the non-type template parameter is a pointer, take the
3388 // address of the declaration.
John McCalldadc5752010-08-24 06:29:42 +00003389 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003390 if (RefExpr.isInvalid())
3391 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003392
3393 if (T->isFunctionType() || T->isArrayType()) {
3394 // Decay functions and arrays.
3395 Expr *RefE = (Expr *)RefExpr.get();
3396 DefaultFunctionArrayConversion(RefE);
3397 if (RefE != RefExpr.get()) {
3398 RefExpr.release();
3399 RefExpr = Owned(RefE);
3400 }
3401
3402 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003403 }
3404
Douglas Gregorb242683d2010-04-01 18:32:35 +00003405 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00003406 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003407 }
3408
3409 // If the non-type template parameter has reference type, qualify the
3410 // resulting declaration reference with the extra qualifiers on the
3411 // type that the reference refers to.
3412 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3413 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3414
3415 return BuildDeclRefExpr(VD, T, Loc);
3416}
3417
3418/// \brief Construct a new expression that refers to the given
3419/// integral template argument with the given source-location
3420/// information.
3421///
3422/// This routine takes care of the mapping from an integral template
3423/// argument (which may have any integral type) to the appropriate
3424/// literal value.
John McCalldadc5752010-08-24 06:29:42 +00003425ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003426Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3427 SourceLocation Loc) {
3428 assert(Arg.getKind() == TemplateArgument::Integral &&
3429 "Operation is only value for integral template arguments");
3430 QualType T = Arg.getIntegralType();
3431 if (T->isCharType() || T->isWideCharType())
3432 return Owned(new (Context) CharacterLiteral(
3433 Arg.getAsIntegral()->getZExtValue(),
3434 T->isWideCharType(),
3435 T,
3436 Loc));
3437 if (T->isBooleanType())
3438 return Owned(new (Context) CXXBoolLiteralExpr(
3439 Arg.getAsIntegral()->getBoolValue(),
3440 T,
3441 Loc));
3442
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003443 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003444}
3445
3446
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003447/// \brief Determine whether the given template parameter lists are
3448/// equivalent.
3449///
Mike Stump11289f42009-09-09 15:08:12 +00003450/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003451/// source code as part of a new template declaration.
3452///
3453/// \param Old The old template parameter list, typically found via
3454/// name lookup of the template declared with this template parameter
3455/// list.
3456///
3457/// \param Complain If true, this routine will produce a diagnostic if
3458/// the template parameter lists are not equivalent.
3459///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003460/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003461///
3462/// \param TemplateArgLoc If this source location is valid, then we
3463/// are actually checking the template parameter list of a template
3464/// argument (New) against the template parameter list of its
3465/// corresponding template template parameter (Old). We produce
3466/// slightly different diagnostics in this scenario.
3467///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003468/// \returns True if the template parameter lists are equal, false
3469/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003470bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003471Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3472 TemplateParameterList *Old,
3473 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003474 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003475 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003476 if (Old->size() != New->size()) {
3477 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003478 unsigned NextDiag = diag::err_template_param_list_different_arity;
3479 if (TemplateArgLoc.isValid()) {
3480 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3481 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003482 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003483 Diag(New->getTemplateLoc(), NextDiag)
3484 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003485 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003486 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003487 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003488 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003489 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3490 }
3491
3492 return false;
3493 }
3494
3495 for (TemplateParameterList::iterator OldParm = Old->begin(),
3496 OldParmEnd = Old->end(), NewParm = New->begin();
3497 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3498 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003499 if (Complain) {
3500 unsigned NextDiag = diag::err_template_param_different_kind;
3501 if (TemplateArgLoc.isValid()) {
3502 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3503 NextDiag = diag::note_template_param_different_kind;
3504 }
3505 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003506 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003507 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003508 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003509 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003510 return false;
3511 }
3512
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003513 if (TemplateTypeParmDecl *OldTTP
3514 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3515 // Template type parameters are equivalent if either both are template
3516 // type parameter packs or neither are (since we know we're at the same
3517 // index).
3518 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3519 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3520 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3521 // allow one to match a template parameter pack in the template
3522 // parameter list of a template template parameter to one or more
3523 // template parameters in the template parameter list of the
3524 // corresponding template template argument.
3525 if (Complain) {
3526 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3527 if (TemplateArgLoc.isValid()) {
3528 Diag(TemplateArgLoc,
3529 diag::err_template_arg_template_params_mismatch);
3530 NextDiag = diag::note_template_parameter_pack_non_pack;
3531 }
3532 Diag(NewTTP->getLocation(), NextDiag)
3533 << 0 << NewTTP->isParameterPack();
3534 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3535 << 0 << OldTTP->isParameterPack();
3536 }
3537 return false;
3538 }
Mike Stump11289f42009-09-09 15:08:12 +00003539 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003540 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3541 // The types of non-type template parameters must agree.
3542 NonTypeTemplateParmDecl *NewNTTP
3543 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003544
3545 // If we are matching a template template argument to a template
3546 // template parameter and one of the non-type template parameter types
3547 // is dependent, then we must wait until template instantiation time
3548 // to actually compare the arguments.
3549 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3550 (OldNTTP->getType()->isDependentType() ||
3551 NewNTTP->getType()->isDependentType()))
3552 continue;
3553
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003554 if (Context.getCanonicalType(OldNTTP->getType()) !=
3555 Context.getCanonicalType(NewNTTP->getType())) {
3556 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003557 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3558 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003559 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003560 diag::err_template_arg_template_params_mismatch);
3561 NextDiag = diag::note_template_nontype_parm_different_type;
3562 }
3563 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003564 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003565 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003566 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003567 diag::note_template_nontype_parm_prev_declaration)
3568 << OldNTTP->getType();
3569 }
3570 return false;
3571 }
3572 } else {
3573 // The template parameter lists of template template
3574 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003575 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003576 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003577 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003578 = cast<TemplateTemplateParmDecl>(*OldParm);
3579 TemplateTemplateParmDecl *NewTTP
3580 = cast<TemplateTemplateParmDecl>(*NewParm);
3581 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3582 OldTTP->getTemplateParameters(),
3583 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003584 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003585 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003586 return false;
3587 }
3588 }
3589
3590 return true;
3591}
3592
3593/// \brief Check whether a template can be declared within this scope.
3594///
3595/// If the template declaration is valid in this scope, returns
3596/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003597bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003598Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003599 // Find the nearest enclosing declaration scope.
3600 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3601 (S->getFlags() & Scope::TemplateParamScope) != 0)
3602 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003603
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003604 // C++ [temp]p2:
3605 // A template-declaration can appear only as a namespace scope or
3606 // class scope declaration.
3607 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003608 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3609 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003610 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003611 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003612
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003613 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003614 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003615
3616 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3617 return false;
3618
Mike Stump11289f42009-09-09 15:08:12 +00003619 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003620 diag::err_template_outside_namespace_or_class_scope)
3621 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003622}
Douglas Gregor67a65642009-02-17 23:15:12 +00003623
Douglas Gregor54888652009-10-07 00:13:32 +00003624/// \brief Determine what kind of template specialization the given declaration
3625/// is.
3626static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3627 if (!D)
3628 return TSK_Undeclared;
3629
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003630 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3631 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003632 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3633 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003634 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3635 return Var->getTemplateSpecializationKind();
3636
Douglas Gregor54888652009-10-07 00:13:32 +00003637 return TSK_Undeclared;
3638}
3639
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003640/// \brief Check whether a specialization is well-formed in the current
3641/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003642///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003643/// This routine determines whether a template specialization can be declared
3644/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003645///
3646/// \param S the semantic analysis object for which this check is being
3647/// performed.
3648///
3649/// \param Specialized the entity being specialized or instantiated, which
3650/// may be a kind of template (class template, function template, etc.) or
3651/// a member of a class template (member function, static data member,
3652/// member class).
3653///
3654/// \param PrevDecl the previous declaration of this entity, if any.
3655///
3656/// \param Loc the location of the explicit specialization or instantiation of
3657/// this entity.
3658///
3659/// \param IsPartialSpecialization whether this is a partial specialization of
3660/// a class template.
3661///
Douglas Gregor54888652009-10-07 00:13:32 +00003662/// \returns true if there was an error that we cannot recover from, false
3663/// otherwise.
3664static bool CheckTemplateSpecializationScope(Sema &S,
3665 NamedDecl *Specialized,
3666 NamedDecl *PrevDecl,
3667 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003668 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003669 // Keep these "kind" numbers in sync with the %select statements in the
3670 // various diagnostics emitted by this routine.
3671 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003672 bool isTemplateSpecialization = false;
3673 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003674 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003675 isTemplateSpecialization = true;
3676 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003677 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003678 isTemplateSpecialization = true;
3679 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003680 EntityKind = 3;
3681 else if (isa<VarDecl>(Specialized))
3682 EntityKind = 4;
3683 else if (isa<RecordDecl>(Specialized))
3684 EntityKind = 5;
3685 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003686 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3687 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003688 return true;
3689 }
3690
Douglas Gregorf47b9112009-02-25 22:02:03 +00003691 // C++ [temp.expl.spec]p2:
3692 // An explicit specialization shall be declared in the namespace
3693 // of which the template is a member, or, for member templates, in
3694 // the namespace of which the enclosing class or enclosing class
3695 // template is a member. An explicit specialization of a member
3696 // function, member class or static data member of a class
3697 // template shall be declared in the namespace of which the class
3698 // template is a member. Such a declaration may also be a
3699 // definition. If the declaration is not a definition, the
3700 // specialization may be defined later in the name- space in which
3701 // the explicit specialization was declared, or in a namespace
3702 // that encloses the one in which the explicit specialization was
3703 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00003704 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00003705 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003706 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003707 return true;
3708 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003709
Douglas Gregor40fb7442009-10-07 17:30:37 +00003710 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3711 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003712 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003713 return true;
3714 }
3715
Douglas Gregore4b05162009-10-07 17:21:34 +00003716 // C++ [temp.class.spec]p6:
3717 // A class template partial specialization may be declared or redeclared
3718 // in any namespace scope in which its definition may be defined (14.5.1
3719 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003720 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003721 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003722 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003723 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003724 if ((!PrevDecl ||
3725 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3726 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregorb1aab432010-09-12 05:08:28 +00003727 // C++ [temp.exp.spec]p2:
3728 // An explicit specialization shall be declared in the namespace of which
3729 // the template is a member, or, for member templates, in the namespace
3730 // of which the enclosing class or enclosing class template is a member.
3731 // An explicit specialization of a member function, member class or
3732 // static data member of a class template shall be declared in the
3733 // namespace of which the class template is a member.
3734 //
3735 // C++0x [temp.expl.spec]p2:
3736 // An explicit specialization shall be declared in a namespace enclosing
3737 // the specialized template.
3738 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3739 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregor8ce63152010-09-12 05:24:55 +00003740 bool IsCPlusPlus0xExtension
3741 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003742 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003743 S.Diag(Loc, IsCPlusPlus0xExtension
3744 ? diag::ext_template_spec_decl_out_of_scope_global
3745 : diag::err_template_spec_decl_out_of_scope_global)
3746 << EntityKind << Specialized;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003747 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregor8ce63152010-09-12 05:24:55 +00003748 S.Diag(Loc, IsCPlusPlus0xExtension
3749 ? diag::ext_template_spec_decl_out_of_scope
3750 : diag::err_template_spec_decl_out_of_scope)
3751 << EntityKind << Specialized
3752 << cast<NamedDecl>(SpecializedContext);
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003753
3754 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3755 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003756 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003757 }
Douglas Gregor54888652009-10-07 00:13:32 +00003758
3759 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003760 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003761 // Note that HandleDeclarator() performs this check for explicit
3762 // specializations of function templates, static data members, and member
3763 // functions, so we skip the check here for those kinds of entities.
3764 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003765 // Should we refactor that check, so that it occurs later?
3766 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003767 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3768 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003769 if (isa<TranslationUnitDecl>(SpecializedContext))
3770 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3771 << EntityKind << Specialized;
3772 else if (isa<NamespaceDecl>(SpecializedContext))
3773 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3774 << EntityKind << Specialized
3775 << cast<NamedDecl>(SpecializedContext);
3776
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003777 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003778 }
Douglas Gregor54888652009-10-07 00:13:32 +00003779
3780 // FIXME: check for specialization-after-instantiation errors and such.
3781
Douglas Gregorf47b9112009-02-25 22:02:03 +00003782 return false;
3783}
Douglas Gregor54888652009-10-07 00:13:32 +00003784
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003785/// \brief Check the non-type template arguments of a class template
3786/// partial specialization according to C++ [temp.class.spec]p9.
3787///
Douglas Gregor09a30232009-06-12 22:08:06 +00003788/// \param TemplateParams the template parameters of the primary class
3789/// template.
3790///
3791/// \param TemplateArg the template arguments of the class template
3792/// partial specialization.
3793///
3794/// \param MirrorsPrimaryTemplate will be set true if the class
3795/// template partial specialization arguments are identical to the
3796/// implicit template arguments of the primary template. This is not
3797/// necessarily an error (C++0x), and it is left to the caller to diagnose
3798/// this condition when it is an error.
3799///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003800/// \returns true if there was an error, false otherwise.
3801bool Sema::CheckClassTemplatePartialSpecializationArgs(
3802 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003803 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003804 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003805 // FIXME: the interface to this function will have to change to
3806 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003807 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003808
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003809 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003810
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003811 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003812 // Determine whether the template argument list of the partial
3813 // specialization is identical to the implicit argument list of
3814 // the primary template. The caller may need to diagnostic this as
3815 // an error per C++ [temp.class.spec]p9b3.
3816 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003817 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003818 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3819 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003820 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003821 MirrorsPrimaryTemplate = false;
3822 } else if (TemplateTemplateParmDecl *TTP
3823 = dyn_cast<TemplateTemplateParmDecl>(
3824 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003825 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003826 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003827 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003828 if (!ArgDecl ||
3829 ArgDecl->getIndex() != TTP->getIndex() ||
3830 ArgDecl->getDepth() != TTP->getDepth())
3831 MirrorsPrimaryTemplate = false;
3832 }
3833 }
3834
Mike Stump11289f42009-09-09 15:08:12 +00003835 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003836 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003837 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003838 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003839 }
3840
Anders Carlsson40c1d492009-06-13 18:20:51 +00003841 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003842 if (!ArgExpr) {
3843 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003844 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003845 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003846
3847 // C++ [temp.class.spec]p8:
3848 // A non-type argument is non-specialized if it is the name of a
3849 // non-type parameter. All other non-type arguments are
3850 // specialized.
3851 //
3852 // Below, we check the two conditions that only apply to
3853 // specialized non-type arguments, so skip any non-specialized
3854 // arguments.
3855 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003856 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003857 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003858 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003859 (Param->getIndex() != NTTP->getIndex() ||
3860 Param->getDepth() != NTTP->getDepth()))
3861 MirrorsPrimaryTemplate = false;
3862
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003863 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003864 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003865
3866 // C++ [temp.class.spec]p9:
3867 // Within the argument list of a class template partial
3868 // specialization, the following restrictions apply:
3869 // -- A partially specialized non-type argument expression
3870 // shall not involve a template parameter of the partial
3871 // specialization except when the argument expression is a
3872 // simple identifier.
3873 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003874 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003875 diag::err_dependent_non_type_arg_in_partial_spec)
3876 << ArgExpr->getSourceRange();
3877 return true;
3878 }
3879
3880 // -- The type of a template parameter corresponding to a
3881 // specialized non-type argument shall not be dependent on a
3882 // parameter of the specialization.
3883 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003884 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003885 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3886 << Param->getType()
3887 << ArgExpr->getSourceRange();
3888 Diag(Param->getLocation(), diag::note_template_param_here);
3889 return true;
3890 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003891
3892 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003893 }
3894
3895 return false;
3896}
3897
Douglas Gregorc854c662010-02-26 06:03:23 +00003898/// \brief Retrieve the previous declaration of the given declaration.
3899static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3900 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3901 return VD->getPreviousDeclaration();
3902 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3903 return FD->getPreviousDeclaration();
3904 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3905 return TD->getPreviousDeclaration();
3906 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3907 return TD->getPreviousDeclaration();
3908 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3909 return FTD->getPreviousDeclaration();
3910 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3911 return CTD->getPreviousDeclaration();
3912 return 0;
3913}
3914
John McCall48871652010-08-21 09:40:31 +00003915DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003916Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3917 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003918 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003919 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003920 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003921 SourceLocation TemplateNameLoc,
3922 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003923 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003924 SourceLocation RAngleLoc,
3925 AttributeList *Attr,
3926 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003927 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003928
Douglas Gregor67a65642009-02-17 23:15:12 +00003929 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003930 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003931 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003932 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3933
3934 if (!ClassTemplate) {
3935 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3936 << (Name.getAsTemplateDecl() &&
3937 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3938 return true;
3939 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003940
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003941 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003942 bool isPartialSpecialization = false;
3943
Douglas Gregorf47b9112009-02-25 22:02:03 +00003944 // Check the validity of the template headers that introduce this
3945 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003946 // FIXME: We probably shouldn't complain about these headers for
3947 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003948 bool Invalid = false;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003949 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003950 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3951 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003952 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003953 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003954 isExplicitSpecialization,
3955 Invalid);
3956 if (Invalid)
3957 return true;
3958
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003959 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3960 if (TemplateParams)
3961 --NumMatchedTemplateParamLists;
3962
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003963 if (TemplateParams && TemplateParams->size() > 0) {
3964 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003965
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003966 // C++ [temp.class.spec]p10:
3967 // The template parameter list of a specialization shall not
3968 // contain default template argument values.
3969 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3970 Decl *Param = TemplateParams->getParam(I);
3971 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3972 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003973 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003974 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003975 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003976 }
3977 } else if (NonTypeTemplateParmDecl *NTTP
3978 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3979 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003980 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003981 diag::err_default_arg_in_partial_spec)
3982 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003983 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003984 }
3985 } else {
3986 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003987 if (TTP->hasDefaultArgument()) {
3988 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003989 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003990 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003991 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003992 }
3993 }
3994 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003995 } else if (TemplateParams) {
3996 if (TUK == TUK_Friend)
3997 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003998 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003999 SourceRange(TemplateParams->getTemplateLoc(),
4000 TemplateParams->getRAngleLoc()))
4001 << SourceRange(LAngleLoc, RAngleLoc);
4002 else
4003 isExplicitSpecialization = true;
4004 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004005 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00004006 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004007 isExplicitSpecialization = true;
4008 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00004009
Douglas Gregor67a65642009-02-17 23:15:12 +00004010 // Check that the specialization uses the same tag kind as the
4011 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004012 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4013 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004014 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004015 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004016 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004017 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00004018 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004019 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00004020 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004021 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00004022 diag::note_previous_use);
4023 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4024 }
4025
Douglas Gregorc40290e2009-03-09 23:48:35 +00004026 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004027 TemplateArgumentListInfo TemplateArgs;
4028 TemplateArgs.setLAngleLoc(LAngleLoc);
4029 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004030 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00004031
Douglas Gregor67a65642009-02-17 23:15:12 +00004032 // Check that the template argument list is well-formed for this
4033 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004034 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4035 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004036 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4037 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00004038 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00004039
Mike Stump11289f42009-09-09 15:08:12 +00004040 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00004041 ClassTemplate->getTemplateParameters()->size()) &&
4042 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004043
Douglas Gregor2373c592009-05-31 09:31:02 +00004044 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00004045 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00004046 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00004047 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00004048 if (CheckClassTemplatePartialSpecializationArgs(
4049 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004050 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00004051 return true;
4052
Douglas Gregor09a30232009-06-12 22:08:06 +00004053 if (MirrorsPrimaryTemplate) {
4054 // C++ [temp.class.spec]p9b3:
4055 //
Mike Stump11289f42009-09-09 15:08:12 +00004056 // -- The argument list of the specialization shall not be identical
4057 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00004058 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00004059 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00004060 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00004061 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00004062 ClassTemplate->getIdentifier(),
4063 TemplateNameLoc,
4064 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00004065 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00004066 AS_none);
4067 }
4068
Douglas Gregor2208a292009-09-26 20:57:03 +00004069 // FIXME: Diagnose friend partial specializations
4070
Douglas Gregor92354b62010-02-09 00:37:32 +00004071 if (!Name.isDependent() &&
4072 !TemplateSpecializationType::anyDependentTemplateArguments(
4073 TemplateArgs.getArgumentArray(),
4074 TemplateArgs.size())) {
4075 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4076 << ClassTemplate->getDeclName();
4077 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00004078 }
4079 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004080
Douglas Gregor67a65642009-02-17 23:15:12 +00004081 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00004082 ClassTemplateSpecializationDecl *PrevDecl = 0;
4083
4084 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004085 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00004086 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004087 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
4088 Converted.flatSize(),
4089 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00004090 else
4091 PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004092 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4093 Converted.flatSize(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00004094
4095 ClassTemplateSpecializationDecl *Specialization = 0;
4096
Douglas Gregorf47b9112009-02-25 22:02:03 +00004097 // Check whether we can declare a class template specialization in
4098 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00004099 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00004100 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004101 TemplateNameLoc,
4102 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00004103 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004104
Douglas Gregor15301382009-07-30 17:40:51 +00004105 // The canonical type
4106 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00004107 if (PrevDecl &&
4108 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00004109 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00004110 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00004111 // arguments was referenced but not declared, or we're only
4112 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00004113 // declaration node as our own, updating its source location to
4114 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00004115 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00004116 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00004117 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00004118 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00004119 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00004120 // Build the canonical type that describes the converted template
4121 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00004122 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4123 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00004124 Converted.getFlatArguments(),
4125 Converted.flatSize());
4126
Douglas Gregor2373c592009-05-31 09:31:02 +00004127 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00004128 ClassTemplatePartialSpecializationDecl *PrevPartial
4129 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00004130 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004131 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump11289f42009-09-09 15:08:12 +00004132 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00004133 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00004134 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00004135 TemplateNameLoc,
4136 TemplateParams,
4137 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004138 Converted,
John McCall6b51f282009-11-23 01:53:49 +00004139 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00004140 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00004141 PrevPartial,
4142 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00004143 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00004144 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00004145 Partial->setTemplateParameterListsInfo(Context,
4146 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004147 (TemplateParameterList**) TemplateParameterLists.release());
4148 }
Douglas Gregor2373c592009-05-31 09:31:02 +00004149
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004150 if (!PrevPartial)
4151 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00004152 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00004153
Douglas Gregor21610382009-10-29 00:04:11 +00004154 // If we are providing an explicit specialization of a member class
4155 // template specialization, make a note of that.
4156 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4157 PrevPartial->setMemberSpecialization();
4158
Douglas Gregor91772d12009-06-13 00:26:55 +00004159 // Check that all of the template parameters of the class template
4160 // partial specialization are deducible from the template
4161 // arguments. If not, this class template partial specialization
4162 // will never be used.
4163 llvm::SmallVector<bool, 8> DeducibleParams;
4164 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004165 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00004166 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004167 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00004168 unsigned NumNonDeducible = 0;
4169 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4170 if (!DeducibleParams[I])
4171 ++NumNonDeducible;
4172
4173 if (NumNonDeducible) {
4174 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4175 << (NumNonDeducible > 1)
4176 << SourceRange(TemplateNameLoc, RAngleLoc);
4177 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4178 if (!DeducibleParams[I]) {
4179 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4180 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00004181 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00004182 diag::note_partial_spec_unused_parameter)
4183 << Param->getDeclName();
4184 else
Mike Stump11289f42009-09-09 15:08:12 +00004185 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00004186 diag::note_partial_spec_unused_parameter)
Benjamin Kramere8394df2010-08-11 14:47:12 +00004187 << "<anonymous>";
Douglas Gregor91772d12009-06-13 00:26:55 +00004188 }
4189 }
4190 }
Douglas Gregor67a65642009-02-17 23:15:12 +00004191 } else {
4192 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00004193 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00004194 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004195 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00004196 ClassTemplate->getDeclContext(),
4197 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004198 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004199 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00004200 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004201 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor43397fc2010-07-28 23:59:57 +00004202 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00004203 Specialization->setTemplateParameterListsInfo(Context,
4204 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004205 (TemplateParameterList**) TemplateParameterLists.release());
4206 }
Douglas Gregor67a65642009-02-17 23:15:12 +00004207
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00004208 if (!PrevDecl)
4209 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00004210
4211 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004212 }
4213
Douglas Gregor06db9f52009-10-12 20:18:28 +00004214 // C++ [temp.expl.spec]p6:
4215 // If a template, a member template or the member of a class template is
4216 // explicitly specialized then that specialization shall be declared
4217 // before the first use of that specialization that would cause an implicit
4218 // instantiation to take place, in every translation unit in which such a
4219 // use occurs; no diagnostic is required.
4220 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00004221 bool Okay = false;
4222 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4223 // Is there any previous explicit specialization declaration?
4224 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4225 Okay = true;
4226 break;
4227 }
4228 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00004229
Douglas Gregorc854c662010-02-26 06:03:23 +00004230 if (!Okay) {
4231 SourceRange Range(TemplateNameLoc, RAngleLoc);
4232 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4233 << Context.getTypeDeclType(Specialization) << Range;
4234
4235 Diag(PrevDecl->getPointOfInstantiation(),
4236 diag::note_instantiation_required_here)
4237 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00004238 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00004239 return true;
4240 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00004241 }
4242
Douglas Gregor2208a292009-09-26 20:57:03 +00004243 // If this is not a friend, note that this is an explicit specialization.
4244 if (TUK != TUK_Friend)
4245 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004246
4247 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004248 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004249 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00004250 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004251 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00004252 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00004253 Diag(Def->getLocation(), diag::note_previous_definition);
4254 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00004255 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00004256 }
4257 }
4258
Douglas Gregord56a91e2009-02-26 22:19:44 +00004259 // Build the fully-sugared type for this class template
4260 // specialization as the user wrote in the specialization
4261 // itself. This means that we'll pretty-print the type retrieved
4262 // from the specialization's declaration the way that the user
4263 // actually wrote the specialization, rather than formatting the
4264 // name based on the "canonical" representation used to store the
4265 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004266 TypeSourceInfo *WrittenTy
4267 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4268 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004269 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00004270 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregord890b732010-07-06 18:33:12 +00004271 if (TemplateParams)
4272 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnara8075c852010-06-12 07:44:57 +00004273 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00004274 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00004275
Douglas Gregor1e249f82009-02-25 22:18:32 +00004276 // C++ [temp.expl.spec]p9:
4277 // A template explicit specialization is in the scope of the
4278 // namespace in which the template was defined.
4279 //
4280 // We actually implement this paragraph where we set the semantic
4281 // context (in the creation of the ClassTemplateSpecializationDecl),
4282 // but we also maintain the lexical context where the actual
4283 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00004284 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00004285
Douglas Gregor67a65642009-02-17 23:15:12 +00004286 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004287 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00004288 Specialization->startDefinition();
4289
Douglas Gregor2208a292009-09-26 20:57:03 +00004290 if (TUK == TUK_Friend) {
4291 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4292 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00004293 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00004294 /*FIXME:*/KWLoc);
4295 Friend->setAccess(AS_public);
4296 CurContext->addDecl(Friend);
4297 } else {
4298 // Add the specialization into its lexical context, so that it can
4299 // be seen when iterating through the list of declarations in that
4300 // context. However, specializations are not found by name lookup.
4301 CurContext->addDecl(Specialization);
4302 }
John McCall48871652010-08-21 09:40:31 +00004303 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00004304}
Douglas Gregor333489b2009-03-27 23:10:48 +00004305
John McCall48871652010-08-21 09:40:31 +00004306Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004307 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004308 Declarator &D) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004309 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4310}
4311
John McCall48871652010-08-21 09:40:31 +00004312Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004313 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00004314 Declarator &D) {
Douglas Gregor17a7c122009-06-24 00:54:41 +00004315 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4316 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4317 "Not a function declarator!");
4318 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004319
Douglas Gregor17a7c122009-06-24 00:54:41 +00004320 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004321 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004322 }
Mike Stump11289f42009-09-09 15:08:12 +00004323
Douglas Gregor17a7c122009-06-24 00:54:41 +00004324 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004325
John McCall48871652010-08-21 09:40:31 +00004326 Decl *DP = HandleDeclarator(ParentScope, D,
4327 move(TemplateParameterLists),
4328 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004329 if (FunctionTemplateDecl *FunctionTemplate
John McCall48871652010-08-21 09:40:31 +00004330 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump11289f42009-09-09 15:08:12 +00004331 return ActOnStartOfFunctionDef(FnBodyScope,
John McCall48871652010-08-21 09:40:31 +00004332 FunctionTemplate->getTemplatedDecl());
4333 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4334 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4335 return 0;
Douglas Gregor17a7c122009-06-24 00:54:41 +00004336}
4337
John McCall4f7ced62010-02-11 01:33:53 +00004338/// \brief Strips various properties off an implicit instantiation
4339/// that has just been explicitly specialized.
4340static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004341 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00004342
4343 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4344 FD->setInlineSpecified(false);
4345 }
4346}
4347
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004348/// \brief Diagnose cases where we have an explicit template specialization
4349/// before/after an explicit template instantiation, producing diagnostics
4350/// for those cases where they are required and determining whether the
4351/// new specialization/instantiation will have any effect.
4352///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004353/// \param NewLoc the location of the new explicit specialization or
4354/// instantiation.
4355///
4356/// \param NewTSK the kind of the new explicit specialization or instantiation.
4357///
4358/// \param PrevDecl the previous declaration of the entity.
4359///
4360/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4361///
4362/// \param PrevPointOfInstantiation if valid, indicates where the previus
4363/// declaration was instantiated (either implicitly or explicitly).
4364///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004365/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004366/// specialization or instantiation has no effect and should be ignored.
4367///
4368/// \returns true if there was an error that should prevent the introduction of
4369/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004370bool
4371Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4372 TemplateSpecializationKind NewTSK,
4373 NamedDecl *PrevDecl,
4374 TemplateSpecializationKind PrevTSK,
4375 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004376 bool &HasNoEffect) {
4377 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004378
4379 switch (NewTSK) {
4380 case TSK_Undeclared:
4381 case TSK_ImplicitInstantiation:
4382 assert(false && "Don't check implicit instantiations here");
4383 return false;
4384
4385 case TSK_ExplicitSpecialization:
4386 switch (PrevTSK) {
4387 case TSK_Undeclared:
4388 case TSK_ExplicitSpecialization:
4389 // Okay, we're just specializing something that is either already
4390 // explicitly specialized or has merely been mentioned without any
4391 // instantiation.
4392 return false;
4393
4394 case TSK_ImplicitInstantiation:
4395 if (PrevPointOfInstantiation.isInvalid()) {
4396 // The declaration itself has not actually been instantiated, so it is
4397 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004398 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004399 return false;
4400 }
4401 // Fall through
4402
4403 case TSK_ExplicitInstantiationDeclaration:
4404 case TSK_ExplicitInstantiationDefinition:
4405 assert((PrevTSK == TSK_ImplicitInstantiation ||
4406 PrevPointOfInstantiation.isValid()) &&
4407 "Explicit instantiation without point of instantiation?");
4408
4409 // C++ [temp.expl.spec]p6:
4410 // If a template, a member template or the member of a class template
4411 // is explicitly specialized then that specialization shall be declared
4412 // before the first use of that specialization that would cause an
4413 // implicit instantiation to take place, in every translation unit in
4414 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004415 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4416 // Is there any previous explicit specialization declaration?
4417 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4418 return false;
4419 }
4420
Douglas Gregor1d957a32009-10-27 18:42:08 +00004421 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004422 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004423 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004424 << (PrevTSK != TSK_ImplicitInstantiation);
4425
4426 return true;
4427 }
4428 break;
4429
4430 case TSK_ExplicitInstantiationDeclaration:
4431 switch (PrevTSK) {
4432 case TSK_ExplicitInstantiationDeclaration:
4433 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004434 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004435 return false;
4436
4437 case TSK_Undeclared:
4438 case TSK_ImplicitInstantiation:
4439 // We're explicitly instantiating something that may have already been
4440 // implicitly instantiated; that's fine.
4441 return false;
4442
4443 case TSK_ExplicitSpecialization:
4444 // C++0x [temp.explicit]p4:
4445 // For a given set of template parameters, if an explicit instantiation
4446 // of a template appears after a declaration of an explicit
4447 // specialization for that template, the explicit instantiation has no
4448 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004449 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004450 return false;
4451
4452 case TSK_ExplicitInstantiationDefinition:
4453 // C++0x [temp.explicit]p10:
4454 // If an entity is the subject of both an explicit instantiation
4455 // declaration and an explicit instantiation definition in the same
4456 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004457 Diag(NewLoc,
4458 diag::err_explicit_instantiation_declaration_after_definition);
4459 Diag(PrevPointOfInstantiation,
4460 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004461 assert(PrevPointOfInstantiation.isValid() &&
4462 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004463 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004464 return false;
4465 }
4466 break;
4467
4468 case TSK_ExplicitInstantiationDefinition:
4469 switch (PrevTSK) {
4470 case TSK_Undeclared:
4471 case TSK_ImplicitInstantiation:
4472 // We're explicitly instantiating something that may have already been
4473 // implicitly instantiated; that's fine.
4474 return false;
4475
4476 case TSK_ExplicitSpecialization:
4477 // C++ DR 259, C++0x [temp.explicit]p4:
4478 // For a given set of template parameters, if an explicit
4479 // instantiation of a template appears after a declaration of
4480 // an explicit specialization for that template, the explicit
4481 // instantiation has no effect.
4482 //
4483 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004484 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004485 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004486 if (!getLangOptions().CPlusPlus0x) {
4487 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004488 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004489 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004490 diag::note_previous_template_specialization);
4491 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004492 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004493 return false;
4494
4495 case TSK_ExplicitInstantiationDeclaration:
4496 // We're explicity instantiating a definition for something for which we
4497 // were previously asked to suppress instantiations. That's fine.
4498 return false;
4499
4500 case TSK_ExplicitInstantiationDefinition:
4501 // C++0x [temp.spec]p5:
4502 // For a given template and a given set of template-arguments,
4503 // - an explicit instantiation definition shall appear at most once
4504 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004505 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004506 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004507 Diag(PrevPointOfInstantiation,
4508 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004509 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004510 return false;
4511 }
4512 break;
4513 }
4514
4515 assert(false && "Missing specialization/instantiation case?");
4516
4517 return false;
4518}
4519
John McCallb9c78482010-04-08 09:05:18 +00004520/// \brief Perform semantic analysis for the given dependent function
4521/// template specialization. The only possible way to get a dependent
4522/// function template specialization is with a friend declaration,
4523/// like so:
4524///
4525/// template <class T> void foo(T);
4526/// template <class T> class A {
4527/// friend void foo<>(T);
4528/// };
4529///
4530/// There really isn't any useful analysis we can do here, so we
4531/// just store the information.
4532bool
4533Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4534 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4535 LookupResult &Previous) {
4536 // Remove anything from Previous that isn't a function template in
4537 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00004538 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00004539 LookupResult::Filter F = Previous.makeFilter();
4540 while (F.hasNext()) {
4541 NamedDecl *D = F.next()->getUnderlyingDecl();
4542 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00004543 !FDLookupContext->InEnclosingNamespaceSetOf(
4544 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00004545 F.erase();
4546 }
4547 F.done();
4548
4549 // Should this be diagnosed here?
4550 if (Previous.empty()) return true;
4551
4552 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4553 ExplicitTemplateArgs);
4554 return false;
4555}
4556
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004557/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004558/// specialization.
4559///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004560/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004561/// explicit function template specialization. On successful completion,
4562/// the function declaration \p FD will become a function template
4563/// specialization.
4564///
4565/// \param FD the function declaration, which will be updated to become a
4566/// function template specialization.
4567///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004568/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4569/// if any. Note that this may be valid info even when 0 arguments are
4570/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4571/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004572///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004573/// \param PrevDecl the set of declarations that may be specialized by
4574/// this function specialization.
4575bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004576Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004577 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004578 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004579 // The set of function template specializations that could match this
4580 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004581 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004582
Sebastian Redl50c68252010-08-31 00:36:30 +00004583 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00004584 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4585 I != E; ++I) {
4586 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4587 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004588 // Only consider templates found within the same semantic lookup scope as
4589 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00004590 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4591 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004592 continue;
4593
4594 // C++ [temp.expl.spec]p11:
4595 // A trailing template-argument can be left unspecified in the
4596 // template-id naming an explicit function template specialization
4597 // provided it can be deduced from the function argument type.
4598 // Perform template argument deduction to determine whether we may be
4599 // specializing this template.
4600 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004601 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004602 FunctionDecl *Specialization = 0;
4603 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004604 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004605 FD->getType(),
4606 Specialization,
4607 Info)) {
4608 // FIXME: Template argument deduction failed; record why it failed, so
4609 // that we can provide nifty diagnostics.
4610 (void)TDK;
4611 continue;
4612 }
4613
4614 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004615 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004616 }
4617 }
4618
Douglas Gregor5de279c2009-09-26 03:41:46 +00004619 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004620 UnresolvedSetIterator Result
4621 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4622 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004623 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004624 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004625 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004626 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004627 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004628 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004629 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004630
4631 // Ignore access information; it doesn't figure into redeclaration checking.
4632 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004633 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004634
4635 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004636 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004637
4638 // If this is a friend declaration, then we're not really declaring
4639 // an explicit specialization.
4640 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004641
Douglas Gregor54888652009-10-07 00:13:32 +00004642 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004643 if (!isFriend &&
4644 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004645 Specialization->getPrimaryTemplate(),
4646 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004647 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004648 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004649
4650 // C++ [temp.expl.spec]p6:
4651 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004652 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004653 // before the first use of that specialization that would cause an implicit
4654 // instantiation to take place, in every translation unit in which such a
4655 // use occurs; no diagnostic is required.
4656 FunctionTemplateSpecializationInfo *SpecInfo
4657 = Specialization->getTemplateSpecializationInfo();
4658 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004659
Abramo Bagnara8075c852010-06-12 07:44:57 +00004660 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004661 if (!isFriend &&
4662 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004663 TSK_ExplicitSpecialization,
4664 Specialization,
4665 SpecInfo->getTemplateSpecializationKind(),
4666 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004667 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004668 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004669
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004670 // Mark the prior declaration as an explicit specialization, so that later
4671 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004672 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00004673 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004674 MarkUnusedFileScopedDecl(Specialization);
4675 }
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004676
4677 // Turn the given function declaration into a function template
4678 // specialization, with the template arguments from the previous
4679 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004680 // Take copies of (semantic and syntactic) template argument lists.
4681 const TemplateArgumentList* TemplArgs = new (Context)
4682 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4683 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4684 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004685 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004686 TemplArgs, /*InsertPos=*/0,
4687 SpecInfo->getTemplateSpecializationKind(),
4688 TemplArgsAsWritten);
4689
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004690 // The "previous declaration" for this function template specialization is
4691 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004692 Previous.clear();
4693 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004694 return false;
4695}
4696
Douglas Gregor86d142a2009-10-08 07:24:58 +00004697/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004698/// specialization.
4699///
4700/// This routine performs all of the semantic analysis required for an
4701/// explicit member function specialization. On successful completion,
4702/// the function declaration \p FD will become a member function
4703/// specialization.
4704///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004705/// \param Member the member declaration, which will be updated to become a
4706/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004707///
John McCall1f82f242009-11-18 22:49:29 +00004708/// \param Previous the set of declarations, one of which may be specialized
4709/// by this function specialization; the set will be modified to contain the
4710/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004711bool
John McCall1f82f242009-11-18 22:49:29 +00004712Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004713 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004714
Douglas Gregor86d142a2009-10-08 07:24:58 +00004715 // Try to find the member we are instantiating.
4716 NamedDecl *Instantiation = 0;
4717 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004718 MemberSpecializationInfo *MSInfo = 0;
4719
John McCall1f82f242009-11-18 22:49:29 +00004720 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004721 // Nowhere to look anyway.
4722 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004723 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4724 I != E; ++I) {
4725 NamedDecl *D = (*I)->getUnderlyingDecl();
4726 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004727 if (Context.hasSameType(Function->getType(), Method->getType())) {
4728 Instantiation = Method;
4729 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004730 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004731 break;
4732 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004733 }
4734 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004735 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004736 VarDecl *PrevVar;
4737 if (Previous.isSingleResult() &&
4738 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004739 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004740 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004741 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004742 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004743 }
4744 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004745 CXXRecordDecl *PrevRecord;
4746 if (Previous.isSingleResult() &&
4747 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4748 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004749 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004750 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004751 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004752 }
4753
4754 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004755 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004756 // specializations are always out-of-line, the caller will complain about
4757 // this mismatch later.
4758 return false;
4759 }
John McCalle820e5e2010-04-13 20:37:33 +00004760
4761 // If this is a friend, just bail out here before we start turning
4762 // things into explicit specializations.
4763 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4764 // Preserve instantiation information.
4765 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4766 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4767 cast<CXXMethodDecl>(InstantiatedFrom),
4768 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4769 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4770 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4771 cast<CXXRecordDecl>(InstantiatedFrom),
4772 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4773 }
4774
4775 Previous.clear();
4776 Previous.addDecl(Instantiation);
4777 return false;
4778 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004779
Douglas Gregor86d142a2009-10-08 07:24:58 +00004780 // Make sure that this is a specialization of a member.
4781 if (!InstantiatedFrom) {
4782 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4783 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004784 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4785 return true;
4786 }
4787
Douglas Gregor06db9f52009-10-12 20:18:28 +00004788 // C++ [temp.expl.spec]p6:
4789 // If a template, a member template or the member of a class template is
4790 // explicitly specialized then that spe- cialization shall be declared
4791 // before the first use of that specialization that would cause an implicit
4792 // instantiation to take place, in every translation unit in which such a
4793 // use occurs; no diagnostic is required.
4794 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004795
Abramo Bagnara8075c852010-06-12 07:44:57 +00004796 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004797 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4798 TSK_ExplicitSpecialization,
4799 Instantiation,
4800 MSInfo->getTemplateSpecializationKind(),
4801 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004802 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004803 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004804
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004805 // Check the scope of this explicit specialization.
4806 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004807 InstantiatedFrom,
4808 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004809 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004810 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004811
Douglas Gregor86d142a2009-10-08 07:24:58 +00004812 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004813 // the original declaration to note that it is an explicit specialization
4814 // (if it was previously an implicit instantiation). This latter step
4815 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004816 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004817 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4818 if (InstantiationFunction->getTemplateSpecializationKind() ==
4819 TSK_ImplicitInstantiation) {
4820 InstantiationFunction->setTemplateSpecializationKind(
4821 TSK_ExplicitSpecialization);
4822 InstantiationFunction->setLocation(Member->getLocation());
4823 }
4824
Douglas Gregor86d142a2009-10-08 07:24:58 +00004825 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4826 cast<CXXMethodDecl>(InstantiatedFrom),
4827 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004828 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004829 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004830 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4831 if (InstantiationVar->getTemplateSpecializationKind() ==
4832 TSK_ImplicitInstantiation) {
4833 InstantiationVar->setTemplateSpecializationKind(
4834 TSK_ExplicitSpecialization);
4835 InstantiationVar->setLocation(Member->getLocation());
4836 }
4837
Douglas Gregor86d142a2009-10-08 07:24:58 +00004838 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4839 cast<VarDecl>(InstantiatedFrom),
4840 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004841 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004842 } else {
4843 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004844 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4845 if (InstantiationClass->getTemplateSpecializationKind() ==
4846 TSK_ImplicitInstantiation) {
4847 InstantiationClass->setTemplateSpecializationKind(
4848 TSK_ExplicitSpecialization);
4849 InstantiationClass->setLocation(Member->getLocation());
4850 }
4851
Douglas Gregor86d142a2009-10-08 07:24:58 +00004852 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004853 cast<CXXRecordDecl>(InstantiatedFrom),
4854 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004855 }
4856
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004857 // Save the caller the trouble of having to figure out which declaration
4858 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004859 Previous.clear();
4860 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004861 return false;
4862}
4863
Douglas Gregore47f5a72009-10-14 23:41:34 +00004864/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004865///
4866/// \returns true if a serious error occurs, false otherwise.
4867static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00004868 SourceLocation InstLoc,
4869 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00004870 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4871 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregore47f5a72009-10-14 23:41:34 +00004872
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004873 if (CurContext->isRecord()) {
4874 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4875 << D;
4876 return true;
4877 }
4878
Douglas Gregore47f5a72009-10-14 23:41:34 +00004879 // C++0x [temp.explicit]p2:
4880 // An explicit instantiation shall appear in an enclosing namespace of its
4881 // template.
4882 //
4883 // This is DR275, which we do not retroactively apply to C++98/03.
4884 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004885 !CurContext->Encloses(OrigContext)) {
4886 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004887 S.Diag(InstLoc,
4888 S.getLangOptions().CPlusPlus0x?
4889 diag::err_explicit_instantiation_out_of_scope
4890 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004891 << D << NS;
4892 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004893 S.Diag(InstLoc,
4894 S.getLangOptions().CPlusPlus0x?
4895 diag::err_explicit_instantiation_must_be_global
4896 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004897 << D;
4898 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004899 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004900 }
Sebastian Redl50c68252010-08-31 00:36:30 +00004901
Douglas Gregore47f5a72009-10-14 23:41:34 +00004902 // C++0x [temp.explicit]p2:
4903 // If the name declared in the explicit instantiation is an unqualified
4904 // name, the explicit instantiation shall appear in the namespace where
4905 // its template is declared or, if that namespace is inline (7.3.1), any
4906 // namespace from its enclosing namespace set.
4907 if (WasQualifiedName)
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004908 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004909
4910 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004911 return false;
Sebastian Redl50c68252010-08-31 00:36:30 +00004912
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004913 S.Diag(InstLoc,
4914 S.getLangOptions().CPlusPlus0x?
4915 diag::err_explicit_instantiation_unqualified_wrong_namespace
4916 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl50c68252010-08-31 00:36:30 +00004917 << D << OrigContext;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004918 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00004919 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004920}
4921
4922/// \brief Determine whether the given scope specifier has a template-id in it.
4923static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4924 if (!SS.isSet())
4925 return false;
4926
4927 // C++0x [temp.explicit]p2:
4928 // If the explicit instantiation is for a member function, a member class
4929 // or a static data member of a class template specialization, the name of
4930 // the class template specialization in the qualified-id for the member
4931 // name shall be a simple-template-id.
4932 //
4933 // C++98 has the same restriction, just worded differently.
4934 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4935 NNS; NNS = NNS->getPrefix())
4936 if (Type *T = NNS->getAsType())
4937 if (isa<TemplateSpecializationType>(T))
4938 return true;
4939
4940 return false;
4941}
4942
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004943// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00004944DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004945Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004946 SourceLocation ExternLoc,
4947 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004948 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004949 SourceLocation KWLoc,
4950 const CXXScopeSpec &SS,
4951 TemplateTy TemplateD,
4952 SourceLocation TemplateNameLoc,
4953 SourceLocation LAngleLoc,
4954 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004955 SourceLocation RAngleLoc,
4956 AttributeList *Attr) {
4957 // Find the class template we're specializing
4958 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004959 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004960 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4961
4962 // Check that the specialization uses the same tag kind as the
4963 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004964 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4965 assert(Kind != TTK_Enum &&
4966 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004967 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004968 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004969 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004970 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004971 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004972 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004973 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004974 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004975 diag::note_previous_use);
4976 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4977 }
4978
Douglas Gregore47f5a72009-10-14 23:41:34 +00004979 // C++0x [temp.explicit]p2:
4980 // There are two forms of explicit instantiation: an explicit instantiation
4981 // definition and an explicit instantiation declaration. An explicit
4982 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004983 TemplateSpecializationKind TSK
4984 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4985 : TSK_ExplicitInstantiationDeclaration;
4986
Douglas Gregora1f49972009-05-13 00:25:59 +00004987 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004988 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004989 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004990
4991 // Check that the template argument list is well-formed for this
4992 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004993 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4994 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004995 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4996 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004997 return true;
4998
Mike Stump11289f42009-09-09 15:08:12 +00004999 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00005000 ClassTemplate->getTemplateParameters()->size()) &&
5001 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00005002
Douglas Gregora1f49972009-05-13 00:25:59 +00005003 // Find the class template specialization declaration that
5004 // corresponds to these arguments.
Douglas Gregora1f49972009-05-13 00:25:59 +00005005 void *InsertPos = 0;
5006 ClassTemplateSpecializationDecl *PrevDecl
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00005007 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
5008 Converted.flatSize(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00005009
Abramo Bagnara8075c852010-06-12 07:44:57 +00005010 TemplateSpecializationKind PrevDecl_TSK
5011 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5012
Douglas Gregor54888652009-10-07 00:13:32 +00005013 // C++0x [temp.explicit]p2:
5014 // [...] An explicit instantiation shall appear in an enclosing
5015 // namespace of its template. [...]
5016 //
5017 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00005018 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5019 SS.isSet()))
5020 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00005021
Douglas Gregora1f49972009-05-13 00:25:59 +00005022 ClassTemplateSpecializationDecl *Specialization = 0;
5023
Douglas Gregor0681a352009-11-25 06:01:46 +00005024 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005025 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00005026 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00005027 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00005028 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00005029 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005030 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00005031 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00005032
Abramo Bagnara8075c852010-06-12 07:44:57 +00005033 // Even though HasNoEffect == true means that this explicit instantiation
5034 // has no effect on semantics, we go on to put its syntax in the AST.
5035
5036 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5037 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005038 // Since the only prior class template specialization with these
5039 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00005040 // declaration node as our own, updating the source location
5041 // for the template name to reflect our new declaration.
5042 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005043 Specialization = PrevDecl;
5044 Specialization->setLocation(TemplateNameLoc);
5045 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00005046 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005047 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00005048 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00005049
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005050 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00005051 // Create a new class template specialization declaration node for
5052 // this explicit specialization.
5053 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00005054 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00005055 ClassTemplate->getDeclContext(),
5056 TemplateNameLoc,
5057 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00005058 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00005059 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00005060
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00005061 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005062 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00005063 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005064 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005065 }
5066
5067 // Build the fully-sugared type for this explicit instantiation as
5068 // the user wrote in the explicit instantiation itself. This means
5069 // that we'll pretty-print the type retrieved from the
5070 // specialization's declaration the way that the user actually wrote
5071 // the explicit instantiation, rather than formatting the name based
5072 // on the "canonical" representation used to store the template
5073 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00005074 TypeSourceInfo *WrittenTy
5075 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5076 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00005077 Context.getTypeDeclType(Specialization));
5078 Specialization->setTypeAsWritten(WrittenTy);
5079 TemplateArgsIn.release();
5080
Abramo Bagnara8075c852010-06-12 07:44:57 +00005081 // Set source locations for keywords.
5082 Specialization->setExternLoc(ExternLoc);
5083 Specialization->setTemplateKeywordLoc(TemplateLoc);
5084
5085 // Add the explicit instantiation into its lexical context. However,
5086 // since explicit instantiations are never found by name lookup, we
5087 // just put it into the declaration context directly.
5088 Specialization->setLexicalDeclContext(CurContext);
5089 CurContext->addDecl(Specialization);
5090
5091 // Syntax is now OK, so return if it has no other effect on semantics.
5092 if (HasNoEffect) {
5093 // Set the template specialization kind.
5094 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00005095 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00005096 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005097
5098 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00005099 // A definition of a class template or class member template
5100 // shall be in scope at the point of the explicit instantiation of
5101 // the class template or class member template.
5102 //
5103 // This check comes when we actually try to perform the
5104 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00005105 ClassTemplateSpecializationDecl *Def
5106 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005107 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00005108 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00005109 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005110 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00005111 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00005112 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5113 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005114
Douglas Gregor1d957a32009-10-27 18:42:08 +00005115 // Instantiate the members of this class template specialization.
5116 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005117 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00005118 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00005119 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5120
5121 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5122 // TSK_ExplicitInstantiationDefinition
5123 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5124 TSK == TSK_ExplicitInstantiationDefinition)
5125 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00005126
Douglas Gregor12e49d32009-10-15 22:53:21 +00005127 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00005128 }
Douglas Gregora1f49972009-05-13 00:25:59 +00005129
Abramo Bagnara8075c852010-06-12 07:44:57 +00005130 // Set the template specialization kind.
5131 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00005132 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00005133}
5134
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005135// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00005136DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00005137Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00005138 SourceLocation ExternLoc,
5139 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005140 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005141 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005142 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005143 IdentifierInfo *Name,
5144 SourceLocation NameLoc,
5145 AttributeList *Attr) {
5146
Douglas Gregord6ab8742009-05-28 23:31:59 +00005147 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00005148 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00005149 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00005150 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5151 MultiTemplateParamsArg(*this, 0, 0),
Douglas Gregor0bf31402010-10-08 23:50:27 +00005152 Owned, IsDependent, false,
5153 TypeResult());
John McCall7f41d982009-09-11 04:59:25 +00005154 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5155
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005156 if (!TagD)
5157 return true;
5158
John McCall48871652010-08-21 09:40:31 +00005159 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005160 if (Tag->isEnum()) {
5161 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5162 << Context.getTypeDeclType(Tag);
5163 return true;
5164 }
5165
Douglas Gregorb8006faf2009-05-27 17:30:49 +00005166 if (Tag->isInvalidDecl())
5167 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005168
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005169 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5170 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5171 if (!Pattern) {
5172 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5173 << Context.getTypeDeclType(Record);
5174 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5175 return true;
5176 }
5177
Douglas Gregore47f5a72009-10-14 23:41:34 +00005178 // C++0x [temp.explicit]p2:
5179 // If the explicit instantiation is for a class or member class, the
5180 // elaborated-type-specifier in the declaration shall include a
5181 // simple-template-id.
5182 //
5183 // C++98 has the same restriction, just worded differently.
5184 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00005185 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005186 << Record << SS.getRange();
5187
5188 // C++0x [temp.explicit]p2:
5189 // There are two forms of explicit instantiation: an explicit instantiation
5190 // definition and an explicit instantiation declaration. An explicit
5191 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00005192 TemplateSpecializationKind TSK
5193 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5194 : TSK_ExplicitInstantiationDeclaration;
5195
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005196 // C++0x [temp.explicit]p2:
5197 // [...] An explicit instantiation shall appear in an enclosing
5198 // namespace of its template. [...]
5199 //
5200 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00005201 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005202
5203 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00005204 CXXRecordDecl *PrevDecl
5205 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005206 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00005207 PrevDecl = Record;
5208 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005209 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00005210 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005211 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00005212 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005213 PrevDecl,
5214 MSInfo->getTemplateSpecializationKind(),
5215 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005216 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005217 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005218 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005219 return TagD;
5220 }
5221
Douglas Gregor12e49d32009-10-15 22:53:21 +00005222 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005223 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00005224 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00005225 // C++ [temp.explicit]p3:
5226 // A definition of a member class of a class template shall be in scope
5227 // at the point of an explicit instantiation of the member class.
5228 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005229 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00005230 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00005231 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5232 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00005233 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5234 << Pattern;
5235 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005236 } else {
5237 if (InstantiateClass(NameLoc, Record, Def,
5238 getTemplateInstantiationArgs(Record),
5239 TSK))
5240 return true;
5241
Douglas Gregor0a5a2212010-02-11 01:04:33 +00005242 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00005243 if (!RecordDef)
5244 return true;
5245 }
5246 }
5247
5248 // Instantiate all of the members of the class.
5249 InstantiateClassMembers(NameLoc, RecordDef,
5250 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005251
Douglas Gregor88d292c2010-05-13 16:44:06 +00005252 if (TSK == TSK_ExplicitInstantiationDefinition)
5253 MarkVTableUsed(NameLoc, RecordDef, true);
5254
Mike Stump87c57ac2009-05-16 07:39:55 +00005255 // FIXME: We don't have any representation for explicit instantiations of
5256 // member classes. Such a representation is not needed for compilation, but it
5257 // should be available for clients that want to see all of the declarations in
5258 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00005259 return TagD;
5260}
5261
John McCallfaf5fb42010-08-26 23:41:50 +00005262DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5263 SourceLocation ExternLoc,
5264 SourceLocation TemplateLoc,
5265 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005266 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005267 // TODO: check if/when DNInfo should replace Name.
5268 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5269 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00005270 if (!Name) {
5271 if (!D.isInvalidType())
5272 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5273 diag::err_explicit_instantiation_requires_name)
5274 << D.getDeclSpec().getSourceRange()
5275 << D.getSourceRange();
5276
5277 return true;
5278 }
5279
5280 // The scope passed in may not be a decl scope. Zip up the scope tree until
5281 // we find one that is.
5282 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5283 (S->getFlags() & Scope::TemplateParamScope) != 0)
5284 S = S->getParent();
5285
5286 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00005287 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5288 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00005289 if (R.isNull())
5290 return true;
5291
5292 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5293 // Cannot explicitly instantiate a typedef.
5294 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5295 << Name;
5296 return true;
5297 }
5298
Douglas Gregor3c74d412009-10-14 20:14:33 +00005299 // C++0x [temp.explicit]p1:
5300 // [...] An explicit instantiation of a function template shall not use the
5301 // inline or constexpr specifiers.
5302 // Presumably, this also applies to member functions of class templates as
5303 // well.
5304 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5305 Diag(D.getDeclSpec().getInlineSpecLoc(),
5306 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00005307 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00005308
5309 // FIXME: check for constexpr specifier.
5310
Douglas Gregore47f5a72009-10-14 23:41:34 +00005311 // C++0x [temp.explicit]p2:
5312 // There are two forms of explicit instantiation: an explicit instantiation
5313 // definition and an explicit instantiation declaration. An explicit
5314 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005315 TemplateSpecializationKind TSK
5316 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5317 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005318
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005319 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005320 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005321
5322 if (!R->isFunctionType()) {
5323 // C++ [temp.explicit]p1:
5324 // A [...] static data member of a class template can be explicitly
5325 // instantiated from the member definition associated with its class
5326 // template.
John McCall27b18f82009-11-17 02:14:36 +00005327 if (Previous.isAmbiguous())
5328 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005329
John McCall67c00872009-12-02 08:25:40 +00005330 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005331 if (!Prev || !Prev->isStaticDataMember()) {
5332 // We expect to see a data data member here.
5333 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5334 << Name;
5335 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5336 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005337 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005338 return true;
5339 }
5340
5341 if (!Prev->getInstantiatedFromStaticDataMember()) {
5342 // FIXME: Check for explicit specialization?
5343 Diag(D.getIdentifierLoc(),
5344 diag::err_explicit_instantiation_data_member_not_instantiated)
5345 << Prev;
5346 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5347 // FIXME: Can we provide a note showing where this was declared?
5348 return true;
5349 }
5350
Douglas Gregore47f5a72009-10-14 23:41:34 +00005351 // C++0x [temp.explicit]p2:
5352 // If the explicit instantiation is for a member function, a member class
5353 // or a static data member of a class template specialization, the name of
5354 // the class template specialization in the qualified-id for the member
5355 // name shall be a simple-template-id.
5356 //
5357 // C++98 has the same restriction, just worded differently.
5358 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5359 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005360 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005361 << Prev << D.getCXXScopeSpec().getRange();
5362
5363 // Check the scope of this explicit instantiation.
5364 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5365
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005366 // Verify that it is okay to explicitly instantiate here.
5367 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5368 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005369 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005370 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005371 MSInfo->getTemplateSpecializationKind(),
5372 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005373 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005374 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005375 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005376 return (Decl*) 0;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005377
Douglas Gregor450f00842009-09-25 18:43:00 +00005378 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005379 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005380 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005381 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregor450f00842009-09-25 18:43:00 +00005382
5383 // FIXME: Create an ExplicitInstantiation node?
John McCall48871652010-08-21 09:40:31 +00005384 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005385 }
5386
Douglas Gregor0e876e02009-09-25 23:53:26 +00005387 // If the declarator is a template-id, translate the parser's template
5388 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005389 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005390 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005391 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5392 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005393 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5394 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005395 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5396 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005397 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005398 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005399 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005400 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005401 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005402
Douglas Gregor450f00842009-09-25 18:43:00 +00005403 // C++ [temp.explicit]p1:
5404 // A [...] function [...] can be explicitly instantiated from its template.
5405 // A member function [...] of a class template can be explicitly
5406 // instantiated from the member definition associated with its class
5407 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005408 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005409 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5410 P != PEnd; ++P) {
5411 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005412 if (!HasExplicitTemplateArgs) {
5413 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5414 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5415 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005416
John McCall58cc69d2010-01-27 01:50:18 +00005417 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005418 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5419 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005420 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005421 }
5422 }
5423
5424 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5425 if (!FunTmpl)
5426 continue;
5427
John McCallbc077cf2010-02-08 23:07:23 +00005428 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005429 FunctionDecl *Specialization = 0;
5430 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005431 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005432 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005433 R, Specialization, Info)) {
5434 // FIXME: Keep track of almost-matches?
5435 (void)TDK;
5436 continue;
5437 }
5438
John McCall58cc69d2010-01-27 01:50:18 +00005439 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005440 }
5441
5442 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005443 UnresolvedSetIterator Result
5444 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005445 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005446 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5447 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5448 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005449
John McCall58cc69d2010-01-27 01:50:18 +00005450 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005451 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005452
5453 // Ignore access control bits, we don't need them for redeclaration checking.
5454 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005455
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005456 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005457 Diag(D.getIdentifierLoc(),
5458 diag::err_explicit_instantiation_member_function_not_instantiated)
5459 << Specialization
5460 << (Specialization->getTemplateSpecializationKind() ==
5461 TSK_ExplicitSpecialization);
5462 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5463 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005464 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005465
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005466 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005467 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5468 PrevDecl = Specialization;
5469
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005470 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005471 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005472 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005473 PrevDecl,
5474 PrevDecl->getTemplateSpecializationKind(),
5475 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005476 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005477 return true;
5478
5479 // FIXME: We may still want to build some representation of this
5480 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005481 if (HasNoEffect)
John McCall48871652010-08-21 09:40:31 +00005482 return (Decl*) 0;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005483 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005484
5485 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005486
5487 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005488 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005489
Douglas Gregore47f5a72009-10-14 23:41:34 +00005490 // C++0x [temp.explicit]p2:
5491 // If the explicit instantiation is for a member function, a member class
5492 // or a static data member of a class template specialization, the name of
5493 // the class template specialization in the qualified-id for the member
5494 // name shall be a simple-template-id.
5495 //
5496 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005497 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005498 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005499 D.getCXXScopeSpec().isSet() &&
5500 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5501 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005502 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005503 << Specialization << D.getCXXScopeSpec().getRange();
5504
5505 CheckExplicitInstantiationScope(*this,
5506 FunTmpl? (NamedDecl *)FunTmpl
5507 : Specialization->getInstantiatedFromMemberFunction(),
5508 D.getIdentifierLoc(),
5509 D.getCXXScopeSpec().isSet());
5510
Douglas Gregor450f00842009-09-25 18:43:00 +00005511 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCall48871652010-08-21 09:40:31 +00005512 return (Decl*) 0;
Douglas Gregor450f00842009-09-25 18:43:00 +00005513}
5514
John McCallfaf5fb42010-08-26 23:41:50 +00005515TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005516Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5517 const CXXScopeSpec &SS, IdentifierInfo *Name,
5518 SourceLocation TagLoc, SourceLocation NameLoc) {
5519 // This has to hold, because SS is expected to be defined.
5520 assert(Name && "Expected a name in a dependent tag");
5521
5522 NestedNameSpecifier *NNS
5523 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5524 if (!NNS)
5525 return true;
5526
Abramo Bagnara6150c882010-05-11 21:36:43 +00005527 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005528
Douglas Gregorba41d012010-04-24 16:38:41 +00005529 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5530 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005531 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005532 return true;
5533 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005534
5535 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallba7bf592010-08-24 05:47:05 +00005536 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCall7f41d982009-09-11 04:59:25 +00005537}
5538
John McCallfaf5fb42010-08-26 23:41:50 +00005539TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005540Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5541 const CXXScopeSpec &SS, const IdentifierInfo &II,
5542 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005543 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005544 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5545 if (!NNS)
5546 return true;
5547
Douglas Gregorf7d77712010-06-16 22:31:08 +00005548 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5549 !getLangOptions().CPlusPlus0x)
5550 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5551 << FixItHint::CreateRemoval(TypenameLoc);
5552
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005553 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005554 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005555 if (T.isNull())
5556 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005557
5558 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5559 if (isa<DependentNameType>(T)) {
5560 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005561 TL.setKeywordLoc(TypenameLoc);
5562 TL.setQualifierRange(SS.getRange());
5563 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005564 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005565 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005566 TL.setKeywordLoc(TypenameLoc);
5567 TL.setQualifierRange(SS.getRange());
5568 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005569 }
5570
John McCallba7bf592010-08-24 05:47:05 +00005571 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00005572}
5573
John McCallfaf5fb42010-08-26 23:41:50 +00005574TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005575Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5576 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallba7bf592010-08-24 05:47:05 +00005577 ParsedType Ty) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00005578 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5579 !getLangOptions().CPlusPlus0x)
5580 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5581 << FixItHint::CreateRemoval(TypenameLoc);
5582
John McCallf7bcc812010-05-28 23:32:21 +00005583 TypeSourceInfo *InnerTSI = 0;
5584 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCallf7bcc812010-05-28 23:32:21 +00005585
5586 assert(isa<TemplateSpecializationType>(T) &&
5587 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005588
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005589 if (computeDeclContext(SS, false)) {
5590 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005591 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005592 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005593
5594 // Push the inner type, preserving its source locations if possible.
5595 TypeLocBuilder Builder;
5596 if (InnerTSI)
5597 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5598 else
5599 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5600
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005601 /* Note: NNS already embedded in template specialization type T. */
5602 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCallf7bcc812010-05-28 23:32:21 +00005603 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5604 TL.setKeywordLoc(TypenameLoc);
5605 TL.setQualifierRange(SS.getRange());
5606
5607 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallba7bf592010-08-24 05:47:05 +00005608 return CreateParsedType(T, TSI);
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005609 }
Mike Stump11289f42009-09-09 15:08:12 +00005610
John McCallc392f372010-06-11 00:33:02 +00005611 // TODO: it's really silly that we make a template specialization
5612 // type earlier only to drop it again here.
5613 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5614 DependentTemplateName *DTN =
5615 TST->getTemplateName().getAsDependentTemplateName();
5616 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnaraf9985b42010-08-10 13:46:45 +00005617 assert(DTN->getQualifier()
5618 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5619 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5620 DTN->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00005621 DTN->getIdentifier(),
5622 TST->getNumArgs(),
5623 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005624 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005625 DependentTemplateSpecializationTypeLoc TL =
5626 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5627 if (InnerTSI) {
5628 TemplateSpecializationTypeLoc TSTL =
5629 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5630 TL.setLAngleLoc(TSTL.getLAngleLoc());
5631 TL.setRAngleLoc(TSTL.getRAngleLoc());
5632 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5633 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5634 } else {
5635 TL.initializeLocal(SourceLocation());
5636 }
John McCallf7bcc812010-05-28 23:32:21 +00005637 TL.setKeywordLoc(TypenameLoc);
5638 TL.setQualifierRange(SS.getRange());
John McCallba7bf592010-08-24 05:47:05 +00005639 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00005640}
5641
Douglas Gregor333489b2009-03-27 23:10:48 +00005642/// \brief Build the type that describes a C++ typename specifier,
5643/// e.g., "typename T::type".
5644QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005645Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5646 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005647 SourceLocation KeywordLoc, SourceRange NNSRange,
5648 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005649 CXXScopeSpec SS;
5650 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005651 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005652
John McCall0b66eb32010-05-01 00:40:08 +00005653 DeclContext *Ctx = computeDeclContext(SS);
5654 if (!Ctx) {
5655 // If the nested-name-specifier is dependent and couldn't be
5656 // resolved to a type, build a typename type.
5657 assert(NNS->isDependent());
5658 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005659 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005660
John McCall0b66eb32010-05-01 00:40:08 +00005661 // If the nested-name-specifier refers to the current instantiation,
5662 // the "typename" keyword itself is superfluous. In C++03, the
5663 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5664 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005665 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005666
John McCall0b66eb32010-05-01 00:40:08 +00005667 if (RequireCompleteDeclContext(SS, Ctx))
5668 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005669
5670 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005671 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005672 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005673 unsigned DiagID = 0;
5674 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005675 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005676 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005677 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005678 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005679
5680 case LookupResult::NotFoundInCurrentInstantiation:
5681 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005682 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005683
5684 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005685 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005686 // We found a type. Build an ElaboratedType, since the
5687 // typename-specifier was just sugar.
5688 return Context.getElaboratedType(ETK_Typename, NNS,
5689 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005690 }
5691
5692 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005693 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005694 break;
5695
John McCalle61f2ba2009-11-18 02:36:19 +00005696 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005697 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005698 return QualType();
5699
Douglas Gregor333489b2009-03-27 23:10:48 +00005700 case LookupResult::FoundOverloaded:
5701 DiagID = diag::err_typename_nested_not_type;
5702 Referenced = *Result.begin();
5703 break;
5704
John McCall6538c932009-10-10 05:48:19 +00005705 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005706 return QualType();
5707 }
5708
5709 // If we get here, it's because name lookup did not find a
5710 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005711 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5712 IILoc);
5713 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005714 if (Referenced)
5715 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5716 << Name;
5717 return QualType();
5718}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005719
5720namespace {
5721 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005722 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005723 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005724 SourceLocation Loc;
5725 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005726
Douglas Gregor15acfb92009-08-06 16:20:37 +00005727 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005728 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5729
Mike Stump11289f42009-09-09 15:08:12 +00005730 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005731 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005732 DeclarationName Entity)
5733 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005734 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005735
5736 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005737 /// transformed.
5738 ///
5739 /// For the purposes of type reconstruction, a type has already been
5740 /// transformed if it is NULL or if it is not dependent.
5741 bool AlreadyTransformed(QualType T) {
5742 return T.isNull() || !T->isDependentType();
5743 }
Mike Stump11289f42009-09-09 15:08:12 +00005744
5745 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005746 /// rebuilt.
5747 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005748
Douglas Gregor15acfb92009-08-06 16:20:37 +00005749 /// \brief Returns the name of the entity whose type is being rebuilt.
5750 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005751
Douglas Gregoref6ab412009-10-27 06:26:26 +00005752 /// \brief Sets the "base" location and entity when that
5753 /// information is known based on another transformation.
5754 void setBase(SourceLocation Loc, DeclarationName Entity) {
5755 this->Loc = Loc;
5756 this->Entity = Entity;
5757 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005758 };
5759}
5760
Douglas Gregor15acfb92009-08-06 16:20:37 +00005761/// \brief Rebuilds a type within the context of the current instantiation.
5762///
Mike Stump11289f42009-09-09 15:08:12 +00005763/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005764/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005765/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005766/// partial specialization thereof). This routine will rebuild that type now
5767/// that we have entered the declarator's scope, which may produce different
5768/// canonical types, e.g.,
5769///
5770/// \code
5771/// template<typename T>
5772/// struct X {
5773/// typedef T* pointer;
5774/// pointer data();
5775/// };
5776///
5777/// template<typename T>
5778/// typename X<T>::pointer X<T>::data() { ... }
5779/// \endcode
5780///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005781/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005782/// since we do not know that we can look into X<T> when we parsed the type.
5783/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005784/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005785/// as the canonical type of T*, allowing the return types of the out-of-line
5786/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005787TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5788 SourceLocation Loc,
5789 DeclarationName Name) {
5790 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005791 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005792
Douglas Gregor15acfb92009-08-06 16:20:37 +00005793 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5794 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005795}
Douglas Gregorbe999392009-09-15 16:23:51 +00005796
John McCalldadc5752010-08-24 06:29:42 +00005797ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00005798 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5799 DeclarationName());
5800 return Rebuilder.TransformExpr(E);
5801}
5802
John McCall99b2fe52010-04-29 23:50:39 +00005803bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5804 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005805
5806 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5807 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5808 DeclarationName());
5809 NestedNameSpecifier *Rebuilt =
5810 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005811 if (!Rebuilt) return true;
5812
5813 SS.setScopeRep(Rebuilt);
5814 return false;
John McCall2408e322010-04-27 00:57:59 +00005815}
5816
Douglas Gregorbe999392009-09-15 16:23:51 +00005817/// \brief Produces a formatted string that describes the binding of
5818/// template parameters to template arguments.
5819std::string
5820Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5821 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005822 // FIXME: For variadic templates, we'll need to get the structured list.
5823 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5824 Args.flat_size());
5825}
5826
5827std::string
5828Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5829 const TemplateArgument *Args,
5830 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005831 std::string Result;
5832
Douglas Gregore62e6a02009-11-11 19:13:48 +00005833 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005834 return Result;
5835
5836 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005837 if (I >= NumArgs)
5838 break;
5839
Douglas Gregorbe999392009-09-15 16:23:51 +00005840 if (I == 0)
5841 Result += "[with ";
5842 else
5843 Result += ", ";
5844
5845 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5846 Result += Id->getName();
5847 } else {
5848 Result += '$';
5849 Result += llvm::utostr(I);
5850 }
5851
5852 Result += " = ";
5853
5854 switch (Args[I].getKind()) {
5855 case TemplateArgument::Null:
5856 Result += "<no value>";
5857 break;
5858
5859 case TemplateArgument::Type: {
5860 std::string TypeStr;
5861 Args[I].getAsType().getAsStringInternal(TypeStr,
5862 Context.PrintingPolicy);
5863 Result += TypeStr;
5864 break;
5865 }
5866
5867 case TemplateArgument::Declaration: {
5868 bool Unnamed = true;
5869 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5870 if (ND->getDeclName()) {
5871 Unnamed = false;
5872 Result += ND->getNameAsString();
5873 }
5874 }
5875
5876 if (Unnamed) {
5877 Result += "<anonymous>";
5878 }
5879 break;
5880 }
5881
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005882 case TemplateArgument::Template: {
5883 std::string Str;
5884 llvm::raw_string_ostream OS(Str);
5885 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5886 Result += OS.str();
5887 break;
5888 }
5889
Douglas Gregorbe999392009-09-15 16:23:51 +00005890 case TemplateArgument::Integral: {
5891 Result += Args[I].getAsIntegral()->toString(10);
5892 break;
5893 }
5894
5895 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005896 // FIXME: This is non-optimal, since we're regurgitating the
5897 // expression we were given.
5898 std::string Str;
5899 {
5900 llvm::raw_string_ostream OS(Str);
5901 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5902 Context.PrintingPolicy);
5903 }
5904 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005905 break;
5906 }
5907
5908 case TemplateArgument::Pack:
5909 // FIXME: Format template argument packs
5910 Result += "<template argument pack>";
5911 break;
5912 }
5913 }
5914
5915 Result += ']';
5916 return Result;
5917}