blob: 828085b8bc2d005f08182f07e156364e22297c9d [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 return 0;
63}
64
John McCalle66edc12009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
71 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
72 if (!Repl)
73 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000074 else if (Repl != Orig) {
75
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
83 // ambiguous.
84 //
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
88 filter.erase();
89 continue;
90 }
91
John McCalle66edc12009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor41f90302010-04-12 20:54:26 +000093 }
John McCalle66edc12009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000100 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000101 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000102 bool EnteringContext,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000103 TemplateTy &TemplateResult) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000104 assert(getLangOptions().CPlusPlus && "No template names in C!");
105
Douglas Gregor3cf81312009-11-03 23:16:33 +0000106 DeclarationName TName;
107
108 switch (Name.getKind()) {
109 case UnqualifiedId::IK_Identifier:
110 TName = DeclarationName(Name.Identifier);
111 break;
112
113 case UnqualifiedId::IK_OperatorFunctionId:
114 TName = Context.DeclarationNames.getCXXOperatorName(
115 Name.OperatorFunctionId.Operator);
116 break;
117
Alexis Hunted0530f2009-11-28 08:58:14 +0000118 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000119 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
120 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000121
Douglas Gregor3cf81312009-11-03 23:16:33 +0000122 default:
123 return TNK_Non_template;
124 }
Mike Stump11289f42009-09-09 15:08:12 +0000125
John McCalle66edc12009-11-24 19:00:30 +0000126 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000127
Douglas Gregorff18cc12009-12-31 08:11:17 +0000128 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
129 LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +0000130 R.suppressDiagnostics();
131 LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
Douglas Gregor41f90302010-04-12 20:54:26 +0000132 if (R.empty() || R.isAmbiguous())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000133 return TNK_Non_template;
134
John McCalld28ae272009-12-02 08:04:21 +0000135 TemplateName Template;
136 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000137
John McCalld28ae272009-12-02 08:04:21 +0000138 unsigned ResultCount = R.end() - R.begin();
139 if (ResultCount > 1) {
140 // We assume that we'll preserve the qualifier from a function
141 // template name in other ways.
142 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
143 TemplateKind = TNK_Function_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000144 } else {
John McCalld28ae272009-12-02 08:04:21 +0000145 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
146
147 if (SS.isSet() && !SS.isInvalid()) {
148 NestedNameSpecifier *Qualifier
149 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
150 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
151 } else {
152 Template = TemplateName(TD);
153 }
154
155 if (isa<FunctionTemplateDecl>(TD))
156 TemplateKind = TNK_Function_template;
157 else {
158 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
159 TemplateKind = TNK_Type_template;
160 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000161 }
Mike Stump11289f42009-09-09 15:08:12 +0000162
John McCalld28ae272009-12-02 08:04:21 +0000163 TemplateResult = TemplateTy::make(Template);
164 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000165}
166
Douglas Gregor18473f32010-01-12 21:28:44 +0000167bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
168 SourceLocation IILoc,
169 Scope *S,
170 const CXXScopeSpec *SS,
171 TemplateTy &SuggestedTemplate,
172 TemplateNameKind &SuggestedKind) {
173 // We can't recover unless there's a dependent scope specifier preceding the
174 // template name.
175 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
176 computeDeclContext(*SS))
177 return false;
178
179 // The code is missing a 'template' keyword prior to the dependent template
180 // name.
181 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
182 Diag(IILoc, diag::err_template_kw_missing)
183 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000184 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000185 SuggestedTemplate
186 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
187 SuggestedKind = TNK_Dependent_template_name;
188 return true;
189}
190
John McCalle66edc12009-11-24 19:00:30 +0000191void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000192 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000193 QualType ObjectType,
194 bool EnteringContext) {
195 // Determine where to perform name lookup
196 DeclContext *LookupCtx = 0;
197 bool isDependent = false;
198 if (!ObjectType.isNull()) {
199 // This nested-name-specifier occurs in a member access expression, e.g.,
200 // x->B::f, and we are looking into the type of the object.
201 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
202 LookupCtx = computeDeclContext(ObjectType);
203 isDependent = ObjectType->isDependentType();
204 assert((isDependent || !ObjectType->isIncompleteType()) &&
205 "Caller should have completed object type");
206 } else if (SS.isSet()) {
207 // This nested-name-specifier occurs after another nested-name-specifier,
208 // so long into the context associated with the prior nested-name-specifier.
209 LookupCtx = computeDeclContext(SS, EnteringContext);
210 isDependent = isDependentScopeSpecifier(SS);
211
212 // The declaration context must be complete.
213 if (LookupCtx && RequireCompleteDeclContext(SS))
214 return;
215 }
216
217 bool ObjectTypeSearchedInScope = false;
218 if (LookupCtx) {
219 // Perform "qualified" name lookup into the declaration context we
220 // computed, which is either the type of the base of a member access
221 // expression or the declaration context associated with a prior
222 // nested-name-specifier.
223 LookupQualifiedName(Found, LookupCtx);
224
225 if (!ObjectType.isNull() && Found.empty()) {
226 // C++ [basic.lookup.classref]p1:
227 // In a class member access expression (5.2.5), if the . or -> token is
228 // immediately followed by an identifier followed by a <, the
229 // identifier must be looked up to determine whether the < is the
230 // beginning of a template argument list (14.2) or a less-than operator.
231 // The identifier is first looked up in the class of the object
232 // expression. If the identifier is not found, it is then looked up in
233 // the context of the entire postfix-expression and shall name a class
234 // or function template.
235 //
236 // FIXME: When we're instantiating a template, do we actually have to
237 // look in the scope of the template? Seems fishy...
238 if (S) LookupName(Found, S);
239 ObjectTypeSearchedInScope = true;
240 }
241 } else if (isDependent) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000242 // We cannot look into a dependent object type or nested nme
243 // specifier.
John McCalle66edc12009-11-24 19:00:30 +0000244 return;
245 } else {
246 // Perform unqualified name lookup in the current scope.
247 LookupName(Found, S);
248 }
249
Douglas Gregorc119dd52010-01-12 17:06:20 +0000250 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000251 // If we did not find any names, attempt to correct any typos.
252 DeclarationName Name = Found.getLookupName();
253 if (CorrectTypo(Found, S, &SS, LookupCtx)) {
254 FilterAcceptableTemplateNames(Context, Found);
255 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
256 if (LookupCtx)
257 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
258 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000259 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000260 Found.getLookupName().getAsString());
261 else
262 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
263 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000264 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000265 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000266 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
267 Diag(Template->getLocation(), diag::note_previous_decl)
268 << Template->getDeclName();
Douglas Gregorff18cc12009-12-31 08:11:17 +0000269 } else
270 Found.clear();
271 } else {
272 Found.clear();
273 }
274 }
275
John McCalle66edc12009-11-24 19:00:30 +0000276 FilterAcceptableTemplateNames(Context, Found);
277 if (Found.empty())
278 return;
279
280 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
281 // C++ [basic.lookup.classref]p1:
282 // [...] If the lookup in the class of the object expression finds a
283 // template, the name is also looked up in the context of the entire
284 // postfix-expression and [...]
285 //
286 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
287 LookupOrdinaryName);
288 LookupName(FoundOuter, S);
289 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000290
John McCalle66edc12009-11-24 19:00:30 +0000291 if (FoundOuter.empty()) {
292 // - if the name is not found, the name found in the class of the
293 // object expression is used, otherwise
294 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
295 // - if the name is found in the context of the entire
296 // postfix-expression and does not name a class template, the name
297 // found in the class of the object expression is used, otherwise
298 } else {
299 // - if the name found is a class template, it must refer to the same
300 // entity as the one found in the class of the object expression,
301 // otherwise the program is ill-formed.
302 if (!Found.isSingleResult() ||
303 Found.getFoundDecl()->getCanonicalDecl()
304 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
305 Diag(Found.getNameLoc(),
306 diag::err_nested_name_member_ref_lookup_ambiguous)
307 << Found.getLookupName();
308 Diag(Found.getRepresentativeDecl()->getLocation(),
309 diag::note_ambig_member_ref_object_type)
310 << ObjectType;
311 Diag(FoundOuter.getFoundDecl()->getLocation(),
312 diag::note_ambig_member_ref_scope);
313
314 // Recover by taking the template that we found in the object
315 // expression's type.
316 }
317 }
318 }
319}
320
John McCallcd4b4772009-12-02 03:53:29 +0000321/// ActOnDependentIdExpression - Handle a dependent id-expression that
322/// was just parsed. This is only possible with an explicit scope
323/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000324Sema::OwningExprResult
325Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
326 DeclarationName Name,
327 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000328 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000329 const TemplateArgumentListInfo *TemplateArgs) {
330 NestedNameSpecifier *Qualifier
331 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
332
John McCallcd4b4772009-12-02 03:53:29 +0000333 if (!isAddressOfOperand &&
334 isa<CXXMethodDecl>(CurContext) &&
335 cast<CXXMethodDecl>(CurContext)->isInstance()) {
336 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
337
John McCalle66edc12009-11-24 19:00:30 +0000338 // Since the 'this' expression is synthesized, we don't need to
339 // perform the double-lookup check.
340 NamedDecl *FirstQualifierInScope = 0;
341
John McCall2d74de92009-12-01 22:10:20 +0000342 return Owned(CXXDependentScopeMemberExpr::Create(Context,
343 /*This*/ 0, ThisType,
344 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000345 /*Op*/ SourceLocation(),
346 Qualifier, SS.getRange(),
347 FirstQualifierInScope,
348 Name, NameLoc,
349 TemplateArgs));
350 }
351
352 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
353}
354
355Sema::OwningExprResult
356Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
357 DeclarationName Name,
358 SourceLocation NameLoc,
359 const TemplateArgumentListInfo *TemplateArgs) {
360 return Owned(DependentScopeDeclRefExpr::Create(Context,
361 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
362 SS.getRange(),
363 Name, NameLoc,
364 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000365}
366
Douglas Gregor5101c242008-12-05 18:15:24 +0000367/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
368/// that the template parameter 'PrevDecl' is being shadowed by a new
369/// declaration at location Loc. Returns true to indicate that this is
370/// an error, and false otherwise.
371bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000372 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000373
374 // Microsoft Visual C++ permits template parameters to be shadowed.
375 if (getLangOptions().Microsoft)
376 return false;
377
378 // C++ [temp.local]p4:
379 // A template-parameter shall not be redeclared within its
380 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000381 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000382 << cast<NamedDecl>(PrevDecl)->getDeclName();
383 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
384 return true;
385}
386
Douglas Gregor463421d2009-03-03 04:44:36 +0000387/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000388/// the parameter D to reference the templated declaration and return a pointer
389/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000390TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000391 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000392 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000393 return Temp;
394 }
395 return 0;
396}
397
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000398static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
399 const ParsedTemplateArgument &Arg) {
400
401 switch (Arg.getKind()) {
402 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000403 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000404 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
405 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000406 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000407 return TemplateArgumentLoc(TemplateArgument(T), DI);
408 }
409
410 case ParsedTemplateArgument::NonType: {
411 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
412 return TemplateArgumentLoc(TemplateArgument(E), E);
413 }
414
415 case ParsedTemplateArgument::Template: {
416 TemplateName Template
417 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
418 return TemplateArgumentLoc(TemplateArgument(Template),
419 Arg.getScopeSpec().getRange(),
420 Arg.getLocation());
421 }
422 }
423
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000424 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000425 return TemplateArgumentLoc();
426}
427
428/// \brief Translates template arguments as provided by the parser
429/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000430void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
431 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000432 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000433 TemplateArgs.addArgument(translateTemplateArgument(*this,
434 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000435}
436
Douglas Gregor5101c242008-12-05 18:15:24 +0000437/// ActOnTypeParameter - Called when a C++ template type parameter
438/// (e.g., "typename T") has been parsed. Typename specifies whether
439/// the keyword "typename" was used to declare the type parameter
440/// (otherwise, "class" was used), and KeyLoc is the location of the
441/// "class" or "typename" keyword. ParamName is the name of the
442/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000443/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000444/// If the type parameter has a default argument, it will be added
445/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000446Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000447 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000448 SourceLocation KeyLoc,
449 IdentifierInfo *ParamName,
450 SourceLocation ParamNameLoc,
451 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000452 assert(S->isTemplateParamScope() &&
453 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000454 bool Invalid = false;
455
456 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000457 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000458 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000459 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000460 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000461 }
462
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000463 SourceLocation Loc = ParamNameLoc;
464 if (!ParamName)
465 Loc = KeyLoc;
466
Douglas Gregor5101c242008-12-05 18:15:24 +0000467 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000468 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
469 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000470 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000471 if (Invalid)
472 Param->setInvalidDecl();
473
474 if (ParamName) {
475 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000476 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000477 IdResolver.AddDecl(Param);
478 }
479
Chris Lattner83f095c2009-03-28 19:18:32 +0000480 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000481}
482
Douglas Gregordba32632009-02-10 19:49:53 +0000483/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000484/// Default) to the given template type parameter (TypeParam).
485void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000486 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000487 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000488 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000489 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000490 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000491
John McCallbcd03502009-12-07 02:54:59 +0000492 TypeSourceInfo *DefaultTInfo;
493 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000494
John McCallbcd03502009-12-07 02:54:59 +0000495 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000496
Anders Carlssond3824352009-06-12 22:30:13 +0000497 // C++0x [temp.param]p9:
498 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000499 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000500 if (Parm->isParameterPack()) {
501 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000502 return;
503 }
Mike Stump11289f42009-09-09 15:08:12 +0000504
Douglas Gregordba32632009-02-10 19:49:53 +0000505 // C++ [temp.param]p14:
506 // A template-parameter shall not be used in its own default argument.
507 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000508
Douglas Gregordba32632009-02-10 19:49:53 +0000509 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000510 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000511 Parm->setInvalidDecl();
512 return;
513 }
514
John McCallbcd03502009-12-07 02:54:59 +0000515 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000516}
517
Douglas Gregor463421d2009-03-03 04:44:36 +0000518/// \brief Check that the type of a non-type template parameter is
519/// well-formed.
520///
521/// \returns the (possibly-promoted) parameter type if valid;
522/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000523QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000524Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
525 // C++ [temp.param]p4:
526 //
527 // A non-type template-parameter shall have one of the following
528 // (optionally cv-qualified) types:
529 //
530 // -- integral or enumeration type,
531 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000532 // -- pointer to object or pointer to function,
533 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000534 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
535 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000536 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000537 T->isReferenceType() ||
538 // -- pointer to member.
539 T->isMemberPointerType() ||
540 // If T is a dependent type, we can't do the check now, so we
541 // assume that it is well-formed.
542 T->isDependentType())
543 return T;
544 // C++ [temp.param]p8:
545 //
546 // A non-type template-parameter of type "array of T" or
547 // "function returning T" is adjusted to be of type "pointer to
548 // T" or "pointer to function returning T", respectively.
549 else if (T->isArrayType())
550 // FIXME: Keep the type prior to promotion?
551 return Context.getArrayDecayedType(T);
552 else if (T->isFunctionType())
553 // FIXME: Keep the type prior to promotion?
554 return Context.getPointerType(T);
555
556 Diag(Loc, diag::err_template_nontype_parm_bad_type)
557 << T;
558
559 return QualType();
560}
561
Douglas Gregor5101c242008-12-05 18:15:24 +0000562/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
563/// template parameter (e.g., "int Size" in "template<int Size>
564/// class Array") has been parsed. S is the current scope and D is
565/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000566Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000567 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000568 unsigned Position) {
John McCallbcd03502009-12-07 02:54:59 +0000569 TypeSourceInfo *TInfo = 0;
570 QualType T = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000571
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000572 assert(S->isTemplateParamScope() &&
573 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000574 bool Invalid = false;
575
576 IdentifierInfo *ParamName = D.getIdentifier();
577 if (ParamName) {
John McCall9f3059a2009-10-09 21:13:30 +0000578 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000579 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000580 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000581 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000582 }
583
Douglas Gregor463421d2009-03-03 04:44:36 +0000584 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000585 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000586 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000587 Invalid = true;
588 }
Douglas Gregor81338792009-02-10 17:43:50 +0000589
Douglas Gregor5101c242008-12-05 18:15:24 +0000590 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000591 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
592 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000593 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000594 if (Invalid)
595 Param->setInvalidDecl();
596
597 if (D.getIdentifier()) {
598 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000599 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000600 IdResolver.AddDecl(Param);
601 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000602 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000603}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000604
Douglas Gregordba32632009-02-10 19:49:53 +0000605/// \brief Adds a default argument to the given non-type template
606/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000607void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000608 SourceLocation EqualLoc,
609 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000610 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000611 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000612 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000613
Douglas Gregordba32632009-02-10 19:49:53 +0000614 // C++ [temp.param]p14:
615 // A template-parameter shall not be used in its own default argument.
616 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000617
Douglas Gregordba32632009-02-10 19:49:53 +0000618 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000619 TemplateArgument Converted;
620 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
621 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000622 TemplateParm->setInvalidDecl();
623 return;
624 }
625
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000626 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
Douglas Gregordba32632009-02-10 19:49:53 +0000627}
628
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000629
630/// ActOnTemplateTemplateParameter - Called when a C++ template template
631/// parameter (e.g. T in template <template <typename> class T> class array)
632/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000633Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
634 SourceLocation TmpLoc,
635 TemplateParamsTy *Params,
636 IdentifierInfo *Name,
637 SourceLocation NameLoc,
638 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000639 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000640 assert(S->isTemplateParamScope() &&
641 "Template template parameter not in template parameter scope!");
642
643 // Construct the parameter object.
644 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000645 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
646 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000647 (TemplateParameterList*)Params);
648
649 // Make sure the parameter is valid.
650 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
651 // do anything yet. However, if the template parameter list or (eventual)
652 // default value is ever invalidated, that will propagate here.
653 bool Invalid = false;
654 if (Invalid) {
655 Param->setInvalidDecl();
656 }
657
658 // If the tt-param has a name, then link the identifier into the scope
659 // and lookup mechanisms.
660 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000661 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000662 IdResolver.AddDecl(Param);
663 }
664
Chris Lattner83f095c2009-03-28 19:18:32 +0000665 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000666}
667
Douglas Gregordba32632009-02-10 19:49:53 +0000668/// \brief Adds a default argument to the given template template
669/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000670void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000671 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000672 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000673 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000674 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000675
Douglas Gregordba32632009-02-10 19:49:53 +0000676 // C++ [temp.param]p14:
677 // A template-parameter shall not be used in its own default argument.
678 // FIXME: Implement this check! Needs a recursive walk over the types.
679
Douglas Gregore62e6a02009-11-11 19:13:48 +0000680 // Check only that we have a template template argument. We don't want to
681 // try to check well-formedness now, because our template template parameter
682 // might have dependent types in its template parameters, which we wouldn't
683 // be able to match now.
684 //
685 // If none of the template template parameter's template arguments mention
686 // other template parameters, we could actually perform more checking here.
687 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000688 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000689 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
690 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
691 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000692 return;
693 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000694
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000695 TemplateParm->setDefaultArgument(DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000696}
697
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000698/// ActOnTemplateParameterList - Builds a TemplateParameterList that
699/// contains the template parameters in Params/NumParams.
700Sema::TemplateParamsTy *
701Sema::ActOnTemplateParameterList(unsigned Depth,
702 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000703 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000704 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000705 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000706 SourceLocation RAngleLoc) {
707 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000708 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000709
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000710 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000711 (NamedDecl**)Params, NumParams,
712 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000713}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000714
John McCall3e11ebe2010-03-15 10:12:16 +0000715static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
716 if (SS.isSet())
717 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
718 SS.getRange());
719}
720
Douglas Gregorc08f4892009-03-25 00:13:59 +0000721Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000722Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000723 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000724 IdentifierInfo *Name, SourceLocation NameLoc,
725 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000726 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000727 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000728 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000729 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000730 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000731 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000732
733 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000734 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000735 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000736
John McCall27b5c252009-09-14 21:59:20 +0000737 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
738 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000739
740 // There is no such thing as an unnamed class template.
741 if (!Name) {
742 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000743 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000744 }
745
746 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000747 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000748 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000749 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000750 if (SS.isNotEmpty() && !SS.isInvalid()) {
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000751 if (RequireCompleteDeclContext(SS))
752 return true;
753
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000754 SemanticContext = computeDeclContext(SS, true);
755 if (!SemanticContext) {
756 // FIXME: Produce a reasonable diagnostic here
757 return true;
758 }
Mike Stump11289f42009-09-09 15:08:12 +0000759
John McCall27b18f82009-11-17 02:14:36 +0000760 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000761 } else {
762 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000763 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000764 }
Mike Stump11289f42009-09-09 15:08:12 +0000765
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000766 if (Previous.isAmbiguous())
767 return true;
768
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000769 NamedDecl *PrevDecl = 0;
770 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000771 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000772
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000773 // If there is a previous declaration with the same name, check
774 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000775 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000776 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000777
778 // We may have found the injected-class-name of a class template,
779 // class template partial specialization, or class template specialization.
780 // In these cases, grab the template that is being defined or specialized.
781 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
782 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
783 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
784 PrevClassTemplate
785 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
786 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
787 PrevClassTemplate
788 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
789 ->getSpecializedTemplate();
790 }
791 }
792
John McCalld43784f2009-12-18 11:25:59 +0000793 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000794 // C++ [namespace.memdef]p3:
795 // [...] When looking for a prior declaration of a class or a function
796 // declared as a friend, and when the name of the friend class or
797 // function is neither a qualified name nor a template-id, scopes outside
798 // the innermost enclosing namespace scope are not considered.
799 DeclContext *OutermostContext = CurContext;
800 while (!OutermostContext->isFileContext())
801 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000802
803 if (PrevDecl &&
804 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
805 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
John McCall90d3bb92009-12-17 23:21:11 +0000806 SemanticContext = PrevDecl->getDeclContext();
807 } else {
808 // Declarations in outer scopes don't matter. However, the outermost
809 // context we computed is the semantic context for our new
810 // declaration.
811 PrevDecl = PrevClassTemplate = 0;
812 SemanticContext = OutermostContext;
813 }
814
815 if (CurContext->isDependentContext()) {
816 // If this is a dependent context, we don't want to link the friend
817 // class template to the template in scope, because that would perform
818 // checking of the template parameter lists that can't be performed
819 // until the outer context is instantiated.
820 PrevDecl = PrevClassTemplate = 0;
821 }
822 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
823 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000824
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000825 if (PrevClassTemplate) {
826 // Ensure that the template parameter lists are compatible.
827 if (!TemplateParameterListsAreEqual(TemplateParams,
828 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000829 /*Complain=*/true,
830 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000831 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000832
833 // C++ [temp.class]p4:
834 // In a redeclaration, partial specialization, explicit
835 // specialization or explicit instantiation of a class template,
836 // the class-key shall agree in kind with the original class
837 // template declaration (7.1.5.3).
838 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000839 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000840 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000841 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000842 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000843 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000844 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000845 }
846
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000847 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000848 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000849 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000850 Diag(NameLoc, diag::err_redefinition) << Name;
851 Diag(Def->getLocation(), diag::note_previous_definition);
852 // FIXME: Would it make sense to try to "forget" the previous
853 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000854 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000855 }
856 }
857 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
858 // Maybe we will complain about the shadowed template parameter.
859 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
860 // Just pretend that we didn't see the previous declaration.
861 PrevDecl = 0;
862 } else if (PrevDecl) {
863 // C++ [temp]p5:
864 // A class template shall not have the same name as any other
865 // template, class, function, object, enumeration, enumerator,
866 // namespace, or type in the same scope (3.3), except as specified
867 // in (14.5.4).
868 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
869 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000870 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000871 }
872
Douglas Gregordba32632009-02-10 19:49:53 +0000873 // Check the template parameter list of this declaration, possibly
874 // merging in the template parameter list from the previous class
875 // template declaration.
876 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000877 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
878 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000879 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000880
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000881 if (SS.isSet()) {
882 // If the name of the template was qualified, we must be defining the
883 // template out-of-line.
884 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
885 !(TUK == TUK_Friend && CurContext->isDependentContext()))
886 Diag(NameLoc, diag::err_member_def_does_not_match)
887 << Name << SemanticContext << SS.getRange();
888 }
889
Mike Stump11289f42009-09-09 15:08:12 +0000890 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000891 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000892 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000893 PrevClassTemplate->getTemplatedDecl() : 0,
894 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000895 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000896
897 ClassTemplateDecl *NewTemplate
898 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
899 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000900 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000901 NewClass->setDescribedClassTemplate(NewTemplate);
902
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000903 // Build the type for the class template declaration now.
John McCalle78aac42010-03-10 03:28:59 +0000904 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
905 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000906 assert(T->isDependentType() && "Class template type is not dependent?");
907 (void)T;
908
Douglas Gregorcf915552009-10-13 16:30:37 +0000909 // If we are providing an explicit specialization of a member that is a
910 // class template, make a note of that.
911 if (PrevClassTemplate &&
912 PrevClassTemplate->getInstantiatedFromMemberTemplate())
913 PrevClassTemplate->setMemberSpecialization();
914
Anders Carlsson137108d2009-03-26 01:24:28 +0000915 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000916 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000917 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000918
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000919 // Set the lexical context of these templates
920 NewClass->setLexicalDeclContext(CurContext);
921 NewTemplate->setLexicalDeclContext(CurContext);
922
John McCall9bb74a52009-07-31 02:45:11 +0000923 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000924 NewClass->startDefinition();
925
926 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000927 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000928
John McCall27b5c252009-09-14 21:59:20 +0000929 if (TUK != TUK_Friend)
930 PushOnScopeChains(NewTemplate, S);
931 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000932 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000933 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000934 NewClass->setAccess(PrevClassTemplate->getAccess());
935 }
John McCall27b5c252009-09-14 21:59:20 +0000936
Douglas Gregor3dad8422009-09-26 06:47:28 +0000937 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
938 PrevClassTemplate != NULL);
939
John McCall27b5c252009-09-14 21:59:20 +0000940 // Friend templates are visible in fairly strange ways.
941 if (!CurContext->isDependentContext()) {
942 DeclContext *DC = SemanticContext->getLookupContext();
943 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
944 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
945 PushOnScopeChains(NewTemplate, EnclosingScope,
946 /* AddToContext = */ false);
947 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000948
949 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
950 NewClass->getLocation(),
951 NewTemplate,
952 /*FIXME:*/NewClass->getLocation());
953 Friend->setAccess(AS_public);
954 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000955 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000956
Douglas Gregordba32632009-02-10 19:49:53 +0000957 if (Invalid) {
958 NewTemplate->setInvalidDecl();
959 NewClass->setInvalidDecl();
960 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000961 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000962}
963
Douglas Gregored5731f2009-11-25 17:50:39 +0000964/// \brief Diagnose the presence of a default template argument on a
965/// template parameter, which is ill-formed in certain contexts.
966///
967/// \returns true if the default template argument should be dropped.
968static bool DiagnoseDefaultTemplateArgument(Sema &S,
969 Sema::TemplateParamListContext TPC,
970 SourceLocation ParamLoc,
971 SourceRange DefArgRange) {
972 switch (TPC) {
973 case Sema::TPC_ClassTemplate:
974 return false;
975
976 case Sema::TPC_FunctionTemplate:
977 // C++ [temp.param]p9:
978 // A default template-argument shall not be specified in a
979 // function template declaration or a function template
980 // definition [...]
981 // (This sentence is not in C++0x, per DR226).
982 if (!S.getLangOptions().CPlusPlus0x)
983 S.Diag(ParamLoc,
984 diag::err_template_parameter_default_in_function_template)
985 << DefArgRange;
986 return false;
987
988 case Sema::TPC_ClassTemplateMember:
989 // C++0x [temp.param]p9:
990 // A default template-argument shall not be specified in the
991 // template-parameter-lists of the definition of a member of a
992 // class template that appears outside of the member's class.
993 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
994 << DefArgRange;
995 return true;
996
997 case Sema::TPC_FriendFunctionTemplate:
998 // C++ [temp.param]p9:
999 // A default template-argument shall not be specified in a
1000 // friend template declaration.
1001 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1002 << DefArgRange;
1003 return true;
1004
1005 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1006 // for friend function templates if there is only a single
1007 // declaration (and it is a definition). Strange!
1008 }
1009
1010 return false;
1011}
1012
Douglas Gregordba32632009-02-10 19:49:53 +00001013/// \brief Checks the validity of a template parameter list, possibly
1014/// considering the template parameter list from a previous
1015/// declaration.
1016///
1017/// If an "old" template parameter list is provided, it must be
1018/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1019/// template parameter list.
1020///
1021/// \param NewParams Template parameter list for a new template
1022/// declaration. This template parameter list will be updated with any
1023/// default arguments that are carried through from the previous
1024/// template parameter list.
1025///
1026/// \param OldParams If provided, template parameter list from a
1027/// previous declaration of the same template. Default template
1028/// arguments will be merged from the old template parameter list to
1029/// the new template parameter list.
1030///
Douglas Gregored5731f2009-11-25 17:50:39 +00001031/// \param TPC Describes the context in which we are checking the given
1032/// template parameter list.
1033///
Douglas Gregordba32632009-02-10 19:49:53 +00001034/// \returns true if an error occurred, false otherwise.
1035bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001036 TemplateParameterList *OldParams,
1037 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001038 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001039
Douglas Gregordba32632009-02-10 19:49:53 +00001040 // C++ [temp.param]p10:
1041 // The set of default template-arguments available for use with a
1042 // template declaration or definition is obtained by merging the
1043 // default arguments from the definition (if in scope) and all
1044 // declarations in scope in the same way default function
1045 // arguments are (8.3.6).
1046 bool SawDefaultArgument = false;
1047 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001048
Anders Carlsson327865d2009-06-12 23:20:15 +00001049 bool SawParameterPack = false;
1050 SourceLocation ParameterPackLoc;
1051
Mike Stumpc89c8e32009-02-11 23:03:27 +00001052 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001053 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001054 if (OldParams)
1055 OldParam = OldParams->begin();
1056
1057 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1058 NewParamEnd = NewParams->end();
1059 NewParam != NewParamEnd; ++NewParam) {
1060 // Variables used to diagnose redundant default arguments
1061 bool RedundantDefaultArg = false;
1062 SourceLocation OldDefaultLoc;
1063 SourceLocation NewDefaultLoc;
1064
1065 // Variables used to diagnose missing default arguments
1066 bool MissingDefaultArg = false;
1067
Anders Carlsson327865d2009-06-12 23:20:15 +00001068 // C++0x [temp.param]p11:
1069 // If a template parameter of a class template is a template parameter pack,
1070 // it must be the last template parameter.
1071 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001072 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001073 diag::err_template_param_pack_must_be_last_template_parameter);
1074 Invalid = true;
1075 }
1076
Douglas Gregordba32632009-02-10 19:49:53 +00001077 if (TemplateTypeParmDecl *NewTypeParm
1078 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001079 // Check the presence of a default argument here.
1080 if (NewTypeParm->hasDefaultArgument() &&
1081 DiagnoseDefaultTemplateArgument(*this, TPC,
1082 NewTypeParm->getLocation(),
1083 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1084 .getFullSourceRange()))
1085 NewTypeParm->removeDefaultArgument();
1086
1087 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001088 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001089 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001090
Anders Carlsson327865d2009-06-12 23:20:15 +00001091 if (NewTypeParm->isParameterPack()) {
1092 assert(!NewTypeParm->hasDefaultArgument() &&
1093 "Parameter packs can't have a default argument!");
1094 SawParameterPack = true;
1095 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001096 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001097 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001098 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1099 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1100 SawDefaultArgument = true;
1101 RedundantDefaultArg = true;
1102 PreviousDefaultArgLoc = NewDefaultLoc;
1103 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1104 // Merge the default argument from the old declaration to the
1105 // new declaration.
1106 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001107 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001108 true);
1109 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1110 } else if (NewTypeParm->hasDefaultArgument()) {
1111 SawDefaultArgument = true;
1112 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1113 } else if (SawDefaultArgument)
1114 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001115 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001116 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001117 // Check the presence of a default argument here.
1118 if (NewNonTypeParm->hasDefaultArgument() &&
1119 DiagnoseDefaultTemplateArgument(*this, TPC,
1120 NewNonTypeParm->getLocation(),
1121 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1122 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1123 NewNonTypeParm->setDefaultArgument(0);
1124 }
1125
Mike Stump12b8ce12009-08-04 21:02:39 +00001126 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001127 NonTypeTemplateParmDecl *OldNonTypeParm
1128 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001129 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001130 NewNonTypeParm->hasDefaultArgument()) {
1131 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1132 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1133 SawDefaultArgument = true;
1134 RedundantDefaultArg = true;
1135 PreviousDefaultArgLoc = NewDefaultLoc;
1136 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1137 // Merge the default argument from the old declaration to the
1138 // new declaration.
1139 SawDefaultArgument = true;
1140 // FIXME: We need to create a new kind of "default argument"
1141 // expression that points to a previous template template
1142 // parameter.
1143 NewNonTypeParm->setDefaultArgument(
1144 OldNonTypeParm->getDefaultArgument());
1145 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1146 } else if (NewNonTypeParm->hasDefaultArgument()) {
1147 SawDefaultArgument = true;
1148 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1149 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001150 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001151 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001152 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001153 TemplateTemplateParmDecl *NewTemplateParm
1154 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001155 if (NewTemplateParm->hasDefaultArgument() &&
1156 DiagnoseDefaultTemplateArgument(*this, TPC,
1157 NewTemplateParm->getLocation(),
1158 NewTemplateParm->getDefaultArgument().getSourceRange()))
1159 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1160
1161 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001162 TemplateTemplateParmDecl *OldTemplateParm
1163 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001164 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001165 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001166 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1167 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001168 SawDefaultArgument = true;
1169 RedundantDefaultArg = true;
1170 PreviousDefaultArgLoc = NewDefaultLoc;
1171 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1172 // Merge the default argument from the old declaration to the
1173 // new declaration.
1174 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001175 // FIXME: We need to create a new kind of "default argument" expression
1176 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001177 NewTemplateParm->setDefaultArgument(
1178 OldTemplateParm->getDefaultArgument());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001179 PreviousDefaultArgLoc
1180 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001181 } else if (NewTemplateParm->hasDefaultArgument()) {
1182 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001183 PreviousDefaultArgLoc
1184 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001185 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001186 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001187 }
1188
1189 if (RedundantDefaultArg) {
1190 // C++ [temp.param]p12:
1191 // A template-parameter shall not be given default arguments
1192 // by two different declarations in the same scope.
1193 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1194 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1195 Invalid = true;
1196 } else if (MissingDefaultArg) {
1197 // C++ [temp.param]p11:
1198 // If a template-parameter has a default template-argument,
1199 // all subsequent template-parameters shall have a default
1200 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001201 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001202 diag::err_template_param_default_arg_missing);
1203 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1204 Invalid = true;
1205 }
1206
1207 // If we have an old template parameter list that we're merging
1208 // in, move on to the next parameter.
1209 if (OldParams)
1210 ++OldParam;
1211 }
1212
1213 return Invalid;
1214}
Douglas Gregord32e0282009-02-09 23:23:08 +00001215
Mike Stump11289f42009-09-09 15:08:12 +00001216/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001217/// specifier, returning the template parameter list that applies to the
1218/// name.
1219///
1220/// \param DeclStartLoc the start of the declaration that has a scope
1221/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001222///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001223/// \param SS the scope specifier that will be matched to the given template
1224/// parameter lists. This scope specifier precedes a qualified name that is
1225/// being declared.
1226///
1227/// \param ParamLists the template parameter lists, from the outermost to the
1228/// innermost template parameter lists.
1229///
1230/// \param NumParamLists the number of template parameter lists in ParamLists.
1231///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001232/// \param IsExplicitSpecialization will be set true if the entity being
1233/// declared is an explicit specialization, false otherwise.
1234///
Mike Stump11289f42009-09-09 15:08:12 +00001235/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001236/// name that is preceded by the scope specifier @p SS. This template
1237/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001238/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001239/// template specialization), or may be NULL (if we were's declaring isn't
1240/// itself a template).
1241TemplateParameterList *
1242Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1243 const CXXScopeSpec &SS,
1244 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001245 unsigned NumParamLists,
1246 bool &IsExplicitSpecialization) {
1247 IsExplicitSpecialization = false;
1248
Douglas Gregord8d297c2009-07-21 23:53:31 +00001249 // Find the template-ids that occur within the nested-name-specifier. These
1250 // template-ids will match up with the template parameter lists.
1251 llvm::SmallVector<const TemplateSpecializationType *, 4>
1252 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001253 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1254 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001255 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1256 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001257 const Type *T = NNS->getAsType();
1258 if (!T) break;
1259
1260 // C++0x [temp.expl.spec]p17:
1261 // A member or a member template may be nested within many
1262 // enclosing class templates. In an explicit specialization for
1263 // such a member, the member declaration shall be preceded by a
1264 // template<> for each enclosing class template that is
1265 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001266 //
1267 // Following the existing practice of GNU and EDG, we allow a typedef of a
1268 // template specialization type.
1269 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1270 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001271
Mike Stump11289f42009-09-09 15:08:12 +00001272 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001273 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001274 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1275 if (!Template)
1276 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001277
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001278 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001279 ClassTemplateSpecializationDecl *SpecDecl
1280 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1281 // If the nested name specifier refers to an explicit specialization,
1282 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001283 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1284 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001285 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001286 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288
Douglas Gregord8d297c2009-07-21 23:53:31 +00001289 TemplateIdsInSpecifier.push_back(SpecType);
1290 }
1291 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
Douglas Gregord8d297c2009-07-21 23:53:31 +00001293 // Reverse the list of template-ids in the scope specifier, so that we can
1294 // more easily match up the template-ids and the template parameter lists.
1295 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001296
Douglas Gregord8d297c2009-07-21 23:53:31 +00001297 SourceLocation FirstTemplateLoc = DeclStartLoc;
1298 if (NumParamLists)
1299 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001300
Douglas Gregord8d297c2009-07-21 23:53:31 +00001301 // Match the template-ids found in the specifier to the template parameter
1302 // lists.
1303 unsigned Idx = 0;
1304 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1305 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001306 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1307 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001308 if (Idx >= NumParamLists) {
1309 // We have a template-id without a corresponding template parameter
1310 // list.
1311 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001312 // FIXME: the location information here isn't great.
1313 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001314 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001315 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001316 << SS.getRange();
1317 } else {
1318 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1319 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001320 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001321 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001322 }
1323 return 0;
1324 }
Mike Stump11289f42009-09-09 15:08:12 +00001325
Douglas Gregord8d297c2009-07-21 23:53:31 +00001326 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001327 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001328 TemplateDecl *Template
Douglas Gregor15301382009-07-30 17:40:51 +00001329 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl();
1330
Mike Stump11289f42009-09-09 15:08:12 +00001331 if (ClassTemplateDecl *ClassTemplate
Douglas Gregor15301382009-07-30 17:40:51 +00001332 = dyn_cast<ClassTemplateDecl>(Template)) {
1333 TemplateParameterList *ExpectedTemplateParams = 0;
1334 // Is this template-id naming the primary template?
1335 if (Context.hasSameType(TemplateId,
John McCalle78aac42010-03-10 03:28:59 +00001336 ClassTemplate->getInjectedClassNameSpecialization(Context)))
Douglas Gregor15301382009-07-30 17:40:51 +00001337 ExpectedTemplateParams = ClassTemplate->getTemplateParameters();
1338 // ... or a partial specialization?
1339 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1340 = ClassTemplate->findPartialSpecialization(TemplateId))
1341 ExpectedTemplateParams = PartialSpec->getTemplateParameters();
1342
1343 if (ExpectedTemplateParams)
Mike Stump11289f42009-09-09 15:08:12 +00001344 TemplateParameterListsAreEqual(ParamLists[Idx],
Douglas Gregor15301382009-07-30 17:40:51 +00001345 ExpectedTemplateParams,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001346 true, TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00001347 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001348
1349 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001350 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001351 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001352 diag::err_template_param_list_matches_nontemplate)
1353 << TemplateId
1354 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001355 else
1356 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001357 }
Mike Stump11289f42009-09-09 15:08:12 +00001358
Douglas Gregord8d297c2009-07-21 23:53:31 +00001359 // If there were at least as many template-ids as there were template
1360 // parameter lists, then there are no template parameter lists remaining for
1361 // the declaration itself.
1362 if (Idx >= NumParamLists)
1363 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001364
Douglas Gregord8d297c2009-07-21 23:53:31 +00001365 // If there were too many template parameter lists, complain about that now.
1366 if (Idx != NumParamLists - 1) {
1367 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001368 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001369 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001370 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1371 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001372 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1373 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001374
1375 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1376 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1377 diag::note_explicit_template_spec_does_not_need_header)
1378 << ExplicitSpecializationsInSpecifier.back();
1379 ExplicitSpecializationsInSpecifier.pop_back();
1380 }
1381
Douglas Gregord8d297c2009-07-21 23:53:31 +00001382 ++Idx;
1383 }
1384 }
Mike Stump11289f42009-09-09 15:08:12 +00001385
Douglas Gregord8d297c2009-07-21 23:53:31 +00001386 // Return the last template parameter list, which corresponds to the
1387 // entity being declared.
1388 return ParamLists[NumParamLists - 1];
1389}
1390
Douglas Gregordc572a32009-03-30 22:58:21 +00001391QualType Sema::CheckTemplateIdType(TemplateName Name,
1392 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001393 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001394 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001395 if (!Template) {
1396 // The template name does not resolve to a template, so we just
1397 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001398 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001399 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001400
Douglas Gregorc40290e2009-03-09 23:48:35 +00001401 // Check that the template argument list is well-formed for this
1402 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001403 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001404 TemplateArgs.size());
1405 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001406 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001407 return QualType();
1408
Mike Stump11289f42009-09-09 15:08:12 +00001409 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001410 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001411 "Converted template argument list is too short!");
1412
1413 QualType CanonType;
1414
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001415 if (Name.isDependent() ||
1416 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001417 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001418 // This class template specialization is a dependent
1419 // type. Therefore, its canonical type is another class template
1420 // specialization type that contains all of the converted
1421 // arguments in canonical form. This ensures that, e.g., A<T> and
1422 // A<T, T> have identical types when A is declared as:
1423 //
1424 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001425 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001426 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001427 Converted.getFlatArguments(),
1428 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001429
Douglas Gregora8e02e72009-07-28 23:00:59 +00001430 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001431 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001432 // In the future, we need to teach getTemplateSpecializationType to only
1433 // build the canonical type and return that to us.
1434 CanonType = Context.getCanonicalType(CanonType);
Mike Stump11289f42009-09-09 15:08:12 +00001435 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001436 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001437 // Find the class template specialization declaration that
1438 // corresponds to these arguments.
1439 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001440 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001441 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001442 Converted.flatSize(),
1443 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001444 void *InsertPos = 0;
1445 ClassTemplateSpecializationDecl *Decl
1446 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1447 if (!Decl) {
1448 // This is the first time we have referenced this class template
1449 // specialization. Create the canonical declaration and add it to
1450 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001451 Decl = ClassTemplateSpecializationDecl::Create(Context,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001452 ClassTemplate->getDeclContext(),
John McCall1806c272009-09-11 07:25:08 +00001453 ClassTemplate->getLocation(),
Anders Carlsson8aa89d42009-06-05 03:43:12 +00001454 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001455 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001456 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1457 Decl->setLexicalDeclContext(CurContext);
1458 }
1459
1460 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001461 assert(isa<RecordType>(CanonType) &&
1462 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001463 }
Mike Stump11289f42009-09-09 15:08:12 +00001464
Douglas Gregorc40290e2009-03-09 23:48:35 +00001465 // Build the fully-sugared type for this class template
1466 // specialization, which refers back to the class template
1467 // specialization we created or found.
John McCall6b51f282009-11-23 01:53:49 +00001468 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001469}
1470
Douglas Gregor67a65642009-02-17 23:15:12 +00001471Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001472Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001473 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001474 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001475 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001476 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001477
Douglas Gregorc40290e2009-03-09 23:48:35 +00001478 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001479 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001480 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001481
John McCall6b51f282009-11-23 01:53:49 +00001482 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001483 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001484
1485 if (Result.isNull())
1486 return true;
1487
John McCallbcd03502009-12-07 02:54:59 +00001488 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001489 TemplateSpecializationTypeLoc TL
1490 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1491 TL.setTemplateNameLoc(TemplateLoc);
1492 TL.setLAngleLoc(LAngleLoc);
1493 TL.setRAngleLoc(RAngleLoc);
1494 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1495 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1496
1497 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001498}
John McCall06f6fe8d2009-09-04 01:14:41 +00001499
John McCalld8fe9af2009-09-08 17:47:29 +00001500Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1501 TagUseKind TUK,
1502 DeclSpec::TST TagSpec,
1503 SourceLocation TagLoc) {
1504 if (TypeResult.isInvalid())
1505 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001506
John McCall0ad16662009-10-29 08:12:44 +00001507 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001508 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001509 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001510
John McCalld8fe9af2009-09-08 17:47:29 +00001511 // Verify the tag specifier.
1512 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001513
John McCalld8fe9af2009-09-08 17:47:29 +00001514 if (const RecordType *RT = Type->getAs<RecordType>()) {
1515 RecordDecl *D = RT->getDecl();
1516
1517 IdentifierInfo *Id = D->getIdentifier();
1518 assert(Id && "templated class must have an identifier");
1519
1520 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1521 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001522 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001523 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001524 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001525 }
1526 }
1527
John McCalld8fe9af2009-09-08 17:47:29 +00001528 QualType ElabType = Context.getElaboratedType(Type, TagKind);
1529
1530 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001531}
1532
John McCalle66edc12009-11-24 19:00:30 +00001533Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1534 LookupResult &R,
1535 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001536 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001537 // FIXME: Can we do any checking at this point? I guess we could check the
1538 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001539 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001540 // though.
John McCalle66edc12009-11-24 19:00:30 +00001541
1542 // These should be filtered out by our callers.
1543 assert(!R.empty() && "empty lookup results when building templateid");
1544 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1545
1546 NestedNameSpecifier *Qualifier = 0;
1547 SourceRange QualifierRange;
1548 if (SS.isSet()) {
1549 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1550 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001551 }
John McCall58cc69d2010-01-27 01:50:18 +00001552
1553 // We don't want lookup warnings at this point.
1554 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001555
John McCalle66edc12009-11-24 19:00:30 +00001556 bool Dependent
1557 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1558 &TemplateArgs);
1559 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001560 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001561 Qualifier, QualifierRange,
1562 R.getLookupName(), R.getNameLoc(),
1563 RequiresADL, TemplateArgs);
John McCall58cc69d2010-01-27 01:50:18 +00001564 ULE->addDecls(R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001565
1566 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001567}
1568
John McCalle66edc12009-11-24 19:00:30 +00001569// We actually only call this from template instantiation.
1570Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001571Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001572 DeclarationName Name,
1573 SourceLocation NameLoc,
1574 const TemplateArgumentListInfo &TemplateArgs) {
1575 DeclContext *DC;
1576 if (!(DC = computeDeclContext(SS, false)) ||
1577 DC->isDependentContext() ||
1578 RequireCompleteDeclContext(SS))
1579 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001580
John McCalle66edc12009-11-24 19:00:30 +00001581 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1582 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00001583
John McCalle66edc12009-11-24 19:00:30 +00001584 if (R.isAmbiguous())
1585 return ExprError();
1586
1587 if (R.empty()) {
1588 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1589 << Name << SS.getRange();
1590 return ExprError();
1591 }
1592
1593 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1594 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1595 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1596 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1597 return ExprError();
1598 }
1599
1600 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001601}
1602
Douglas Gregorb67535d2009-03-31 00:43:58 +00001603/// \brief Form a dependent template name.
1604///
1605/// This action forms a dependent template name given the template
1606/// name and its (presumably dependent) scope specifier. For
1607/// example, given "MetaFun::template apply", the scope specifier \p
1608/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1609/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001610Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001611Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001612 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001613 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001614 TypeTy *ObjectType,
1615 bool EnteringContext) {
Douglas Gregor9abe2372010-01-19 16:01:07 +00001616 DeclContext *LookupCtx = 0;
1617 if (SS.isSet())
1618 LookupCtx = computeDeclContext(SS, EnteringContext);
1619 if (!LookupCtx && ObjectType)
1620 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1621 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001622 // C++0x [temp.names]p5:
1623 // If a name prefixed by the keyword template is not the name of
1624 // a template, the program is ill-formed. [Note: the keyword
1625 // template may not be applied to non-template members of class
1626 // templates. -end note ] [ Note: as is the case with the
1627 // typename prefix, the template prefix is allowed in cases
1628 // where it is not strictly necessary; i.e., when the
1629 // nested-name-specifier or the expression on the left of the ->
1630 // or . is not dependent on a template-parameter, or the use
1631 // does not appear in the scope of a template. -end note]
1632 //
1633 // Note: C++03 was more strict here, because it banned the use of
1634 // the "template" keyword prior to a template-name that was not a
1635 // dependent name. C++ DR468 relaxed this requirement (the
1636 // "template" keyword is now permitted). We follow the C++0x
1637 // rules, even in C++03 mode, retroactively applying the DR.
1638 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001639 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001640 EnteringContext, Template);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001641 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1642 isa<CXXRecordDecl>(LookupCtx) &&
1643 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00001644 // This is a dependent template.
1645 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001646 Diag(Name.getSourceRange().getBegin(),
1647 diag::err_template_kw_refers_to_non_template)
1648 << GetNameFromUnqualifiedId(Name)
1649 << Name.getSourceRange();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001650 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001651 } else {
1652 // We found something; return it.
1653 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001654 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001655 }
1656
Mike Stump11289f42009-09-09 15:08:12 +00001657 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001658 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001659
1660 switch (Name.getKind()) {
1661 case UnqualifiedId::IK_Identifier:
1662 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1663 Name.Identifier));
1664
Douglas Gregor71395fa2009-11-04 00:56:37 +00001665 case UnqualifiedId::IK_OperatorFunctionId:
1666 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1667 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001668
1669 case UnqualifiedId::IK_LiteralOperatorId:
1670 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1671
Douglas Gregor3cf81312009-11-03 23:16:33 +00001672 default:
1673 break;
1674 }
1675
1676 Diag(Name.getSourceRange().getBegin(),
1677 diag::err_template_kw_refers_to_non_template)
1678 << GetNameFromUnqualifiedId(Name)
1679 << Name.getSourceRange();
1680 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001681}
1682
Mike Stump11289f42009-09-09 15:08:12 +00001683bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001684 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001685 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001686 const TemplateArgument &Arg = AL.getArgument();
1687
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001688 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001689 switch(Arg.getKind()) {
1690 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001691 // C++ [temp.arg.type]p1:
1692 // A template-argument for a template-parameter which is a
1693 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001694 break;
1695 case TemplateArgument::Template: {
1696 // We have a template type parameter but the template argument
1697 // is a template without any arguments.
1698 SourceRange SR = AL.getSourceRange();
1699 TemplateName Name = Arg.getAsTemplate();
1700 Diag(SR.getBegin(), diag::err_template_missing_args)
1701 << Name << SR;
1702 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1703 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001704
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001705 return true;
1706 }
1707 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001708 // We have a template type parameter but the template argument
1709 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001710 SourceRange SR = AL.getSourceRange();
1711 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001712 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001713
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001714 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001715 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001716 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001717
John McCallbcd03502009-12-07 02:54:59 +00001718 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001719 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001720
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001721 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001722 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001723 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001724 return false;
1725}
1726
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001727/// \brief Substitute template arguments into the default template argument for
1728/// the given template type parameter.
1729///
1730/// \param SemaRef the semantic analysis object for which we are performing
1731/// the substitution.
1732///
1733/// \param Template the template that we are synthesizing template arguments
1734/// for.
1735///
1736/// \param TemplateLoc the location of the template name that started the
1737/// template-id we are checking.
1738///
1739/// \param RAngleLoc the location of the right angle bracket ('>') that
1740/// terminates the template-id.
1741///
1742/// \param Param the template template parameter whose default we are
1743/// substituting into.
1744///
1745/// \param Converted the list of template arguments provided for template
1746/// parameters that precede \p Param in the template parameter list.
1747///
1748/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001749static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001750SubstDefaultTemplateArgument(Sema &SemaRef,
1751 TemplateDecl *Template,
1752 SourceLocation TemplateLoc,
1753 SourceLocation RAngleLoc,
1754 TemplateTypeParmDecl *Param,
1755 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001756 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001757
1758 // If the argument type is dependent, instantiate it now based
1759 // on the previously-computed template arguments.
1760 if (ArgType->getType()->isDependentType()) {
1761 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1762 /*TakeArgs=*/false);
1763
1764 MultiLevelTemplateArgumentList AllTemplateArgs
1765 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1766
1767 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1768 Template, Converted.getFlatArguments(),
1769 Converted.flatSize(),
1770 SourceRange(TemplateLoc, RAngleLoc));
1771
1772 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1773 Param->getDefaultArgumentLoc(),
1774 Param->getDeclName());
1775 }
1776
1777 return ArgType;
1778}
1779
1780/// \brief Substitute template arguments into the default template argument for
1781/// the given non-type template parameter.
1782///
1783/// \param SemaRef the semantic analysis object for which we are performing
1784/// the substitution.
1785///
1786/// \param Template the template that we are synthesizing template arguments
1787/// for.
1788///
1789/// \param TemplateLoc the location of the template name that started the
1790/// template-id we are checking.
1791///
1792/// \param RAngleLoc the location of the right angle bracket ('>') that
1793/// terminates the template-id.
1794///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001795/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001796/// substituting into.
1797///
1798/// \param Converted the list of template arguments provided for template
1799/// parameters that precede \p Param in the template parameter list.
1800///
1801/// \returns the substituted template argument, or NULL if an error occurred.
1802static Sema::OwningExprResult
1803SubstDefaultTemplateArgument(Sema &SemaRef,
1804 TemplateDecl *Template,
1805 SourceLocation TemplateLoc,
1806 SourceLocation RAngleLoc,
1807 NonTypeTemplateParmDecl *Param,
1808 TemplateArgumentListBuilder &Converted) {
1809 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1810 /*TakeArgs=*/false);
1811
1812 MultiLevelTemplateArgumentList AllTemplateArgs
1813 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1814
1815 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1816 Template, Converted.getFlatArguments(),
1817 Converted.flatSize(),
1818 SourceRange(TemplateLoc, RAngleLoc));
1819
1820 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1821}
1822
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001823/// \brief Substitute template arguments into the default template argument for
1824/// the given template template parameter.
1825///
1826/// \param SemaRef the semantic analysis object for which we are performing
1827/// the substitution.
1828///
1829/// \param Template the template that we are synthesizing template arguments
1830/// for.
1831///
1832/// \param TemplateLoc the location of the template name that started the
1833/// template-id we are checking.
1834///
1835/// \param RAngleLoc the location of the right angle bracket ('>') that
1836/// terminates the template-id.
1837///
1838/// \param Param the template template parameter whose default we are
1839/// substituting into.
1840///
1841/// \param Converted the list of template arguments provided for template
1842/// parameters that precede \p Param in the template parameter list.
1843///
1844/// \returns the substituted template argument, or NULL if an error occurred.
1845static TemplateName
1846SubstDefaultTemplateArgument(Sema &SemaRef,
1847 TemplateDecl *Template,
1848 SourceLocation TemplateLoc,
1849 SourceLocation RAngleLoc,
1850 TemplateTemplateParmDecl *Param,
1851 TemplateArgumentListBuilder &Converted) {
1852 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1853 /*TakeArgs=*/false);
1854
1855 MultiLevelTemplateArgumentList AllTemplateArgs
1856 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1857
1858 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1859 Template, Converted.getFlatArguments(),
1860 Converted.flatSize(),
1861 SourceRange(TemplateLoc, RAngleLoc));
1862
1863 return SemaRef.SubstTemplateName(
1864 Param->getDefaultArgument().getArgument().getAsTemplate(),
1865 Param->getDefaultArgument().getTemplateNameLoc(),
1866 AllTemplateArgs);
1867}
1868
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001869/// \brief If the given template parameter has a default template
1870/// argument, substitute into that default template argument and
1871/// return the corresponding template argument.
1872TemplateArgumentLoc
1873Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1874 SourceLocation TemplateLoc,
1875 SourceLocation RAngleLoc,
1876 Decl *Param,
1877 TemplateArgumentListBuilder &Converted) {
1878 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1879 if (!TypeParm->hasDefaultArgument())
1880 return TemplateArgumentLoc();
1881
John McCallbcd03502009-12-07 02:54:59 +00001882 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001883 TemplateLoc,
1884 RAngleLoc,
1885 TypeParm,
1886 Converted);
1887 if (DI)
1888 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1889
1890 return TemplateArgumentLoc();
1891 }
1892
1893 if (NonTypeTemplateParmDecl *NonTypeParm
1894 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1895 if (!NonTypeParm->hasDefaultArgument())
1896 return TemplateArgumentLoc();
1897
1898 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1899 TemplateLoc,
1900 RAngleLoc,
1901 NonTypeParm,
1902 Converted);
1903 if (Arg.isInvalid())
1904 return TemplateArgumentLoc();
1905
1906 Expr *ArgE = Arg.takeAs<Expr>();
1907 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1908 }
1909
1910 TemplateTemplateParmDecl *TempTempParm
1911 = cast<TemplateTemplateParmDecl>(Param);
1912 if (!TempTempParm->hasDefaultArgument())
1913 return TemplateArgumentLoc();
1914
1915 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1916 TemplateLoc,
1917 RAngleLoc,
1918 TempTempParm,
1919 Converted);
1920 if (TName.isNull())
1921 return TemplateArgumentLoc();
1922
1923 return TemplateArgumentLoc(TemplateArgument(TName),
1924 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1925 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1926}
1927
Douglas Gregorda0fb532009-11-11 19:31:23 +00001928/// \brief Check that the given template argument corresponds to the given
1929/// template parameter.
1930bool Sema::CheckTemplateArgument(NamedDecl *Param,
1931 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001932 TemplateDecl *Template,
1933 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00001934 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001935 TemplateArgumentListBuilder &Converted,
1936 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00001937 // Check template type parameters.
1938 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001939 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00001940
Douglas Gregoreebed722009-11-11 19:41:09 +00001941 // Check non-type template parameters.
1942 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00001943 // Do substitution on the type of the non-type template parameter
1944 // with the template arguments we've seen thus far.
1945 QualType NTTPType = NTTP->getType();
1946 if (NTTPType->isDependentType()) {
1947 // Do substitution on the type of the non-type template parameter.
1948 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
1949 NTTP, Converted.getFlatArguments(),
1950 Converted.flatSize(),
1951 SourceRange(TemplateLoc, RAngleLoc));
1952
1953 TemplateArgumentList TemplateArgs(Context, Converted,
1954 /*TakeArgs=*/false);
1955 NTTPType = SubstType(NTTPType,
1956 MultiLevelTemplateArgumentList(TemplateArgs),
1957 NTTP->getLocation(),
1958 NTTP->getDeclName());
1959 // If that worked, check the non-type template parameter type
1960 // for validity.
1961 if (!NTTPType.isNull())
1962 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
1963 NTTP->getLocation());
1964 if (NTTPType.isNull())
1965 return true;
1966 }
1967
1968 switch (Arg.getArgument().getKind()) {
1969 case TemplateArgument::Null:
1970 assert(false && "Should never see a NULL template argument here");
1971 return true;
1972
1973 case TemplateArgument::Expression: {
1974 Expr *E = Arg.getArgument().getAsExpr();
1975 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001976 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00001977 return true;
1978
1979 Converted.Append(Result);
1980 break;
1981 }
1982
1983 case TemplateArgument::Declaration:
1984 case TemplateArgument::Integral:
1985 // We've already checked this template argument, so just copy
1986 // it to the list of converted arguments.
1987 Converted.Append(Arg.getArgument());
1988 break;
1989
1990 case TemplateArgument::Template:
1991 // We were given a template template argument. It may not be ill-formed;
1992 // see below.
1993 if (DependentTemplateName *DTN
1994 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
1995 // We have a template argument such as \c T::template X, which we
1996 // parsed as a template template argument. However, since we now
1997 // know that we need a non-type template argument, convert this
1998 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00001999 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2000 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002001 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00002002 DTN->getIdentifier(),
2003 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002004
2005 TemplateArgument Result;
2006 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2007 return true;
2008
2009 Converted.Append(Result);
2010 break;
2011 }
2012
2013 // We have a template argument that actually does refer to a class
2014 // template, template alias, or template template parameter, and
2015 // therefore cannot be a non-type template argument.
2016 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2017 << Arg.getSourceRange();
2018
2019 Diag(Param->getLocation(), diag::note_template_param_here);
2020 return true;
2021
2022 case TemplateArgument::Type: {
2023 // We have a non-type template parameter but the template
2024 // argument is a type.
2025
2026 // C++ [temp.arg]p2:
2027 // In a template-argument, an ambiguity between a type-id and
2028 // an expression is resolved to a type-id, regardless of the
2029 // form of the corresponding template-parameter.
2030 //
2031 // We warn specifically about this case, since it can be rather
2032 // confusing for users.
2033 QualType T = Arg.getArgument().getAsType();
2034 SourceRange SR = Arg.getSourceRange();
2035 if (T->isFunctionType())
2036 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2037 else
2038 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2039 Diag(Param->getLocation(), diag::note_template_param_here);
2040 return true;
2041 }
2042
2043 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002044 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002045 break;
2046 }
2047
2048 return false;
2049 }
2050
2051
2052 // Check template template parameters.
2053 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2054
2055 // Substitute into the template parameter list of the template
2056 // template parameter, since previously-supplied template arguments
2057 // may appear within the template template parameter.
2058 {
2059 // Set up a template instantiation context.
2060 LocalInstantiationScope Scope(*this);
2061 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2062 TempParm, Converted.getFlatArguments(),
2063 Converted.flatSize(),
2064 SourceRange(TemplateLoc, RAngleLoc));
2065
2066 TemplateArgumentList TemplateArgs(Context, Converted,
2067 /*TakeArgs=*/false);
2068 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2069 SubstDecl(TempParm, CurContext,
2070 MultiLevelTemplateArgumentList(TemplateArgs)));
2071 if (!TempParm)
2072 return true;
2073
2074 // FIXME: TempParam is leaked.
2075 }
2076
2077 switch (Arg.getArgument().getKind()) {
2078 case TemplateArgument::Null:
2079 assert(false && "Should never see a NULL template argument here");
2080 return true;
2081
2082 case TemplateArgument::Template:
2083 if (CheckTemplateArgument(TempParm, Arg))
2084 return true;
2085
2086 Converted.Append(Arg.getArgument());
2087 break;
2088
2089 case TemplateArgument::Expression:
2090 case TemplateArgument::Type:
2091 // We have a template template parameter but the template
2092 // argument does not refer to a template.
2093 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2094 return true;
2095
2096 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002097 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002098 "Declaration argument with template template parameter");
2099 break;
2100 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002101 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002102 "Integral argument with template template parameter");
2103 break;
2104
2105 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002106 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002107 break;
2108 }
2109
2110 return false;
2111}
2112
Douglas Gregord32e0282009-02-09 23:23:08 +00002113/// \brief Check that the given template argument list is well-formed
2114/// for specializing the given template.
2115bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2116 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002117 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002118 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002119 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002120 TemplateParameterList *Params = Template->getTemplateParameters();
2121 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002122 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002123 bool Invalid = false;
2124
John McCall6b51f282009-11-23 01:53:49 +00002125 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2126
Mike Stump11289f42009-09-09 15:08:12 +00002127 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002128 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002129
Anders Carlsson15201f12009-06-13 02:08:00 +00002130 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002131 (NumArgs < Params->getMinRequiredArguments() &&
2132 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002133 // FIXME: point at either the first arg beyond what we can handle,
2134 // or the '>', depending on whether we have too many or too few
2135 // arguments.
2136 SourceRange Range;
2137 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002138 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002139 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2140 << (NumArgs > NumParams)
2141 << (isa<ClassTemplateDecl>(Template)? 0 :
2142 isa<FunctionTemplateDecl>(Template)? 1 :
2143 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2144 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002145 Diag(Template->getLocation(), diag::note_template_decl_here)
2146 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002147 Invalid = true;
2148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
2150 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002151 // [...] The type and form of each template-argument specified in
2152 // a template-id shall match the type and form specified for the
2153 // corresponding parameter declared by the template in its
2154 // template-parameter-list.
2155 unsigned ArgIdx = 0;
2156 for (TemplateParameterList::iterator Param = Params->begin(),
2157 ParamEnd = Params->end();
2158 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002159 if (ArgIdx > NumArgs && PartialTemplateArgs)
2160 break;
Mike Stump11289f42009-09-09 15:08:12 +00002161
Douglas Gregoreebed722009-11-11 19:41:09 +00002162 // If we have a template parameter pack, check every remaining template
2163 // argument against that template parameter pack.
2164 if ((*Param)->isTemplateParameterPack()) {
2165 Converted.BeginPack();
2166 for (; ArgIdx < NumArgs; ++ArgIdx) {
2167 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2168 TemplateLoc, RAngleLoc, Converted)) {
2169 Invalid = true;
2170 break;
2171 }
2172 }
2173 Converted.EndPack();
2174 continue;
2175 }
2176
Douglas Gregor84d49a22009-11-11 21:54:23 +00002177 if (ArgIdx < NumArgs) {
2178 // Check the template argument we were given.
2179 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2180 TemplateLoc, RAngleLoc, Converted))
2181 return true;
2182
2183 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002184 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002185
Douglas Gregor84d49a22009-11-11 21:54:23 +00002186 // We have a default template argument that we will use.
2187 TemplateArgumentLoc Arg;
2188
2189 // Retrieve the default template argument from the template
2190 // parameter. For each kind of template parameter, we substitute the
2191 // template arguments provided thus far and any "outer" template arguments
2192 // (when the template parameter was part of a nested template) into
2193 // the default argument.
2194 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2195 if (!TTP->hasDefaultArgument()) {
2196 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2197 break;
2198 }
2199
John McCallbcd03502009-12-07 02:54:59 +00002200 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002201 Template,
2202 TemplateLoc,
2203 RAngleLoc,
2204 TTP,
2205 Converted);
2206 if (!ArgType)
2207 return true;
2208
2209 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2210 ArgType);
2211 } else if (NonTypeTemplateParmDecl *NTTP
2212 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2213 if (!NTTP->hasDefaultArgument()) {
2214 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2215 break;
2216 }
2217
2218 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2219 TemplateLoc,
2220 RAngleLoc,
2221 NTTP,
2222 Converted);
2223 if (E.isInvalid())
2224 return true;
2225
2226 Expr *Ex = E.takeAs<Expr>();
2227 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2228 } else {
2229 TemplateTemplateParmDecl *TempParm
2230 = cast<TemplateTemplateParmDecl>(*Param);
2231
2232 if (!TempParm->hasDefaultArgument()) {
2233 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2234 break;
2235 }
2236
2237 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2238 TemplateLoc,
2239 RAngleLoc,
2240 TempParm,
2241 Converted);
2242 if (Name.isNull())
2243 return true;
2244
2245 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2246 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2247 TempParm->getDefaultArgument().getTemplateNameLoc());
2248 }
2249
2250 // Introduce an instantiation record that describes where we are using
2251 // the default template argument.
2252 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2253 Converted.getFlatArguments(),
2254 Converted.flatSize(),
2255 SourceRange(TemplateLoc, RAngleLoc));
2256
2257 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002258 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002259 RAngleLoc, Converted))
2260 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002261 }
2262
2263 return Invalid;
2264}
2265
2266/// \brief Check a template argument against its corresponding
2267/// template type parameter.
2268///
2269/// This routine implements the semantics of C++ [temp.arg.type]. It
2270/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002271bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002272 TypeSourceInfo *ArgInfo) {
2273 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002274 QualType Arg = ArgInfo->getType();
2275
Douglas Gregord32e0282009-02-09 23:23:08 +00002276 // C++ [temp.arg.type]p2:
2277 // A local type, a type with no linkage, an unnamed type or a type
2278 // compounded from any of these types shall not be used as a
2279 // template-argument for a template type-parameter.
2280 //
2281 // FIXME: Perform the recursive and no-linkage type checks.
2282 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002283 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002284 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002285 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002286 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002287 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2288 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2289 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2290 << QualType(Tag, 0) << SR;
2291 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002292 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002293 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2294 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002295 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2296 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002297 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2298 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
2299 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002300 }
2301
2302 return false;
2303}
2304
Douglas Gregorccb07762009-02-11 19:52:55 +00002305/// \brief Checks whether the given template argument is the address
2306/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002307static bool
2308CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2309 NonTypeTemplateParmDecl *Param,
2310 QualType ParamType,
2311 Expr *ArgIn,
2312 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002313 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002314 Expr *Arg = ArgIn;
2315 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002316
2317 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002318 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002319 Arg = Cast->getSubExpr();
2320
2321 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002322 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002323 // A template-argument for a non-type, non-template
2324 // template-parameter shall be one of: [...]
2325 //
2326 // -- the address of an object or function with external
2327 // linkage, including function templates and function
2328 // template-ids but excluding non-static class members,
2329 // expressed as & id-expression where the & is optional if
2330 // the name refers to a function or array, or if the
2331 // corresponding template-parameter is a reference; or
2332 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002333
Douglas Gregorccb07762009-02-11 19:52:55 +00002334 // Ignore (and complain about) any excess parentheses.
2335 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2336 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002337 S.Diag(Arg->getSourceRange().getBegin(),
2338 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002339 << Arg->getSourceRange();
2340 Invalid = true;
2341 }
2342
2343 Arg = Parens->getSubExpr();
2344 }
2345
Douglas Gregorb242683d2010-04-01 18:32:35 +00002346 bool AddressTaken = false;
2347 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002348 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002349 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002350 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002351 AddressTaken = true;
2352 AddrOpLoc = UnOp->getOperatorLoc();
2353 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002354 } else
2355 DRE = dyn_cast<DeclRefExpr>(Arg);
2356
Douglas Gregorb242683d2010-04-01 18:32:35 +00002357 if (!DRE) {
2358 if (S.Context.hasSameUnqualifiedType(ArgType, S.Context.OverloadTy)) {
2359 S.Diag(Arg->getLocStart(),
2360 diag::err_template_arg_unresolved_overloaded_function)
2361 << ParamType << Arg->getSourceRange();
2362 } else {
2363 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2364 << Arg->getSourceRange();
2365 }
2366 S.Diag(Param->getLocation(), diag::note_template_param_here);
2367 return true;
2368 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002369
2370 // Stop checking the precise nature of the argument if it is value dependent,
2371 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002372 if (Arg->isValueDependent()) {
2373 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002374 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002375 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002376
Douglas Gregorb242683d2010-04-01 18:32:35 +00002377 if (!isa<ValueDecl>(DRE->getDecl())) {
2378 S.Diag(Arg->getSourceRange().getBegin(),
2379 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002380 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002381 S.Diag(Param->getLocation(), diag::note_template_param_here);
2382 return true;
2383 }
2384
2385 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002386
2387 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002388 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2389 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002390 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002391 S.Diag(Param->getLocation(), diag::note_template_param_here);
2392 return true;
2393 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002394
2395 // Cannot refer to non-static member functions
2396 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002397 if (!Method->isStatic()) {
2398 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002399 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002400 S.Diag(Param->getLocation(), diag::note_template_param_here);
2401 return true;
2402 }
Mike Stump11289f42009-09-09 15:08:12 +00002403
Douglas Gregorccb07762009-02-11 19:52:55 +00002404 // Functions must have external linkage.
2405 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002406 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002407 S.Diag(Arg->getSourceRange().getBegin(),
2408 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002409 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002410 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002411 << true;
2412 return true;
2413 }
2414
2415 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002416 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002417
Douglas Gregorb242683d2010-04-01 18:32:35 +00002418 // If the template parameter has pointer type, the function decays.
2419 if (ParamType->isPointerType() && !AddressTaken)
2420 ArgType = S.Context.getPointerType(Func->getType());
2421 else if (AddressTaken && ParamType->isReferenceType()) {
2422 // If we originally had an address-of operator, but the
2423 // parameter has reference type, complain and (if things look
2424 // like they will work) drop the address-of operator.
2425 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2426 ParamType.getNonReferenceType())) {
2427 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2428 << ParamType;
2429 S.Diag(Param->getLocation(), diag::note_template_param_here);
2430 return true;
2431 }
2432
2433 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2434 << ParamType
2435 << FixItHint::CreateRemoval(AddrOpLoc);
2436 S.Diag(Param->getLocation(), diag::note_template_param_here);
2437
2438 ArgType = Func->getType();
2439 }
2440 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002441 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002442 S.Diag(Arg->getSourceRange().getBegin(),
2443 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002444 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002445 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002446 << true;
2447 return true;
2448 }
2449
Douglas Gregorb242683d2010-04-01 18:32:35 +00002450 // A value of reference type is not an object.
2451 if (Var->getType()->isReferenceType()) {
2452 S.Diag(Arg->getSourceRange().getBegin(),
2453 diag::err_template_arg_reference_var)
2454 << Var->getType() << Arg->getSourceRange();
2455 S.Diag(Param->getLocation(), diag::note_template_param_here);
2456 return true;
2457 }
2458
Douglas Gregorccb07762009-02-11 19:52:55 +00002459 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002460 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002461
2462 // If the template parameter has pointer type, we must have taken
2463 // the address of this object.
2464 if (ParamType->isReferenceType()) {
2465 if (AddressTaken) {
2466 // If we originally had an address-of operator, but the
2467 // parameter has reference type, complain and (if things look
2468 // like they will work) drop the address-of operator.
2469 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2470 ParamType.getNonReferenceType())) {
2471 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2472 << ParamType;
2473 S.Diag(Param->getLocation(), diag::note_template_param_here);
2474 return true;
2475 }
2476
2477 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2478 << ParamType
2479 << FixItHint::CreateRemoval(AddrOpLoc);
2480 S.Diag(Param->getLocation(), diag::note_template_param_here);
2481
2482 ArgType = Var->getType();
2483 }
2484 } else if (!AddressTaken && ParamType->isPointerType()) {
2485 if (Var->getType()->isArrayType()) {
2486 // Array-to-pointer decay.
2487 ArgType = S.Context.getArrayDecayedType(Var->getType());
2488 } else {
2489 // If the template parameter has pointer type but the address of
2490 // this object was not taken, complain and (possibly) recover by
2491 // taking the address of the entity.
2492 ArgType = S.Context.getPointerType(Var->getType());
2493 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2494 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2495 << ParamType;
2496 S.Diag(Param->getLocation(), diag::note_template_param_here);
2497 return true;
2498 }
2499
2500 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2501 << ParamType
2502 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2503
2504 S.Diag(Param->getLocation(), diag::note_template_param_here);
2505 }
2506 }
2507 } else {
2508 // We found something else, but we don't know specifically what it is.
2509 S.Diag(Arg->getSourceRange().getBegin(),
2510 diag::err_template_arg_not_object_or_func)
2511 << Arg->getSourceRange();
2512 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2513 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002514 }
Mike Stump11289f42009-09-09 15:08:12 +00002515
Douglas Gregorb242683d2010-04-01 18:32:35 +00002516 if (ParamType->isPointerType() &&
2517 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2518 S.IsQualificationConversion(ArgType, ParamType)) {
2519 // For pointer-to-object types, qualification conversions are
2520 // permitted.
2521 } else {
2522 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2523 if (!ParamRef->getPointeeType()->isFunctionType()) {
2524 // C++ [temp.arg.nontype]p5b3:
2525 // For a non-type template-parameter of type reference to
2526 // object, no conversions apply. The type referred to by the
2527 // reference may be more cv-qualified than the (otherwise
2528 // identical) type of the template- argument. The
2529 // template-parameter is bound directly to the
2530 // template-argument, which shall be an lvalue.
2531
2532 // FIXME: Other qualifiers?
2533 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2534 unsigned ArgQuals = ArgType.getCVRQualifiers();
2535
2536 if ((ParamQuals | ArgQuals) != ParamQuals) {
2537 S.Diag(Arg->getSourceRange().getBegin(),
2538 diag::err_template_arg_ref_bind_ignores_quals)
2539 << ParamType << Arg->getType()
2540 << Arg->getSourceRange();
2541 S.Diag(Param->getLocation(), diag::note_template_param_here);
2542 return true;
2543 }
2544 }
2545 }
2546
2547 // At this point, the template argument refers to an object or
2548 // function with external linkage. We now need to check whether the
2549 // argument and parameter types are compatible.
2550 if (!S.Context.hasSameUnqualifiedType(ArgType,
2551 ParamType.getNonReferenceType())) {
2552 // We can't perform this conversion or binding.
2553 if (ParamType->isReferenceType())
2554 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2555 << ParamType << Arg->getType() << Arg->getSourceRange();
2556 else
2557 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2558 << Arg->getType() << ParamType << Arg->getSourceRange();
2559 S.Diag(Param->getLocation(), diag::note_template_param_here);
2560 return true;
2561 }
2562 }
2563
2564 // Create the template argument.
2565 Converted = TemplateArgument(Entity->getCanonicalDecl());
2566 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002567}
2568
2569/// \brief Checks whether the given template argument is a pointer to
2570/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002571bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2572 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002573 bool Invalid = false;
2574
2575 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002576 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002577 Arg = Cast->getSubExpr();
2578
2579 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002580 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002581 // A template-argument for a non-type, non-template
2582 // template-parameter shall be one of: [...]
2583 //
2584 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002585 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002586
2587 // Ignore (and complain about) any excess parentheses.
2588 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2589 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002590 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002591 diag::err_template_arg_extra_parens)
2592 << Arg->getSourceRange();
2593 Invalid = true;
2594 }
2595
2596 Arg = Parens->getSubExpr();
2597 }
2598
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002599 // A pointer-to-member constant written &Class::member.
2600 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002601 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2602 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2603 if (DRE && !DRE->getQualifier())
2604 DRE = 0;
2605 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002606 }
2607 // A constant of pointer-to-member type.
2608 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2609 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2610 if (VD->getType()->isMemberPointerType()) {
2611 if (isa<NonTypeTemplateParmDecl>(VD) ||
2612 (isa<VarDecl>(VD) &&
2613 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2614 if (Arg->isTypeDependent() || Arg->isValueDependent())
2615 Converted = TemplateArgument(Arg->Retain());
2616 else
2617 Converted = TemplateArgument(VD->getCanonicalDecl());
2618 return Invalid;
2619 }
2620 }
2621 }
2622
2623 DRE = 0;
2624 }
2625
Douglas Gregorccb07762009-02-11 19:52:55 +00002626 if (!DRE)
2627 return Diag(Arg->getSourceRange().getBegin(),
2628 diag::err_template_arg_not_pointer_to_member_form)
2629 << Arg->getSourceRange();
2630
2631 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2632 assert((isa<FieldDecl>(DRE->getDecl()) ||
2633 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2634 "Only non-static member pointers can make it here");
2635
2636 // Okay: this is the address of a non-static member, and therefore
2637 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002638 if (Arg->isTypeDependent() || Arg->isValueDependent())
2639 Converted = TemplateArgument(Arg->Retain());
2640 else
2641 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002642 return Invalid;
2643 }
2644
2645 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002646 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002647 diag::err_template_arg_not_pointer_to_member_form)
2648 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002649 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002650 diag::note_template_arg_refers_here);
2651 return true;
2652}
2653
Douglas Gregord32e0282009-02-09 23:23:08 +00002654/// \brief Check a template argument against its corresponding
2655/// non-type template parameter.
2656///
Douglas Gregor463421d2009-03-03 04:44:36 +00002657/// This routine implements the semantics of C++ [temp.arg.nontype].
2658/// It returns true if an error occurred, and false otherwise. \p
2659/// InstantiatedParamType is the type of the non-type template
2660/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002661///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002662/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002663bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002664 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002665 TemplateArgument &Converted,
2666 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002667 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2668
Douglas Gregor86560402009-02-10 23:36:10 +00002669 // If either the parameter has a dependent type or the argument is
2670 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002671 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2672 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002673 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002674 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002675 }
Douglas Gregor86560402009-02-10 23:36:10 +00002676
2677 // C++ [temp.arg.nontype]p5:
2678 // The following conversions are performed on each expression used
2679 // as a non-type template-argument. If a non-type
2680 // template-argument cannot be converted to the type of the
2681 // corresponding template-parameter then the program is
2682 // ill-formed.
2683 //
2684 // -- for a non-type template-parameter of integral or
2685 // enumeration type, integral promotions (4.5) and integral
2686 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002687 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002688 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002689 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002690 // C++ [temp.arg.nontype]p1:
2691 // A template-argument for a non-type, non-template
2692 // template-parameter shall be one of:
2693 //
2694 // -- an integral constant-expression of integral or enumeration
2695 // type; or
2696 // -- the name of a non-type template-parameter; or
2697 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002698 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002699 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002700 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002701 diag::err_template_arg_not_integral_or_enumeral)
2702 << ArgType << Arg->getSourceRange();
2703 Diag(Param->getLocation(), diag::note_template_param_here);
2704 return true;
2705 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002706 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002707 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2708 << ArgType << Arg->getSourceRange();
2709 return true;
2710 }
2711
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002712 // From here on out, all we care about are the unqualified forms
2713 // of the parameter and argument types.
2714 ParamType = ParamType.getUnqualifiedType();
2715 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002716
2717 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002718 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002719 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002720 } else if (CTAK == CTAK_Deduced) {
2721 // C++ [temp.deduct.type]p17:
2722 // If, in the declaration of a function template with a non-type
2723 // template-parameter, the non-type template- parameter is used
2724 // in an expression in the function parameter-list and, if the
2725 // corresponding template-argument is deduced, the
2726 // template-argument type shall match the type of the
2727 // template-parameter exactly, except that a template-argument
2728 // deduced from an array bound may be of any integral type.
2729 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2730 << ArgType << ParamType;
2731 Diag(Param->getLocation(), diag::note_template_param_here);
2732 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002733 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2734 !ParamType->isEnumeralType()) {
2735 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002736 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002737 } else {
2738 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002739 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002740 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002741 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002742 Diag(Param->getLocation(), diag::note_template_param_here);
2743 return true;
2744 }
2745
Douglas Gregor52aba872009-03-14 00:20:21 +00002746 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002747 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002748 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002749
2750 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002751 llvm::APSInt OldValue = Value;
2752
2753 // Coerce the template argument's value to the value it will have
2754 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002755 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002756 if (Value.getBitWidth() != AllowedBits)
2757 Value.extOrTrunc(AllowedBits);
2758 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002759
2760 // Complain if an unsigned parameter received a negative value.
2761 if (IntegerType->isUnsignedIntegerType()
2762 && (OldValue.isSigned() && OldValue.isNegative())) {
2763 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2764 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2765 << Arg->getSourceRange();
2766 Diag(Param->getLocation(), diag::note_template_param_here);
2767 }
2768
2769 // Complain if we overflowed the template parameter's type.
2770 unsigned RequiredBits;
2771 if (IntegerType->isUnsignedIntegerType())
2772 RequiredBits = OldValue.getActiveBits();
2773 else if (OldValue.isUnsigned())
2774 RequiredBits = OldValue.getActiveBits() + 1;
2775 else
2776 RequiredBits = OldValue.getMinSignedBits();
2777 if (RequiredBits > AllowedBits) {
2778 Diag(Arg->getSourceRange().getBegin(),
2779 diag::warn_template_arg_too_large)
2780 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2781 << Arg->getSourceRange();
2782 Diag(Param->getLocation(), diag::note_template_param_here);
2783 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002784 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002785
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002786 // Add the value of this argument to the list of converted
2787 // arguments. We use the bitwidth and signedness of the template
2788 // parameter.
2789 if (Arg->isValueDependent()) {
2790 // The argument is value-dependent. Create a new
2791 // TemplateArgument with the converted expression.
2792 Converted = TemplateArgument(Arg);
2793 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002794 }
2795
John McCall0ad16662009-10-29 08:12:44 +00002796 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002797 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002798 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002799 return false;
2800 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002801
John McCall16df1e52010-03-30 21:47:33 +00002802 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2803
Douglas Gregorb242683d2010-04-01 18:32:35 +00002804 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2805 // from a template argument of type std::nullptr_t to a non-type
2806 // template parameter of type pointer to object, pointer to
2807 // function, or pointer-to-member, respectively.
2808 if (ArgType->isNullPtrType() &&
2809 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2810 Converted = TemplateArgument((NamedDecl *)0);
2811 return false;
2812 }
2813
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002814 // Handle pointer-to-function, reference-to-function, and
2815 // pointer-to-member-function all in (roughly) the same way.
2816 if (// -- For a non-type template-parameter of type pointer to
2817 // function, only the function-to-pointer conversion (4.3) is
2818 // applied. If the template-argument represents a set of
2819 // overloaded functions (or a pointer to such), the matching
2820 // function is selected from the set (13.4).
2821 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002822 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002823 // -- For a non-type template-parameter of type reference to
2824 // function, no conversions apply. If the template-argument
2825 // represents a set of overloaded functions, the matching
2826 // function is selected from the set (13.4).
2827 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002828 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002829 // -- For a non-type template-parameter of type pointer to
2830 // member function, no conversions apply. If the
2831 // template-argument represents a set of overloaded member
2832 // functions, the matching member function is selected from
2833 // the set (13.4).
2834 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002835 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002836 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002837
2838 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2839 true,
2840 FoundResult)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002841 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2842 return true;
2843
John McCall16df1e52010-03-30 21:47:33 +00002844 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002845 ArgType = Arg->getType();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002846 }
2847
Douglas Gregorb242683d2010-04-01 18:32:35 +00002848 if (!ParamType->isMemberPointerType())
2849 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2850 ParamType,
2851 Arg, Converted);
2852
2853 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2854 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2855 Arg->isLvalue(Context) == Expr::LV_Valid);
2856 } else if (!Context.hasSameUnqualifiedType(ArgType,
2857 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002858 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002859 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002860 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002861 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002862 Diag(Param->getLocation(), diag::note_template_param_here);
2863 return true;
2864 }
Mike Stump11289f42009-09-09 15:08:12 +00002865
Douglas Gregorb242683d2010-04-01 18:32:35 +00002866 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002867 }
2868
Chris Lattner696197c2009-02-20 21:37:53 +00002869 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002870 // -- for a non-type template-parameter of type pointer to
2871 // object, qualification conversions (4.4) and the
2872 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002873 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002874 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002875 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002876
Douglas Gregorb242683d2010-04-01 18:32:35 +00002877 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2878 ParamType,
2879 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002880 }
Mike Stump11289f42009-09-09 15:08:12 +00002881
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002882 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002883 // -- For a non-type template-parameter of type reference to
2884 // object, no conversions apply. The type referred to by the
2885 // reference may be more cv-qualified than the (otherwise
2886 // identical) type of the template-argument. The
2887 // template-parameter is bound directly to the
2888 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002889 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002890 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002891
Douglas Gregorb242683d2010-04-01 18:32:35 +00002892 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2893 ParamRefType->getPointeeType(),
2894 true,
2895 FoundResult)) {
2896 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2897 return true;
2898
2899 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2900 ArgType = Arg->getType();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002901 }
2902
Douglas Gregorb242683d2010-04-01 18:32:35 +00002903 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2904 ParamType,
2905 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002906 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002907
2908 // -- For a non-type template-parameter of type pointer to data
2909 // member, qualification conversions (4.4) are applied.
2910 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2911
Douglas Gregor1515f762009-02-11 18:22:40 +00002912 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00002913 // Types match exactly: nothing more to do here.
2914 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002915 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2916 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor0e558532009-02-11 16:16:59 +00002917 } else {
2918 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002919 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00002920 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002921 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00002922 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00002923 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00002924 }
2925
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002926 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00002927}
2928
2929/// \brief Check a template argument against its corresponding
2930/// template template parameter.
2931///
2932/// This routine implements the semantics of C++ [temp.arg.template].
2933/// It returns true if an error occurred, and false otherwise.
2934bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002935 const TemplateArgumentLoc &Arg) {
2936 TemplateName Name = Arg.getArgument().getAsTemplate();
2937 TemplateDecl *Template = Name.getAsTemplateDecl();
2938 if (!Template) {
2939 // Any dependent template name is fine.
2940 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
2941 return false;
2942 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00002943
2944 // C++ [temp.arg.template]p1:
2945 // A template-argument for a template template-parameter shall be
2946 // the name of a class template, expressed as id-expression. Only
2947 // primary class templates are considered when matching the
2948 // template template argument with the corresponding parameter;
2949 // partial specializations are not considered even if their
2950 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00002951 //
2952 // Note that we also allow template template parameters here, which
2953 // will happen when we are dealing with, e.g., class template
2954 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002955 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00002956 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00002957 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00002958 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002959 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002960 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00002961 << Template;
2962 }
2963
2964 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
2965 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00002966 true,
2967 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002968 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00002969}
2970
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002971/// \brief Given a non-type template argument that refers to a
2972/// declaration and the type of its corresponding non-type template
2973/// parameter, produce an expression that properly refers to that
2974/// declaration.
2975Sema::OwningExprResult
2976Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
2977 QualType ParamType,
2978 SourceLocation Loc) {
2979 assert(Arg.getKind() == TemplateArgument::Declaration &&
2980 "Only declaration template arguments permitted here");
2981 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
2982
2983 if (VD->getDeclContext()->isRecord() &&
2984 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
2985 // If the value is a class member, we might have a pointer-to-member.
2986 // Determine whether the non-type template template parameter is of
2987 // pointer-to-member type. If so, we need to build an appropriate
2988 // expression for a pointer-to-member, since a "normal" DeclRefExpr
2989 // would refer to the member itself.
2990 if (ParamType->isMemberPointerType()) {
2991 QualType ClassType
2992 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
2993 NestedNameSpecifier *Qualifier
2994 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
2995 CXXScopeSpec SS;
2996 SS.setScopeRep(Qualifier);
2997 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
2998 VD->getType().getNonReferenceType(),
2999 Loc,
3000 &SS);
3001 if (RefExpr.isInvalid())
3002 return ExprError();
3003
3004 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
3005 assert(!RefExpr.isInvalid() &&
3006 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
3007 ParamType));
3008 return move(RefExpr);
3009 }
3010 }
3011
3012 QualType T = VD->getType().getNonReferenceType();
3013 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003014 // When the non-type template parameter is a pointer, take the
3015 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003016 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3017 if (RefExpr.isInvalid())
3018 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003019
3020 if (T->isFunctionType() || T->isArrayType()) {
3021 // Decay functions and arrays.
3022 Expr *RefE = (Expr *)RefExpr.get();
3023 DefaultFunctionArrayConversion(RefE);
3024 if (RefE != RefExpr.get()) {
3025 RefExpr.release();
3026 RefExpr = Owned(RefE);
3027 }
3028
3029 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003030 }
3031
Douglas Gregorb242683d2010-04-01 18:32:35 +00003032 // Take the address of everything else
3033 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003034 }
3035
3036 // If the non-type template parameter has reference type, qualify the
3037 // resulting declaration reference with the extra qualifiers on the
3038 // type that the reference refers to.
3039 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3040 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3041
3042 return BuildDeclRefExpr(VD, T, Loc);
3043}
3044
3045/// \brief Construct a new expression that refers to the given
3046/// integral template argument with the given source-location
3047/// information.
3048///
3049/// This routine takes care of the mapping from an integral template
3050/// argument (which may have any integral type) to the appropriate
3051/// literal value.
3052Sema::OwningExprResult
3053Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3054 SourceLocation Loc) {
3055 assert(Arg.getKind() == TemplateArgument::Integral &&
3056 "Operation is only value for integral template arguments");
3057 QualType T = Arg.getIntegralType();
3058 if (T->isCharType() || T->isWideCharType())
3059 return Owned(new (Context) CharacterLiteral(
3060 Arg.getAsIntegral()->getZExtValue(),
3061 T->isWideCharType(),
3062 T,
3063 Loc));
3064 if (T->isBooleanType())
3065 return Owned(new (Context) CXXBoolLiteralExpr(
3066 Arg.getAsIntegral()->getBoolValue(),
3067 T,
3068 Loc));
3069
3070 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3071}
3072
3073
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003074/// \brief Determine whether the given template parameter lists are
3075/// equivalent.
3076///
Mike Stump11289f42009-09-09 15:08:12 +00003077/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003078/// source code as part of a new template declaration.
3079///
3080/// \param Old The old template parameter list, typically found via
3081/// name lookup of the template declared with this template parameter
3082/// list.
3083///
3084/// \param Complain If true, this routine will produce a diagnostic if
3085/// the template parameter lists are not equivalent.
3086///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003087/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003088///
3089/// \param TemplateArgLoc If this source location is valid, then we
3090/// are actually checking the template parameter list of a template
3091/// argument (New) against the template parameter list of its
3092/// corresponding template template parameter (Old). We produce
3093/// slightly different diagnostics in this scenario.
3094///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003095/// \returns True if the template parameter lists are equal, false
3096/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003097bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003098Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3099 TemplateParameterList *Old,
3100 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003101 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003102 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003103 if (Old->size() != New->size()) {
3104 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003105 unsigned NextDiag = diag::err_template_param_list_different_arity;
3106 if (TemplateArgLoc.isValid()) {
3107 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3108 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003109 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003110 Diag(New->getTemplateLoc(), NextDiag)
3111 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003112 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003113 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003114 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003115 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003116 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3117 }
3118
3119 return false;
3120 }
3121
3122 for (TemplateParameterList::iterator OldParm = Old->begin(),
3123 OldParmEnd = Old->end(), NewParm = New->begin();
3124 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3125 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003126 if (Complain) {
3127 unsigned NextDiag = diag::err_template_param_different_kind;
3128 if (TemplateArgLoc.isValid()) {
3129 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3130 NextDiag = diag::note_template_param_different_kind;
3131 }
3132 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003133 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003134 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003135 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003136 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003137 return false;
3138 }
3139
3140 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3141 // Okay; all template type parameters are equivalent (since we
Douglas Gregor85e0f662009-02-10 00:24:35 +00003142 // know we're at the same index).
Mike Stump11289f42009-09-09 15:08:12 +00003143 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003144 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3145 // The types of non-type template parameters must agree.
3146 NonTypeTemplateParmDecl *NewNTTP
3147 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003148
3149 // If we are matching a template template argument to a template
3150 // template parameter and one of the non-type template parameter types
3151 // is dependent, then we must wait until template instantiation time
3152 // to actually compare the arguments.
3153 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3154 (OldNTTP->getType()->isDependentType() ||
3155 NewNTTP->getType()->isDependentType()))
3156 continue;
3157
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003158 if (Context.getCanonicalType(OldNTTP->getType()) !=
3159 Context.getCanonicalType(NewNTTP->getType())) {
3160 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003161 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3162 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003163 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003164 diag::err_template_arg_template_params_mismatch);
3165 NextDiag = diag::note_template_nontype_parm_different_type;
3166 }
3167 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003168 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003169 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003170 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003171 diag::note_template_nontype_parm_prev_declaration)
3172 << OldNTTP->getType();
3173 }
3174 return false;
3175 }
3176 } else {
3177 // The template parameter lists of template template
3178 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003179 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003180 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003181 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003182 = cast<TemplateTemplateParmDecl>(*OldParm);
3183 TemplateTemplateParmDecl *NewTTP
3184 = cast<TemplateTemplateParmDecl>(*NewParm);
3185 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3186 OldTTP->getTemplateParameters(),
3187 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003188 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003189 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003190 return false;
3191 }
3192 }
3193
3194 return true;
3195}
3196
3197/// \brief Check whether a template can be declared within this scope.
3198///
3199/// If the template declaration is valid in this scope, returns
3200/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003201bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003202Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003203 // Find the nearest enclosing declaration scope.
3204 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3205 (S->getFlags() & Scope::TemplateParamScope) != 0)
3206 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003207
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003208 // C++ [temp]p2:
3209 // A template-declaration can appear only as a namespace scope or
3210 // class scope declaration.
3211 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003212 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3213 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003214 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003215 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003216
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003217 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003218 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003219
3220 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3221 return false;
3222
Mike Stump11289f42009-09-09 15:08:12 +00003223 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003224 diag::err_template_outside_namespace_or_class_scope)
3225 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003226}
Douglas Gregor67a65642009-02-17 23:15:12 +00003227
Douglas Gregor54888652009-10-07 00:13:32 +00003228/// \brief Determine what kind of template specialization the given declaration
3229/// is.
3230static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3231 if (!D)
3232 return TSK_Undeclared;
3233
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003234 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3235 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003236 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3237 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003238 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3239 return Var->getTemplateSpecializationKind();
3240
Douglas Gregor54888652009-10-07 00:13:32 +00003241 return TSK_Undeclared;
3242}
3243
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003244/// \brief Check whether a specialization is well-formed in the current
3245/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003246///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003247/// This routine determines whether a template specialization can be declared
3248/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003249///
3250/// \param S the semantic analysis object for which this check is being
3251/// performed.
3252///
3253/// \param Specialized the entity being specialized or instantiated, which
3254/// may be a kind of template (class template, function template, etc.) or
3255/// a member of a class template (member function, static data member,
3256/// member class).
3257///
3258/// \param PrevDecl the previous declaration of this entity, if any.
3259///
3260/// \param Loc the location of the explicit specialization or instantiation of
3261/// this entity.
3262///
3263/// \param IsPartialSpecialization whether this is a partial specialization of
3264/// a class template.
3265///
Douglas Gregor54888652009-10-07 00:13:32 +00003266/// \returns true if there was an error that we cannot recover from, false
3267/// otherwise.
3268static bool CheckTemplateSpecializationScope(Sema &S,
3269 NamedDecl *Specialized,
3270 NamedDecl *PrevDecl,
3271 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003272 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003273 // Keep these "kind" numbers in sync with the %select statements in the
3274 // various diagnostics emitted by this routine.
3275 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003276 bool isTemplateSpecialization = false;
3277 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003278 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003279 isTemplateSpecialization = true;
3280 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003281 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003282 isTemplateSpecialization = true;
3283 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003284 EntityKind = 3;
3285 else if (isa<VarDecl>(Specialized))
3286 EntityKind = 4;
3287 else if (isa<RecordDecl>(Specialized))
3288 EntityKind = 5;
3289 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003290 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3291 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003292 return true;
3293 }
3294
Douglas Gregorf47b9112009-02-25 22:02:03 +00003295 // C++ [temp.expl.spec]p2:
3296 // An explicit specialization shall be declared in the namespace
3297 // of which the template is a member, or, for member templates, in
3298 // the namespace of which the enclosing class or enclosing class
3299 // template is a member. An explicit specialization of a member
3300 // function, member class or static data member of a class
3301 // template shall be declared in the namespace of which the class
3302 // template is a member. Such a declaration may also be a
3303 // definition. If the declaration is not a definition, the
3304 // specialization may be defined later in the name- space in which
3305 // the explicit specialization was declared, or in a namespace
3306 // that encloses the one in which the explicit specialization was
3307 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003308 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3309 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003310 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003311 return true;
3312 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003313
Douglas Gregor40fb7442009-10-07 17:30:37 +00003314 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3315 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003316 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003317 return true;
3318 }
3319
Douglas Gregore4b05162009-10-07 17:21:34 +00003320 // C++ [temp.class.spec]p6:
3321 // A class template partial specialization may be declared or redeclared
3322 // in any namespace scope in which its definition may be defined (14.5.1
3323 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003324 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003325 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003326 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003327 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003328 if ((!PrevDecl ||
3329 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3330 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3331 // There is no prior declaration of this entity, so this
3332 // specialization must be in the same context as the template
3333 // itself.
3334 if (!DC->Equals(SpecializedContext)) {
3335 if (isa<TranslationUnitDecl>(SpecializedContext))
3336 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3337 << EntityKind << Specialized;
3338 else if (isa<NamespaceDecl>(SpecializedContext))
3339 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3340 << EntityKind << Specialized
3341 << cast<NamedDecl>(SpecializedContext);
3342
3343 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3344 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003345 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003346 }
Douglas Gregor54888652009-10-07 00:13:32 +00003347
3348 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003349 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003350 // Note that HandleDeclarator() performs this check for explicit
3351 // specializations of function templates, static data members, and member
3352 // functions, so we skip the check here for those kinds of entities.
3353 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003354 // Should we refactor that check, so that it occurs later?
3355 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003356 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3357 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003358 if (isa<TranslationUnitDecl>(SpecializedContext))
3359 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3360 << EntityKind << Specialized;
3361 else if (isa<NamespaceDecl>(SpecializedContext))
3362 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3363 << EntityKind << Specialized
3364 << cast<NamedDecl>(SpecializedContext);
3365
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003366 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003367 }
Douglas Gregor54888652009-10-07 00:13:32 +00003368
3369 // FIXME: check for specialization-after-instantiation errors and such.
3370
Douglas Gregorf47b9112009-02-25 22:02:03 +00003371 return false;
3372}
Douglas Gregor54888652009-10-07 00:13:32 +00003373
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003374/// \brief Check the non-type template arguments of a class template
3375/// partial specialization according to C++ [temp.class.spec]p9.
3376///
Douglas Gregor09a30232009-06-12 22:08:06 +00003377/// \param TemplateParams the template parameters of the primary class
3378/// template.
3379///
3380/// \param TemplateArg the template arguments of the class template
3381/// partial specialization.
3382///
3383/// \param MirrorsPrimaryTemplate will be set true if the class
3384/// template partial specialization arguments are identical to the
3385/// implicit template arguments of the primary template. This is not
3386/// necessarily an error (C++0x), and it is left to the caller to diagnose
3387/// this condition when it is an error.
3388///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003389/// \returns true if there was an error, false otherwise.
3390bool Sema::CheckClassTemplatePartialSpecializationArgs(
3391 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003392 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003393 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003394 // FIXME: the interface to this function will have to change to
3395 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003396 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003397
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003398 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003399
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003400 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003401 // Determine whether the template argument list of the partial
3402 // specialization is identical to the implicit argument list of
3403 // the primary template. The caller may need to diagnostic this as
3404 // an error per C++ [temp.class.spec]p9b3.
3405 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003406 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003407 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3408 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003409 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003410 MirrorsPrimaryTemplate = false;
3411 } else if (TemplateTemplateParmDecl *TTP
3412 = dyn_cast<TemplateTemplateParmDecl>(
3413 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003414 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003415 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003416 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003417 if (!ArgDecl ||
3418 ArgDecl->getIndex() != TTP->getIndex() ||
3419 ArgDecl->getDepth() != TTP->getDepth())
3420 MirrorsPrimaryTemplate = false;
3421 }
3422 }
3423
Mike Stump11289f42009-09-09 15:08:12 +00003424 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003425 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003426 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003427 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003428 }
3429
Anders Carlsson40c1d492009-06-13 18:20:51 +00003430 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003431 if (!ArgExpr) {
3432 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003433 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003434 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003435
3436 // C++ [temp.class.spec]p8:
3437 // A non-type argument is non-specialized if it is the name of a
3438 // non-type parameter. All other non-type arguments are
3439 // specialized.
3440 //
3441 // Below, we check the two conditions that only apply to
3442 // specialized non-type arguments, so skip any non-specialized
3443 // arguments.
3444 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003445 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003446 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003447 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003448 (Param->getIndex() != NTTP->getIndex() ||
3449 Param->getDepth() != NTTP->getDepth()))
3450 MirrorsPrimaryTemplate = false;
3451
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003452 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003453 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003454
3455 // C++ [temp.class.spec]p9:
3456 // Within the argument list of a class template partial
3457 // specialization, the following restrictions apply:
3458 // -- A partially specialized non-type argument expression
3459 // shall not involve a template parameter of the partial
3460 // specialization except when the argument expression is a
3461 // simple identifier.
3462 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003463 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003464 diag::err_dependent_non_type_arg_in_partial_spec)
3465 << ArgExpr->getSourceRange();
3466 return true;
3467 }
3468
3469 // -- The type of a template parameter corresponding to a
3470 // specialized non-type argument shall not be dependent on a
3471 // parameter of the specialization.
3472 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003473 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003474 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3475 << Param->getType()
3476 << ArgExpr->getSourceRange();
3477 Diag(Param->getLocation(), diag::note_template_param_here);
3478 return true;
3479 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003480
3481 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003482 }
3483
3484 return false;
3485}
3486
Douglas Gregorc854c662010-02-26 06:03:23 +00003487/// \brief Retrieve the previous declaration of the given declaration.
3488static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3489 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3490 return VD->getPreviousDeclaration();
3491 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3492 return FD->getPreviousDeclaration();
3493 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3494 return TD->getPreviousDeclaration();
3495 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3496 return TD->getPreviousDeclaration();
3497 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3498 return FTD->getPreviousDeclaration();
3499 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3500 return CTD->getPreviousDeclaration();
3501 return 0;
3502}
3503
Douglas Gregorc08f4892009-03-25 00:13:59 +00003504Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003505Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3506 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003507 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003508 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003509 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003510 SourceLocation TemplateNameLoc,
3511 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003512 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003513 SourceLocation RAngleLoc,
3514 AttributeList *Attr,
3515 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003516 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003517
Douglas Gregor67a65642009-02-17 23:15:12 +00003518 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003519 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003520 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003521 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3522
3523 if (!ClassTemplate) {
3524 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3525 << (Name.getAsTemplateDecl() &&
3526 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3527 return true;
3528 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003529
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003530 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003531 bool isPartialSpecialization = false;
3532
Douglas Gregorf47b9112009-02-25 22:02:03 +00003533 // Check the validity of the template headers that introduce this
3534 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003535 // FIXME: We probably shouldn't complain about these headers for
3536 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003537 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003538 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3539 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003540 TemplateParameterLists.size(),
3541 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003542 if (TemplateParams && TemplateParams->size() > 0) {
3543 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003544
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003545 // C++ [temp.class.spec]p10:
3546 // The template parameter list of a specialization shall not
3547 // contain default template argument values.
3548 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3549 Decl *Param = TemplateParams->getParam(I);
3550 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3551 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003552 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003553 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003554 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003555 }
3556 } else if (NonTypeTemplateParmDecl *NTTP
3557 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3558 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003559 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003560 diag::err_default_arg_in_partial_spec)
3561 << DefArg->getSourceRange();
3562 NTTP->setDefaultArgument(0);
3563 DefArg->Destroy(Context);
3564 }
3565 } else {
3566 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003567 if (TTP->hasDefaultArgument()) {
3568 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003569 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003570 << TTP->getDefaultArgument().getSourceRange();
3571 TTP->setDefaultArgument(TemplateArgumentLoc());
Douglas Gregord5222052009-06-12 19:43:02 +00003572 }
3573 }
3574 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003575 } else if (TemplateParams) {
3576 if (TUK == TUK_Friend)
3577 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003578 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003579 SourceRange(TemplateParams->getTemplateLoc(),
3580 TemplateParams->getRAngleLoc()))
3581 << SourceRange(LAngleLoc, RAngleLoc);
3582 else
3583 isExplicitSpecialization = true;
3584 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003585 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003586 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003587 isExplicitSpecialization = true;
3588 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003589
Douglas Gregor67a65642009-02-17 23:15:12 +00003590 // Check that the specialization uses the same tag kind as the
3591 // original template.
3592 TagDecl::TagKind Kind;
3593 switch (TagSpec) {
3594 default: assert(0 && "Unknown tag type!");
3595 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3596 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3597 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3598 }
Douglas Gregord9034f02009-05-14 16:41:31 +00003599 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003600 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003601 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003602 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003603 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003604 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003605 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003606 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003607 diag::note_previous_use);
3608 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3609 }
3610
Douglas Gregorc40290e2009-03-09 23:48:35 +00003611 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003612 TemplateArgumentListInfo TemplateArgs;
3613 TemplateArgs.setLAngleLoc(LAngleLoc);
3614 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003615 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003616
Douglas Gregor67a65642009-02-17 23:15:12 +00003617 // Check that the template argument list is well-formed for this
3618 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003619 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3620 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003621 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3622 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003623 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003624
Mike Stump11289f42009-09-09 15:08:12 +00003625 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003626 ClassTemplate->getTemplateParameters()->size()) &&
3627 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003628
Douglas Gregor2373c592009-05-31 09:31:02 +00003629 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003630 // corresponds to these arguments.
3631 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003632 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003633 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003634 if (CheckClassTemplatePartialSpecializationArgs(
3635 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003636 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003637 return true;
3638
Douglas Gregor09a30232009-06-12 22:08:06 +00003639 if (MirrorsPrimaryTemplate) {
3640 // C++ [temp.class.spec]p9b3:
3641 //
Mike Stump11289f42009-09-09 15:08:12 +00003642 // -- The argument list of the specialization shall not be identical
3643 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003644 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003645 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003646 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003647 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003648 ClassTemplate->getIdentifier(),
3649 TemplateNameLoc,
3650 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003651 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003652 AS_none);
3653 }
3654
Douglas Gregor2208a292009-09-26 20:57:03 +00003655 // FIXME: Diagnose friend partial specializations
3656
Douglas Gregor92354b62010-02-09 00:37:32 +00003657 if (!Name.isDependent() &&
3658 !TemplateSpecializationType::anyDependentTemplateArguments(
3659 TemplateArgs.getArgumentArray(),
3660 TemplateArgs.size())) {
3661 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3662 << ClassTemplate->getDeclName();
3663 isPartialSpecialization = false;
3664 } else {
3665 // FIXME: Template parameter list matters, too
3666 ClassTemplatePartialSpecializationDecl::Profile(ID,
3667 Converted.getFlatArguments(),
3668 Converted.flatSize(),
3669 Context);
3670 }
3671 }
3672
3673 if (!isPartialSpecialization)
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003674 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003675 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003676 Converted.flatSize(),
3677 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003678 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003679 ClassTemplateSpecializationDecl *PrevDecl = 0;
3680
3681 if (isPartialSpecialization)
3682 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003683 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003684 InsertPos);
3685 else
3686 PrevDecl
3687 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003688
3689 ClassTemplateSpecializationDecl *Specialization = 0;
3690
Douglas Gregorf47b9112009-02-25 22:02:03 +00003691 // Check whether we can declare a class template specialization in
3692 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003693 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003694 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003695 TemplateNameLoc,
3696 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003697 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003698
Douglas Gregor15301382009-07-30 17:40:51 +00003699 // The canonical type
3700 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003701 if (PrevDecl &&
3702 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003703 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003704 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003705 // arguments was referenced but not declared, or we're only
3706 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003707 // declaration node as our own, updating its source location to
3708 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003709 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003710 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003711 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003712 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003713 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003714 // Build the canonical type that describes the converted template
3715 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003716 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3717 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003718 Converted.getFlatArguments(),
3719 Converted.flatSize());
3720
Douglas Gregor2373c592009-05-31 09:31:02 +00003721 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003722 ClassTemplatePartialSpecializationDecl *PrevPartial
3723 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00003724 ClassTemplatePartialSpecializationDecl *Partial
3725 = ClassTemplatePartialSpecializationDecl::Create(Context,
Douglas Gregor2373c592009-05-31 09:31:02 +00003726 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003727 TemplateNameLoc,
3728 TemplateParams,
3729 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003730 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003731 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003732 CanonType,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003733 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00003734 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor2373c592009-05-31 09:31:02 +00003735
3736 if (PrevPartial) {
3737 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3738 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3739 } else {
3740 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3741 }
3742 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003743
Douglas Gregor21610382009-10-29 00:04:11 +00003744 // If we are providing an explicit specialization of a member class
3745 // template specialization, make a note of that.
3746 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3747 PrevPartial->setMemberSpecialization();
3748
Douglas Gregor91772d12009-06-13 00:26:55 +00003749 // Check that all of the template parameters of the class template
3750 // partial specialization are deducible from the template
3751 // arguments. If not, this class template partial specialization
3752 // will never be used.
3753 llvm::SmallVector<bool, 8> DeducibleParams;
3754 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003755 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003756 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003757 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003758 unsigned NumNonDeducible = 0;
3759 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3760 if (!DeducibleParams[I])
3761 ++NumNonDeducible;
3762
3763 if (NumNonDeducible) {
3764 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3765 << (NumNonDeducible > 1)
3766 << SourceRange(TemplateNameLoc, RAngleLoc);
3767 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3768 if (!DeducibleParams[I]) {
3769 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3770 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003771 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003772 diag::note_partial_spec_unused_parameter)
3773 << Param->getDeclName();
3774 else
Mike Stump11289f42009-09-09 15:08:12 +00003775 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003776 diag::note_partial_spec_unused_parameter)
3777 << std::string("<anonymous>");
3778 }
3779 }
3780 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003781 } else {
3782 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003783 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003784 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00003785 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor67a65642009-02-17 23:15:12 +00003786 ClassTemplate->getDeclContext(),
3787 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003788 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003789 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003790 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003791 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor67a65642009-02-17 23:15:12 +00003792
3793 if (PrevDecl) {
3794 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3795 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3796 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003797 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003798 InsertPos);
3799 }
Douglas Gregor15301382009-07-30 17:40:51 +00003800
3801 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003802 }
3803
Douglas Gregor06db9f52009-10-12 20:18:28 +00003804 // C++ [temp.expl.spec]p6:
3805 // If a template, a member template or the member of a class template is
3806 // explicitly specialized then that specialization shall be declared
3807 // before the first use of that specialization that would cause an implicit
3808 // instantiation to take place, in every translation unit in which such a
3809 // use occurs; no diagnostic is required.
3810 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003811 bool Okay = false;
3812 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3813 // Is there any previous explicit specialization declaration?
3814 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3815 Okay = true;
3816 break;
3817 }
3818 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003819
Douglas Gregorc854c662010-02-26 06:03:23 +00003820 if (!Okay) {
3821 SourceRange Range(TemplateNameLoc, RAngleLoc);
3822 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3823 << Context.getTypeDeclType(Specialization) << Range;
3824
3825 Diag(PrevDecl->getPointOfInstantiation(),
3826 diag::note_instantiation_required_here)
3827 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003828 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003829 return true;
3830 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003831 }
3832
Douglas Gregor2208a292009-09-26 20:57:03 +00003833 // If this is not a friend, note that this is an explicit specialization.
3834 if (TUK != TUK_Friend)
3835 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003836
3837 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003838 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003839 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003840 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003841 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003842 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003843 Diag(Def->getLocation(), diag::note_previous_definition);
3844 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003845 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003846 }
3847 }
3848
Douglas Gregord56a91e2009-02-26 22:19:44 +00003849 // Build the fully-sugared type for this class template
3850 // specialization as the user wrote in the specialization
3851 // itself. This means that we'll pretty-print the type retrieved
3852 // from the specialization's declaration the way that the user
3853 // actually wrote the specialization, rather than formatting the
3854 // name based on the "canonical" representation used to store the
3855 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003856 TypeSourceInfo *WrittenTy
3857 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3858 TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003859 if (TUK != TUK_Friend)
3860 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003861 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003862
Douglas Gregor1e249f82009-02-25 22:18:32 +00003863 // C++ [temp.expl.spec]p9:
3864 // A template explicit specialization is in the scope of the
3865 // namespace in which the template was defined.
3866 //
3867 // We actually implement this paragraph where we set the semantic
3868 // context (in the creation of the ClassTemplateSpecializationDecl),
3869 // but we also maintain the lexical context where the actual
3870 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003871 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003872
Douglas Gregor67a65642009-02-17 23:15:12 +00003873 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003874 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00003875 Specialization->startDefinition();
3876
Douglas Gregor2208a292009-09-26 20:57:03 +00003877 if (TUK == TUK_Friend) {
3878 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3879 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00003880 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00003881 /*FIXME:*/KWLoc);
3882 Friend->setAccess(AS_public);
3883 CurContext->addDecl(Friend);
3884 } else {
3885 // Add the specialization into its lexical context, so that it can
3886 // be seen when iterating through the list of declarations in that
3887 // context. However, specializations are not found by name lookup.
3888 CurContext->addDecl(Specialization);
3889 }
Chris Lattner83f095c2009-03-28 19:18:32 +00003890 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003891}
Douglas Gregor333489b2009-03-27 23:10:48 +00003892
Mike Stump11289f42009-09-09 15:08:12 +00003893Sema::DeclPtrTy
3894Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003895 MultiTemplateParamsArg TemplateParameterLists,
3896 Declarator &D) {
3897 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
3898}
3899
Mike Stump11289f42009-09-09 15:08:12 +00003900Sema::DeclPtrTy
3901Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003902 MultiTemplateParamsArg TemplateParameterLists,
3903 Declarator &D) {
3904 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3905 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3906 "Not a function declarator!");
3907 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00003908
Douglas Gregor17a7c122009-06-24 00:54:41 +00003909 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00003910 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00003911 }
Mike Stump11289f42009-09-09 15:08:12 +00003912
Douglas Gregor17a7c122009-06-24 00:54:41 +00003913 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003914
3915 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00003916 move(TemplateParameterLists),
3917 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003918 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00003919 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00003920 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003921 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00003922 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
3923 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003924 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00003925}
3926
John McCall4f7ced62010-02-11 01:33:53 +00003927/// \brief Strips various properties off an implicit instantiation
3928/// that has just been explicitly specialized.
3929static void StripImplicitInstantiation(NamedDecl *D) {
3930 D->invalidateAttrs();
3931
3932 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3933 FD->setInlineSpecified(false);
3934 }
3935}
3936
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003937/// \brief Diagnose cases where we have an explicit template specialization
3938/// before/after an explicit template instantiation, producing diagnostics
3939/// for those cases where they are required and determining whether the
3940/// new specialization/instantiation will have any effect.
3941///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003942/// \param NewLoc the location of the new explicit specialization or
3943/// instantiation.
3944///
3945/// \param NewTSK the kind of the new explicit specialization or instantiation.
3946///
3947/// \param PrevDecl the previous declaration of the entity.
3948///
3949/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
3950///
3951/// \param PrevPointOfInstantiation if valid, indicates where the previus
3952/// declaration was instantiated (either implicitly or explicitly).
3953///
3954/// \param SuppressNew will be set to true to indicate that the new
3955/// specialization or instantiation has no effect and should be ignored.
3956///
3957/// \returns true if there was an error that should prevent the introduction of
3958/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00003959bool
3960Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
3961 TemplateSpecializationKind NewTSK,
3962 NamedDecl *PrevDecl,
3963 TemplateSpecializationKind PrevTSK,
3964 SourceLocation PrevPointOfInstantiation,
3965 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003966 SuppressNew = false;
3967
3968 switch (NewTSK) {
3969 case TSK_Undeclared:
3970 case TSK_ImplicitInstantiation:
3971 assert(false && "Don't check implicit instantiations here");
3972 return false;
3973
3974 case TSK_ExplicitSpecialization:
3975 switch (PrevTSK) {
3976 case TSK_Undeclared:
3977 case TSK_ExplicitSpecialization:
3978 // Okay, we're just specializing something that is either already
3979 // explicitly specialized or has merely been mentioned without any
3980 // instantiation.
3981 return false;
3982
3983 case TSK_ImplicitInstantiation:
3984 if (PrevPointOfInstantiation.isInvalid()) {
3985 // The declaration itself has not actually been instantiated, so it is
3986 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00003987 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00003988 return false;
3989 }
3990 // Fall through
3991
3992 case TSK_ExplicitInstantiationDeclaration:
3993 case TSK_ExplicitInstantiationDefinition:
3994 assert((PrevTSK == TSK_ImplicitInstantiation ||
3995 PrevPointOfInstantiation.isValid()) &&
3996 "Explicit instantiation without point of instantiation?");
3997
3998 // C++ [temp.expl.spec]p6:
3999 // If a template, a member template or the member of a class template
4000 // is explicitly specialized then that specialization shall be declared
4001 // before the first use of that specialization that would cause an
4002 // implicit instantiation to take place, in every translation unit in
4003 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004004 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4005 // Is there any previous explicit specialization declaration?
4006 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4007 return false;
4008 }
4009
Douglas Gregor1d957a32009-10-27 18:42:08 +00004010 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004011 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004012 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004013 << (PrevTSK != TSK_ImplicitInstantiation);
4014
4015 return true;
4016 }
4017 break;
4018
4019 case TSK_ExplicitInstantiationDeclaration:
4020 switch (PrevTSK) {
4021 case TSK_ExplicitInstantiationDeclaration:
4022 // This explicit instantiation declaration is redundant (that's okay).
4023 SuppressNew = true;
4024 return false;
4025
4026 case TSK_Undeclared:
4027 case TSK_ImplicitInstantiation:
4028 // We're explicitly instantiating something that may have already been
4029 // implicitly instantiated; that's fine.
4030 return false;
4031
4032 case TSK_ExplicitSpecialization:
4033 // C++0x [temp.explicit]p4:
4034 // For a given set of template parameters, if an explicit instantiation
4035 // of a template appears after a declaration of an explicit
4036 // specialization for that template, the explicit instantiation has no
4037 // effect.
John McCall6b21eb52010-03-02 23:09:38 +00004038 SuppressNew = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004039 return false;
4040
4041 case TSK_ExplicitInstantiationDefinition:
4042 // C++0x [temp.explicit]p10:
4043 // If an entity is the subject of both an explicit instantiation
4044 // declaration and an explicit instantiation definition in the same
4045 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004046 Diag(NewLoc,
4047 diag::err_explicit_instantiation_declaration_after_definition);
4048 Diag(PrevPointOfInstantiation,
4049 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004050 assert(PrevPointOfInstantiation.isValid() &&
4051 "Explicit instantiation without point of instantiation?");
4052 SuppressNew = true;
4053 return false;
4054 }
4055 break;
4056
4057 case TSK_ExplicitInstantiationDefinition:
4058 switch (PrevTSK) {
4059 case TSK_Undeclared:
4060 case TSK_ImplicitInstantiation:
4061 // We're explicitly instantiating something that may have already been
4062 // implicitly instantiated; that's fine.
4063 return false;
4064
4065 case TSK_ExplicitSpecialization:
4066 // C++ DR 259, C++0x [temp.explicit]p4:
4067 // For a given set of template parameters, if an explicit
4068 // instantiation of a template appears after a declaration of
4069 // an explicit specialization for that template, the explicit
4070 // instantiation has no effect.
4071 //
4072 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004073 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004074 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004075 if (!getLangOptions().CPlusPlus0x) {
4076 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004077 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004078 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004079 diag::note_previous_template_specialization);
4080 }
4081 SuppressNew = true;
4082 return false;
4083
4084 case TSK_ExplicitInstantiationDeclaration:
4085 // We're explicity instantiating a definition for something for which we
4086 // were previously asked to suppress instantiations. That's fine.
4087 return false;
4088
4089 case TSK_ExplicitInstantiationDefinition:
4090 // C++0x [temp.spec]p5:
4091 // For a given template and a given set of template-arguments,
4092 // - an explicit instantiation definition shall appear at most once
4093 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004094 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004095 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004096 Diag(PrevPointOfInstantiation,
4097 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004098 SuppressNew = true;
4099 return false;
4100 }
4101 break;
4102 }
4103
4104 assert(false && "Missing specialization/instantiation case?");
4105
4106 return false;
4107}
4108
John McCallb9c78482010-04-08 09:05:18 +00004109/// \brief Perform semantic analysis for the given dependent function
4110/// template specialization. The only possible way to get a dependent
4111/// function template specialization is with a friend declaration,
4112/// like so:
4113///
4114/// template <class T> void foo(T);
4115/// template <class T> class A {
4116/// friend void foo<>(T);
4117/// };
4118///
4119/// There really isn't any useful analysis we can do here, so we
4120/// just store the information.
4121bool
4122Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4123 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4124 LookupResult &Previous) {
4125 // Remove anything from Previous that isn't a function template in
4126 // the correct context.
4127 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4128 LookupResult::Filter F = Previous.makeFilter();
4129 while (F.hasNext()) {
4130 NamedDecl *D = F.next()->getUnderlyingDecl();
4131 if (!isa<FunctionTemplateDecl>(D) ||
4132 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4133 F.erase();
4134 }
4135 F.done();
4136
4137 // Should this be diagnosed here?
4138 if (Previous.empty()) return true;
4139
4140 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4141 ExplicitTemplateArgs);
4142 return false;
4143}
4144
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004145/// \brief Perform semantic analysis for the given function template
4146/// specialization.
4147///
4148/// This routine performs all of the semantic analysis required for an
4149/// explicit function template specialization. On successful completion,
4150/// the function declaration \p FD will become a function template
4151/// specialization.
4152///
4153/// \param FD the function declaration, which will be updated to become a
4154/// function template specialization.
4155///
4156/// \param HasExplicitTemplateArgs whether any template arguments were
4157/// explicitly provided.
4158///
4159/// \param LAngleLoc the location of the left angle bracket ('<'), if
4160/// template arguments were explicitly provided.
4161///
4162/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4163/// if any.
4164///
4165/// \param NumExplicitTemplateArgs the number of explicitly-provided template
4166/// arguments. This number may be zero even when HasExplicitTemplateArgs is
4167/// true as in, e.g., \c void sort<>(char*, char*);
4168///
4169/// \param RAngleLoc the location of the right angle bracket ('>'), if
4170/// template arguments were explicitly provided.
4171///
4172/// \param PrevDecl the set of declarations that
4173bool
4174Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004175 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004176 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004177 // The set of function template specializations that could match this
4178 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004179 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004180
4181 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004182 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4183 I != E; ++I) {
4184 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4185 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004186 // Only consider templates found within the same semantic lookup scope as
4187 // FD.
4188 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4189 continue;
4190
4191 // C++ [temp.expl.spec]p11:
4192 // A trailing template-argument can be left unspecified in the
4193 // template-id naming an explicit function template specialization
4194 // provided it can be deduced from the function argument type.
4195 // Perform template argument deduction to determine whether we may be
4196 // specializing this template.
4197 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004198 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004199 FunctionDecl *Specialization = 0;
4200 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004201 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004202 FD->getType(),
4203 Specialization,
4204 Info)) {
4205 // FIXME: Template argument deduction failed; record why it failed, so
4206 // that we can provide nifty diagnostics.
4207 (void)TDK;
4208 continue;
4209 }
4210
4211 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004212 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004213 }
4214 }
4215
Douglas Gregor5de279c2009-09-26 03:41:46 +00004216 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004217 UnresolvedSetIterator Result
4218 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4219 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004220 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004221 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004222 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004223 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004224 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004225 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004226 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004227
4228 // Ignore access information; it doesn't figure into redeclaration checking.
4229 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004230 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004231
4232 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004233 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004234
4235 // If this is a friend declaration, then we're not really declaring
4236 // an explicit specialization.
4237 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004238
Douglas Gregor54888652009-10-07 00:13:32 +00004239 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004240 if (!isFriend &&
4241 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004242 Specialization->getPrimaryTemplate(),
4243 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004244 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004245 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004246
4247 // C++ [temp.expl.spec]p6:
4248 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004249 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004250 // before the first use of that specialization that would cause an implicit
4251 // instantiation to take place, in every translation unit in which such a
4252 // use occurs; no diagnostic is required.
4253 FunctionTemplateSpecializationInfo *SpecInfo
4254 = Specialization->getTemplateSpecializationInfo();
4255 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004256
4257 bool SuppressNew = false;
John McCall816d75b2010-03-24 07:46:06 +00004258 if (!isFriend &&
4259 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004260 TSK_ExplicitSpecialization,
4261 Specialization,
4262 SpecInfo->getTemplateSpecializationKind(),
4263 SpecInfo->getPointOfInstantiation(),
4264 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004265 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004266
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004267 // Mark the prior declaration as an explicit specialization, so that later
4268 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004269 if (!isFriend)
4270 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004271
4272 // Turn the given function declaration into a function template
4273 // specialization, with the template arguments from the previous
4274 // specialization.
Douglas Gregord5058122010-02-11 01:19:42 +00004275 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004276 new (Context) TemplateArgumentList(
4277 *Specialization->getTemplateSpecializationArgs()),
4278 /*InsertPos=*/0,
John McCall816d75b2010-03-24 07:46:06 +00004279 SpecInfo->getTemplateSpecializationKind());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004280
4281 // The "previous declaration" for this function template specialization is
4282 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004283 Previous.clear();
4284 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004285 return false;
4286}
4287
Douglas Gregor86d142a2009-10-08 07:24:58 +00004288/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004289/// specialization.
4290///
4291/// This routine performs all of the semantic analysis required for an
4292/// explicit member function specialization. On successful completion,
4293/// the function declaration \p FD will become a member function
4294/// specialization.
4295///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004296/// \param Member the member declaration, which will be updated to become a
4297/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004298///
John McCall1f82f242009-11-18 22:49:29 +00004299/// \param Previous the set of declarations, one of which may be specialized
4300/// by this function specialization; the set will be modified to contain the
4301/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004302bool
John McCall1f82f242009-11-18 22:49:29 +00004303Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004304 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
4305
4306 // Try to find the member we are instantiating.
4307 NamedDecl *Instantiation = 0;
4308 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004309 MemberSpecializationInfo *MSInfo = 0;
4310
John McCall1f82f242009-11-18 22:49:29 +00004311 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004312 // Nowhere to look anyway.
4313 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004314 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4315 I != E; ++I) {
4316 NamedDecl *D = (*I)->getUnderlyingDecl();
4317 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004318 if (Context.hasSameType(Function->getType(), Method->getType())) {
4319 Instantiation = Method;
4320 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004321 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004322 break;
4323 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004324 }
4325 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004326 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004327 VarDecl *PrevVar;
4328 if (Previous.isSingleResult() &&
4329 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004330 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004331 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004332 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004333 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004334 }
4335 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004336 CXXRecordDecl *PrevRecord;
4337 if (Previous.isSingleResult() &&
4338 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4339 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004340 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004341 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004342 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004343 }
4344
4345 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004346 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004347 // specializations are always out-of-line, the caller will complain about
4348 // this mismatch later.
4349 return false;
4350 }
4351
Douglas Gregor86d142a2009-10-08 07:24:58 +00004352 // Make sure that this is a specialization of a member.
4353 if (!InstantiatedFrom) {
4354 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4355 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004356 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4357 return true;
4358 }
4359
Douglas Gregor06db9f52009-10-12 20:18:28 +00004360 // C++ [temp.expl.spec]p6:
4361 // If a template, a member template or the member of a class template is
4362 // explicitly specialized then that spe- cialization shall be declared
4363 // before the first use of that specialization that would cause an implicit
4364 // instantiation to take place, in every translation unit in which such a
4365 // use occurs; no diagnostic is required.
4366 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004367
4368 bool SuppressNew = false;
4369 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4370 TSK_ExplicitSpecialization,
4371 Instantiation,
4372 MSInfo->getTemplateSpecializationKind(),
4373 MSInfo->getPointOfInstantiation(),
4374 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004375 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004376
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004377 // Check the scope of this explicit specialization.
4378 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004379 InstantiatedFrom,
4380 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004381 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004382 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004383
Douglas Gregor86d142a2009-10-08 07:24:58 +00004384 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004385 // the original declaration to note that it is an explicit specialization
4386 // (if it was previously an implicit instantiation). This latter step
4387 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004388 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004389 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4390 if (InstantiationFunction->getTemplateSpecializationKind() ==
4391 TSK_ImplicitInstantiation) {
4392 InstantiationFunction->setTemplateSpecializationKind(
4393 TSK_ExplicitSpecialization);
4394 InstantiationFunction->setLocation(Member->getLocation());
4395 }
4396
Douglas Gregor86d142a2009-10-08 07:24:58 +00004397 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4398 cast<CXXMethodDecl>(InstantiatedFrom),
4399 TSK_ExplicitSpecialization);
4400 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004401 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4402 if (InstantiationVar->getTemplateSpecializationKind() ==
4403 TSK_ImplicitInstantiation) {
4404 InstantiationVar->setTemplateSpecializationKind(
4405 TSK_ExplicitSpecialization);
4406 InstantiationVar->setLocation(Member->getLocation());
4407 }
4408
Douglas Gregor86d142a2009-10-08 07:24:58 +00004409 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4410 cast<VarDecl>(InstantiatedFrom),
4411 TSK_ExplicitSpecialization);
4412 } else {
4413 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004414 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4415 if (InstantiationClass->getTemplateSpecializationKind() ==
4416 TSK_ImplicitInstantiation) {
4417 InstantiationClass->setTemplateSpecializationKind(
4418 TSK_ExplicitSpecialization);
4419 InstantiationClass->setLocation(Member->getLocation());
4420 }
4421
Douglas Gregor86d142a2009-10-08 07:24:58 +00004422 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004423 cast<CXXRecordDecl>(InstantiatedFrom),
4424 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004425 }
4426
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004427 // Save the caller the trouble of having to figure out which declaration
4428 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004429 Previous.clear();
4430 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004431 return false;
4432}
4433
Douglas Gregore47f5a72009-10-14 23:41:34 +00004434/// \brief Check the scope of an explicit instantiation.
4435static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4436 SourceLocation InstLoc,
4437 bool WasQualifiedName) {
4438 DeclContext *ExpectedContext
4439 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4440 DeclContext *CurContext = S.CurContext->getLookupContext();
4441
4442 // C++0x [temp.explicit]p2:
4443 // An explicit instantiation shall appear in an enclosing namespace of its
4444 // template.
4445 //
4446 // This is DR275, which we do not retroactively apply to C++98/03.
4447 if (S.getLangOptions().CPlusPlus0x &&
4448 !CurContext->Encloses(ExpectedContext)) {
4449 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4450 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
4451 << D << NS;
4452 else
4453 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
4454 << D;
4455 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4456 return;
4457 }
4458
4459 // C++0x [temp.explicit]p2:
4460 // If the name declared in the explicit instantiation is an unqualified
4461 // name, the explicit instantiation shall appear in the namespace where
4462 // its template is declared or, if that namespace is inline (7.3.1), any
4463 // namespace from its enclosing namespace set.
4464 if (WasQualifiedName)
4465 return;
4466
4467 if (CurContext->Equals(ExpectedContext))
4468 return;
4469
4470 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
4471 << D << ExpectedContext;
4472 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4473}
4474
4475/// \brief Determine whether the given scope specifier has a template-id in it.
4476static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4477 if (!SS.isSet())
4478 return false;
4479
4480 // C++0x [temp.explicit]p2:
4481 // If the explicit instantiation is for a member function, a member class
4482 // or a static data member of a class template specialization, the name of
4483 // the class template specialization in the qualified-id for the member
4484 // name shall be a simple-template-id.
4485 //
4486 // C++98 has the same restriction, just worded differently.
4487 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4488 NNS; NNS = NNS->getPrefix())
4489 if (Type *T = NNS->getAsType())
4490 if (isa<TemplateSpecializationType>(T))
4491 return true;
4492
4493 return false;
4494}
4495
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004496// Explicit instantiation of a class template specialization
Douglas Gregor43e75172009-09-04 06:33:52 +00004497// FIXME: Implement extern template semantics
Douglas Gregora1f49972009-05-13 00:25:59 +00004498Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004499Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004500 SourceLocation ExternLoc,
4501 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004502 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004503 SourceLocation KWLoc,
4504 const CXXScopeSpec &SS,
4505 TemplateTy TemplateD,
4506 SourceLocation TemplateNameLoc,
4507 SourceLocation LAngleLoc,
4508 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004509 SourceLocation RAngleLoc,
4510 AttributeList *Attr) {
4511 // Find the class template we're specializing
4512 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004513 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004514 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4515
4516 // Check that the specialization uses the same tag kind as the
4517 // original template.
4518 TagDecl::TagKind Kind;
4519 switch (TagSpec) {
4520 default: assert(0 && "Unknown tag type!");
4521 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
4522 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
4523 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
4524 }
Douglas Gregord9034f02009-05-14 16:41:31 +00004525 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004526 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004527 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004528 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004529 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004530 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004531 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004532 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004533 diag::note_previous_use);
4534 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4535 }
4536
Douglas Gregore47f5a72009-10-14 23:41:34 +00004537 // C++0x [temp.explicit]p2:
4538 // There are two forms of explicit instantiation: an explicit instantiation
4539 // definition and an explicit instantiation declaration. An explicit
4540 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004541 TemplateSpecializationKind TSK
4542 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4543 : TSK_ExplicitInstantiationDeclaration;
4544
Douglas Gregora1f49972009-05-13 00:25:59 +00004545 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004546 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004547 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004548
4549 // Check that the template argument list is well-formed for this
4550 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004551 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4552 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004553 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4554 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004555 return true;
4556
Mike Stump11289f42009-09-09 15:08:12 +00004557 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004558 ClassTemplate->getTemplateParameters()->size()) &&
4559 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004560
Douglas Gregora1f49972009-05-13 00:25:59 +00004561 // Find the class template specialization declaration that
4562 // corresponds to these arguments.
4563 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004564 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004565 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004566 Converted.flatSize(),
4567 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004568 void *InsertPos = 0;
4569 ClassTemplateSpecializationDecl *PrevDecl
4570 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4571
Douglas Gregor54888652009-10-07 00:13:32 +00004572 // C++0x [temp.explicit]p2:
4573 // [...] An explicit instantiation shall appear in an enclosing
4574 // namespace of its template. [...]
4575 //
4576 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004577 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4578 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004579
Douglas Gregora1f49972009-05-13 00:25:59 +00004580 ClassTemplateSpecializationDecl *Specialization = 0;
4581
Douglas Gregor0681a352009-11-25 06:01:46 +00004582 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004583 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004584 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004585 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004586 PrevDecl,
4587 PrevDecl->getSpecializationKind(),
4588 PrevDecl->getPointOfInstantiation(),
4589 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004590 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004591
Douglas Gregor12e49d32009-10-15 22:53:21 +00004592 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004593 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004594
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004595 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4596 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4597 // Since the only prior class template specialization with these
4598 // arguments was referenced but not declared, reuse that
4599 // declaration node as our own, updating its source location to
4600 // reflect our new declaration.
4601 Specialization = PrevDecl;
4602 Specialization->setLocation(TemplateNameLoc);
4603 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004604 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004605 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004606 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004607
4608 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004609 // Create a new class template specialization declaration node for
4610 // this explicit specialization.
4611 Specialization
Mike Stump11289f42009-09-09 15:08:12 +00004612 = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregora1f49972009-05-13 00:25:59 +00004613 ClassTemplate->getDeclContext(),
4614 TemplateNameLoc,
4615 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004616 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004617 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004618
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004619 if (PrevDecl) {
4620 // Remove the previous declaration from the folding set, since we want
4621 // to introduce a new declaration.
4622 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4623 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4624 }
4625
4626 // Insert the new specialization.
4627 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004628 }
4629
4630 // Build the fully-sugared type for this explicit instantiation as
4631 // the user wrote in the explicit instantiation itself. This means
4632 // that we'll pretty-print the type retrieved from the
4633 // specialization's declaration the way that the user actually wrote
4634 // the explicit instantiation, rather than formatting the name based
4635 // on the "canonical" representation used to store the template
4636 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004637 TypeSourceInfo *WrittenTy
4638 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4639 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004640 Context.getTypeDeclType(Specialization));
4641 Specialization->setTypeAsWritten(WrittenTy);
4642 TemplateArgsIn.release();
4643
Douglas Gregor0681a352009-11-25 06:01:46 +00004644 if (!ReusedDecl) {
4645 // Add the explicit instantiation into its lexical context. However,
4646 // since explicit instantiations are never found by name lookup, we
4647 // just put it into the declaration context directly.
4648 Specialization->setLexicalDeclContext(CurContext);
4649 CurContext->addDecl(Specialization);
4650 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004651
4652 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004653 // A definition of a class template or class member template
4654 // shall be in scope at the point of the explicit instantiation of
4655 // the class template or class member template.
4656 //
4657 // This check comes when we actually try to perform the
4658 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004659 ClassTemplateSpecializationDecl *Def
4660 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004661 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004662 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004663 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor1d957a32009-10-27 18:42:08 +00004664
4665 // Instantiate the members of this class template specialization.
4666 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004667 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004668 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004669 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4670
4671 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4672 // TSK_ExplicitInstantiationDefinition
4673 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4674 TSK == TSK_ExplicitInstantiationDefinition)
4675 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004676
Douglas Gregor12e49d32009-10-15 22:53:21 +00004677 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004678 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004679
4680 return DeclPtrTy::make(Specialization);
4681}
4682
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004683// Explicit instantiation of a member class of a class template.
4684Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004685Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004686 SourceLocation ExternLoc,
4687 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004688 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004689 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004690 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004691 IdentifierInfo *Name,
4692 SourceLocation NameLoc,
4693 AttributeList *Attr) {
4694
Douglas Gregord6ab8742009-05-28 23:31:59 +00004695 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004696 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004697 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004698 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004699 MultiTemplateParamsArg(*this, 0, 0),
4700 Owned, IsDependent);
4701 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4702
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004703 if (!TagD)
4704 return true;
4705
4706 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4707 if (Tag->isEnum()) {
4708 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4709 << Context.getTypeDeclType(Tag);
4710 return true;
4711 }
4712
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004713 if (Tag->isInvalidDecl())
4714 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004715
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004716 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4717 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4718 if (!Pattern) {
4719 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4720 << Context.getTypeDeclType(Record);
4721 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4722 return true;
4723 }
4724
Douglas Gregore47f5a72009-10-14 23:41:34 +00004725 // C++0x [temp.explicit]p2:
4726 // If the explicit instantiation is for a class or member class, the
4727 // elaborated-type-specifier in the declaration shall include a
4728 // simple-template-id.
4729 //
4730 // C++98 has the same restriction, just worded differently.
4731 if (!ScopeSpecifierHasTemplateId(SS))
4732 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4733 << Record << SS.getRange();
4734
4735 // C++0x [temp.explicit]p2:
4736 // There are two forms of explicit instantiation: an explicit instantiation
4737 // definition and an explicit instantiation declaration. An explicit
4738 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004739 TemplateSpecializationKind TSK
4740 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4741 : TSK_ExplicitInstantiationDeclaration;
4742
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004743 // C++0x [temp.explicit]p2:
4744 // [...] An explicit instantiation shall appear in an enclosing
4745 // namespace of its template. [...]
4746 //
4747 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004748 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004749
4750 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004751 CXXRecordDecl *PrevDecl
4752 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004753 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004754 PrevDecl = Record;
4755 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004756 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4757 bool SuppressNew = false;
4758 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004759 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004760 PrevDecl,
4761 MSInfo->getTemplateSpecializationKind(),
4762 MSInfo->getPointOfInstantiation(),
4763 SuppressNew))
4764 return true;
4765 if (SuppressNew)
4766 return TagD;
4767 }
4768
Douglas Gregor12e49d32009-10-15 22:53:21 +00004769 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004770 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004771 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004772 // C++ [temp.explicit]p3:
4773 // A definition of a member class of a class template shall be in scope
4774 // at the point of an explicit instantiation of the member class.
4775 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004776 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004777 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004778 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4779 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004780 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4781 << Pattern;
4782 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004783 } else {
4784 if (InstantiateClass(NameLoc, Record, Def,
4785 getTemplateInstantiationArgs(Record),
4786 TSK))
4787 return true;
4788
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004789 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004790 if (!RecordDef)
4791 return true;
4792 }
4793 }
4794
4795 // Instantiate all of the members of the class.
4796 InstantiateClassMembers(NameLoc, RecordDef,
4797 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004798
Mike Stump87c57ac2009-05-16 07:39:55 +00004799 // FIXME: We don't have any representation for explicit instantiations of
4800 // member classes. Such a representation is not needed for compilation, but it
4801 // should be available for clients that want to see all of the declarations in
4802 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004803 return TagD;
4804}
4805
Douglas Gregor450f00842009-09-25 18:43:00 +00004806Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4807 SourceLocation ExternLoc,
4808 SourceLocation TemplateLoc,
4809 Declarator &D) {
4810 // Explicit instantiations always require a name.
4811 DeclarationName Name = GetNameForDeclarator(D);
4812 if (!Name) {
4813 if (!D.isInvalidType())
4814 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4815 diag::err_explicit_instantiation_requires_name)
4816 << D.getDeclSpec().getSourceRange()
4817 << D.getSourceRange();
4818
4819 return true;
4820 }
4821
4822 // The scope passed in may not be a decl scope. Zip up the scope tree until
4823 // we find one that is.
4824 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4825 (S->getFlags() & Scope::TemplateParamScope) != 0)
4826 S = S->getParent();
4827
4828 // Determine the type of the declaration.
4829 QualType R = GetTypeForDeclarator(D, S, 0);
4830 if (R.isNull())
4831 return true;
4832
4833 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4834 // Cannot explicitly instantiate a typedef.
4835 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4836 << Name;
4837 return true;
4838 }
4839
Douglas Gregor3c74d412009-10-14 20:14:33 +00004840 // C++0x [temp.explicit]p1:
4841 // [...] An explicit instantiation of a function template shall not use the
4842 // inline or constexpr specifiers.
4843 // Presumably, this also applies to member functions of class templates as
4844 // well.
4845 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4846 Diag(D.getDeclSpec().getInlineSpecLoc(),
4847 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004848 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004849
4850 // FIXME: check for constexpr specifier.
4851
Douglas Gregore47f5a72009-10-14 23:41:34 +00004852 // C++0x [temp.explicit]p2:
4853 // There are two forms of explicit instantiation: an explicit instantiation
4854 // definition and an explicit instantiation declaration. An explicit
4855 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00004856 TemplateSpecializationKind TSK
4857 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4858 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004859
John McCall27b18f82009-11-17 02:14:36 +00004860 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4861 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00004862
4863 if (!R->isFunctionType()) {
4864 // C++ [temp.explicit]p1:
4865 // A [...] static data member of a class template can be explicitly
4866 // instantiated from the member definition associated with its class
4867 // template.
John McCall27b18f82009-11-17 02:14:36 +00004868 if (Previous.isAmbiguous())
4869 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00004870
John McCall67c00872009-12-02 08:25:40 +00004871 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00004872 if (!Prev || !Prev->isStaticDataMember()) {
4873 // We expect to see a data data member here.
4874 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4875 << Name;
4876 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4877 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00004878 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00004879 return true;
4880 }
4881
4882 if (!Prev->getInstantiatedFromStaticDataMember()) {
4883 // FIXME: Check for explicit specialization?
4884 Diag(D.getIdentifierLoc(),
4885 diag::err_explicit_instantiation_data_member_not_instantiated)
4886 << Prev;
4887 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
4888 // FIXME: Can we provide a note showing where this was declared?
4889 return true;
4890 }
4891
Douglas Gregore47f5a72009-10-14 23:41:34 +00004892 // C++0x [temp.explicit]p2:
4893 // If the explicit instantiation is for a member function, a member class
4894 // or a static data member of a class template specialization, the name of
4895 // the class template specialization in the qualified-id for the member
4896 // name shall be a simple-template-id.
4897 //
4898 // C++98 has the same restriction, just worded differently.
4899 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
4900 Diag(D.getIdentifierLoc(),
4901 diag::err_explicit_instantiation_without_qualified_id)
4902 << Prev << D.getCXXScopeSpec().getRange();
4903
4904 // Check the scope of this explicit instantiation.
4905 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
4906
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004907 // Verify that it is okay to explicitly instantiate here.
4908 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
4909 assert(MSInfo && "Missing static data member specialization info?");
4910 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004911 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004912 MSInfo->getTemplateSpecializationKind(),
4913 MSInfo->getPointOfInstantiation(),
4914 SuppressNew))
4915 return true;
4916 if (SuppressNew)
4917 return DeclPtrTy();
4918
Douglas Gregor450f00842009-09-25 18:43:00 +00004919 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004920 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004921 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00004922 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
4923 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00004924
4925 // FIXME: Create an ExplicitInstantiation node?
4926 return DeclPtrTy();
4927 }
4928
Douglas Gregor0e876e02009-09-25 23:53:26 +00004929 // If the declarator is a template-id, translate the parser's template
4930 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00004931 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004932 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00004933 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4934 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00004935 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4936 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00004937 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4938 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00004939 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00004940 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00004941 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00004942 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00004943 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00004944
Douglas Gregor450f00842009-09-25 18:43:00 +00004945 // C++ [temp.explicit]p1:
4946 // A [...] function [...] can be explicitly instantiated from its template.
4947 // A member function [...] of a class template can be explicitly
4948 // instantiated from the member definition associated with its class
4949 // template.
John McCall58cc69d2010-01-27 01:50:18 +00004950 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00004951 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4952 P != PEnd; ++P) {
4953 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00004954 if (!HasExplicitTemplateArgs) {
4955 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
4956 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
4957 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004958
John McCall58cc69d2010-01-27 01:50:18 +00004959 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004960 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
4961 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00004962 }
Douglas Gregor450f00842009-09-25 18:43:00 +00004963 }
4964 }
4965
4966 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
4967 if (!FunTmpl)
4968 continue;
4969
John McCallbc077cf2010-02-08 23:07:23 +00004970 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00004971 FunctionDecl *Specialization = 0;
4972 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00004973 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00004974 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004975 R, Specialization, Info)) {
4976 // FIXME: Keep track of almost-matches?
4977 (void)TDK;
4978 continue;
4979 }
4980
John McCall58cc69d2010-01-27 01:50:18 +00004981 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00004982 }
4983
4984 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004985 UnresolvedSetIterator Result
4986 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00004987 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00004988 PDiag(diag::err_explicit_instantiation_not_known) << Name,
4989 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
4990 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00004991
John McCall58cc69d2010-01-27 01:50:18 +00004992 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00004993 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004994
4995 // Ignore access control bits, we don't need them for redeclaration checking.
4996 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00004997
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00004998 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00004999 Diag(D.getIdentifierLoc(),
5000 diag::err_explicit_instantiation_member_function_not_instantiated)
5001 << Specialization
5002 << (Specialization->getTemplateSpecializationKind() ==
5003 TSK_ExplicitSpecialization);
5004 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5005 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005006 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005007
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005008 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005009 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5010 PrevDecl = Specialization;
5011
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005012 if (PrevDecl) {
5013 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005014 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005015 PrevDecl,
5016 PrevDecl->getTemplateSpecializationKind(),
5017 PrevDecl->getPointOfInstantiation(),
5018 SuppressNew))
5019 return true;
5020
5021 // FIXME: We may still want to build some representation of this
5022 // explicit specialization.
5023 if (SuppressNew)
5024 return DeclPtrTy();
5025 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005026
5027 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005028
5029 if (TSK == TSK_ExplicitInstantiationDefinition)
5030 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5031 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005032
Douglas Gregore47f5a72009-10-14 23:41:34 +00005033 // C++0x [temp.explicit]p2:
5034 // If the explicit instantiation is for a member function, a member class
5035 // or a static data member of a class template specialization, the name of
5036 // the class template specialization in the qualified-id for the member
5037 // name shall be a simple-template-id.
5038 //
5039 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005040 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005041 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005042 D.getCXXScopeSpec().isSet() &&
5043 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5044 Diag(D.getIdentifierLoc(),
5045 diag::err_explicit_instantiation_without_qualified_id)
5046 << Specialization << D.getCXXScopeSpec().getRange();
5047
5048 CheckExplicitInstantiationScope(*this,
5049 FunTmpl? (NamedDecl *)FunTmpl
5050 : Specialization->getInstantiatedFromMemberFunction(),
5051 D.getIdentifierLoc(),
5052 D.getCXXScopeSpec().isSet());
5053
Douglas Gregor450f00842009-09-25 18:43:00 +00005054 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5055 return DeclPtrTy();
5056}
5057
Douglas Gregor333489b2009-03-27 23:10:48 +00005058Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005059Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5060 const CXXScopeSpec &SS, IdentifierInfo *Name,
5061 SourceLocation TagLoc, SourceLocation NameLoc) {
5062 // This has to hold, because SS is expected to be defined.
5063 assert(Name && "Expected a name in a dependent tag");
5064
5065 NestedNameSpecifier *NNS
5066 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5067 if (!NNS)
5068 return true;
5069
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005070 ElaboratedTypeKeyword Keyword = ETK_None;
Douglas Gregore677daf2010-03-31 22:19:08 +00005071 switch (TagDecl::getTagKindForTypeSpec(TagSpec)) {
5072 case TagDecl::TK_struct: Keyword = ETK_Struct; break;
5073 case TagDecl::TK_class: Keyword = ETK_Class; break;
5074 case TagDecl::TK_union: Keyword = ETK_Union; break;
5075 case TagDecl::TK_enum: Keyword = ETK_Enum; break;
5076 }
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005077 assert(Keyword != ETK_None && "Invalid tag kind!");
5078
Douglas Gregore677daf2010-03-31 22:19:08 +00005079 return Context.getDependentNameType(Keyword, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005080}
5081
5082Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00005083Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5084 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005085 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005086 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5087 if (!NNS)
5088 return true;
5089
5090 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005091 if (T.isNull())
5092 return true;
Douglas Gregor333489b2009-03-27 23:10:48 +00005093 return T.getAsOpaquePtr();
5094}
5095
Douglas Gregordce2b622009-04-01 00:28:59 +00005096Sema::TypeResult
5097Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5098 SourceLocation TemplateLoc, TypeTy *Ty) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005099 QualType T = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005100 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00005101 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Mike Stump11289f42009-09-09 15:08:12 +00005102 const TemplateSpecializationType *TemplateId
John McCall9dd450b2009-09-21 23:43:11 +00005103 = T->getAs<TemplateSpecializationType>();
Douglas Gregordce2b622009-04-01 00:28:59 +00005104 assert(TemplateId && "Expected a template specialization type");
5105
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005106 if (computeDeclContext(SS, false)) {
5107 // If we can compute a declaration context, then the "typename"
5108 // keyword was superfluous. Just build a QualifiedNameType to keep
5109 // track of the nested-name-specifier.
Mike Stump11289f42009-09-09 15:08:12 +00005110
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005111 // FIXME: Note that the QualifiedNameType had the "typename" keyword!
5112 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
5113 }
Mike Stump11289f42009-09-09 15:08:12 +00005114
Douglas Gregor02085352010-03-31 20:19:30 +00005115 return Context.getDependentNameType(ETK_Typename, NNS, TemplateId)
5116 .getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005117}
5118
Douglas Gregor333489b2009-03-27 23:10:48 +00005119/// \brief Build the type that describes a C++ typename specifier,
5120/// e.g., "typename T::type".
5121QualType
5122Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
5123 SourceRange Range) {
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005124 CXXRecordDecl *CurrentInstantiation = 0;
5125 if (NNS->isDependent()) {
5126 CurrentInstantiation = getCurrentInstantiationOf(NNS);
Douglas Gregor333489b2009-03-27 23:10:48 +00005127
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005128 // If the nested-name-specifier does not refer to the current
5129 // instantiation, then build a typename type.
5130 if (!CurrentInstantiation)
Douglas Gregor02085352010-03-31 20:19:30 +00005131 return Context.getDependentNameType(ETK_Typename, NNS, &II);
Mike Stump11289f42009-09-09 15:08:12 +00005132
Douglas Gregorc707da62009-09-02 13:12:51 +00005133 // The nested-name-specifier refers to the current instantiation, so the
5134 // "typename" keyword itself is superfluous. In C++03, the program is
Mike Stump11289f42009-09-09 15:08:12 +00005135 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such
Douglas Gregorc707da62009-09-02 13:12:51 +00005136 // extraneous "typename" keywords, and we retroactively apply this DR to
5137 // C++03 code.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005138 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005139
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005140 DeclContext *Ctx = 0;
5141
5142 if (CurrentInstantiation)
5143 Ctx = CurrentInstantiation;
5144 else {
5145 CXXScopeSpec SS;
5146 SS.setScopeRep(NNS);
5147 SS.setRange(Range);
5148 if (RequireCompleteDeclContext(SS))
5149 return QualType();
5150
5151 Ctx = computeDeclContext(SS);
5152 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005153 assert(Ctx && "No declaration context?");
5154
5155 DeclarationName Name(&II);
John McCall27b18f82009-11-17 02:14:36 +00005156 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
5157 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005158 unsigned DiagID = 0;
5159 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005160 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005161 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005162 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005163 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005164
5165 case LookupResult::NotFoundInCurrentInstantiation:
5166 // Okay, it's a member of an unknown instantiation.
Douglas Gregor02085352010-03-31 20:19:30 +00005167 return Context.getDependentNameType(ETK_Typename, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005168
5169 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00005170 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005171 // We found a type. Build a QualifiedNameType, since the
5172 // typename-specifier was just sugar. FIXME: Tell
5173 // QualifiedNameType that it has a "typename" prefix.
5174 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
5175 }
5176
5177 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005178 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005179 break;
5180
John McCalle61f2ba2009-11-18 02:36:19 +00005181 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005182 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005183 return QualType();
5184
Douglas Gregor333489b2009-03-27 23:10:48 +00005185 case LookupResult::FoundOverloaded:
5186 DiagID = diag::err_typename_nested_not_type;
5187 Referenced = *Result.begin();
5188 break;
5189
John McCall6538c932009-10-10 05:48:19 +00005190 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005191 return QualType();
5192 }
5193
5194 // If we get here, it's because name lookup did not find a
5195 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregore40876a2009-10-13 21:16:44 +00005196 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005197 if (Referenced)
5198 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5199 << Name;
5200 return QualType();
5201}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005202
5203namespace {
5204 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005205 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005206 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005207 SourceLocation Loc;
5208 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005209
Douglas Gregor15acfb92009-08-06 16:20:37 +00005210 public:
Mike Stump11289f42009-09-09 15:08:12 +00005211 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005212 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005213 DeclarationName Entity)
5214 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005215 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005216
5217 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005218 /// transformed.
5219 ///
5220 /// For the purposes of type reconstruction, a type has already been
5221 /// transformed if it is NULL or if it is not dependent.
5222 bool AlreadyTransformed(QualType T) {
5223 return T.isNull() || !T->isDependentType();
5224 }
Mike Stump11289f42009-09-09 15:08:12 +00005225
5226 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005227 /// rebuilt.
5228 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005229
Douglas Gregor15acfb92009-08-06 16:20:37 +00005230 /// \brief Returns the name of the entity whose type is being rebuilt.
5231 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005232
Douglas Gregoref6ab412009-10-27 06:26:26 +00005233 /// \brief Sets the "base" location and entity when that
5234 /// information is known based on another transformation.
5235 void setBase(SourceLocation Loc, DeclarationName Entity) {
5236 this->Loc = Loc;
5237 this->Entity = Entity;
5238 }
5239
Douglas Gregor15acfb92009-08-06 16:20:37 +00005240 /// \brief Transforms an expression by returning the expression itself
5241 /// (an identity function).
5242 ///
5243 /// FIXME: This is completely unsafe; we will need to actually clone the
5244 /// expressions.
5245 Sema::OwningExprResult TransformExpr(Expr *E) {
5246 return getSema().Owned(E);
5247 }
Mike Stump11289f42009-09-09 15:08:12 +00005248
Douglas Gregor15acfb92009-08-06 16:20:37 +00005249 /// \brief Transforms a typename type by determining whether the type now
5250 /// refers to a member of the current instantiation, and then
5251 /// type-checking and building a QualifiedNameType (when possible).
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005252 QualType TransformDependentNameType(TypeLocBuilder &TLB, DependentNameTypeLoc TL,
Douglas Gregorfe17d252010-02-16 19:09:40 +00005253 QualType ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005254 };
5255}
5256
Mike Stump11289f42009-09-09 15:08:12 +00005257QualType
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005258CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5259 DependentNameTypeLoc TL,
Douglas Gregorfe17d252010-02-16 19:09:40 +00005260 QualType ObjectType) {
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005261 DependentNameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00005262
Douglas Gregor15acfb92009-08-06 16:20:37 +00005263 NestedNameSpecifier *NNS
5264 = TransformNestedNameSpecifier(T->getQualifier(),
Douglas Gregorfe17d252010-02-16 19:09:40 +00005265 /*FIXME:*/SourceRange(getBaseLocation()),
5266 ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005267 if (!NNS)
5268 return QualType();
5269
5270 // If the nested-name-specifier did not change, and we cannot compute the
5271 // context corresponding to the nested-name-specifier, then this
5272 // typename type will not change; exit early.
5273 CXXScopeSpec SS;
5274 SS.setRange(SourceRange(getBaseLocation()));
5275 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00005276
5277 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005278 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00005279 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00005280
5281 // Rebuild the typename type, which will probably turn into a
Douglas Gregor15acfb92009-08-06 16:20:37 +00005282 // QualifiedNameType.
John McCall0ad16662009-10-29 08:12:44 +00005283 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00005284 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00005285 = TransformType(QualType(TemplateId, 0));
5286 if (NewTemplateId.isNull())
5287 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005288
Douglas Gregor15acfb92009-08-06 16:20:37 +00005289 if (NNS == T->getQualifier() &&
5290 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00005291 Result = QualType(T, 0);
5292 else
Douglas Gregor02085352010-03-31 20:19:30 +00005293 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5294 NNS, NewTemplateId);
John McCall0ad16662009-10-29 08:12:44 +00005295 } else
Douglas Gregor02085352010-03-31 20:19:30 +00005296 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5297 NNS, T->getIdentifier(),
5298 SourceRange(TL.getNameLoc()));
Mike Stump11289f42009-09-09 15:08:12 +00005299
Douglas Gregor281c4862010-03-07 23:26:22 +00005300 if (Result.isNull())
5301 return QualType();
5302
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005303 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
John McCall0ad16662009-10-29 08:12:44 +00005304 NewTL.setNameLoc(TL.getNameLoc());
5305 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005306}
5307
5308/// \brief Rebuilds a type within the context of the current instantiation.
5309///
Mike Stump11289f42009-09-09 15:08:12 +00005310/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005311/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005312/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005313/// partial specialization thereof). This routine will rebuild that type now
5314/// that we have entered the declarator's scope, which may produce different
5315/// canonical types, e.g.,
5316///
5317/// \code
5318/// template<typename T>
5319/// struct X {
5320/// typedef T* pointer;
5321/// pointer data();
5322/// };
5323///
5324/// template<typename T>
5325/// typename X<T>::pointer X<T>::data() { ... }
5326/// \endcode
5327///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005328/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005329/// since we do not know that we can look into X<T> when we parsed the type.
5330/// This function will rebuild the type, performing the lookup of "pointer"
5331/// in X<T> and returning a QualifiedNameType whose canonical type is the same
5332/// as the canonical type of T*, allowing the return types of the out-of-line
5333/// definition and the declaration to match.
5334QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc,
5335 DeclarationName Name) {
5336 if (T.isNull() || !T->isDependentType())
5337 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005338
Douglas Gregor15acfb92009-08-06 16:20:37 +00005339 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5340 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005341}
Douglas Gregorbe999392009-09-15 16:23:51 +00005342
5343/// \brief Produces a formatted string that describes the binding of
5344/// template parameters to template arguments.
5345std::string
5346Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5347 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005348 // FIXME: For variadic templates, we'll need to get the structured list.
5349 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5350 Args.flat_size());
5351}
5352
5353std::string
5354Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5355 const TemplateArgument *Args,
5356 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005357 std::string Result;
5358
Douglas Gregore62e6a02009-11-11 19:13:48 +00005359 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005360 return Result;
5361
5362 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005363 if (I >= NumArgs)
5364 break;
5365
Douglas Gregorbe999392009-09-15 16:23:51 +00005366 if (I == 0)
5367 Result += "[with ";
5368 else
5369 Result += ", ";
5370
5371 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5372 Result += Id->getName();
5373 } else {
5374 Result += '$';
5375 Result += llvm::utostr(I);
5376 }
5377
5378 Result += " = ";
5379
5380 switch (Args[I].getKind()) {
5381 case TemplateArgument::Null:
5382 Result += "<no value>";
5383 break;
5384
5385 case TemplateArgument::Type: {
5386 std::string TypeStr;
5387 Args[I].getAsType().getAsStringInternal(TypeStr,
5388 Context.PrintingPolicy);
5389 Result += TypeStr;
5390 break;
5391 }
5392
5393 case TemplateArgument::Declaration: {
5394 bool Unnamed = true;
5395 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5396 if (ND->getDeclName()) {
5397 Unnamed = false;
5398 Result += ND->getNameAsString();
5399 }
5400 }
5401
5402 if (Unnamed) {
5403 Result += "<anonymous>";
5404 }
5405 break;
5406 }
5407
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005408 case TemplateArgument::Template: {
5409 std::string Str;
5410 llvm::raw_string_ostream OS(Str);
5411 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5412 Result += OS.str();
5413 break;
5414 }
5415
Douglas Gregorbe999392009-09-15 16:23:51 +00005416 case TemplateArgument::Integral: {
5417 Result += Args[I].getAsIntegral()->toString(10);
5418 break;
5419 }
5420
5421 case TemplateArgument::Expression: {
5422 assert(false && "No expressions in deduced template arguments!");
5423 Result += "<expression>";
5424 break;
5425 }
5426
5427 case TemplateArgument::Pack:
5428 // FIXME: Format template argument packs
5429 Result += "<template argument pack>";
5430 break;
5431 }
5432 }
5433
5434 Result += ']';
5435 return Result;
5436}