Fix the memory leak of FloatingLiteral/IntegerLiteral.
[clang.git] / lib / Sema / SemaTemplate.cpp
blob09656bcd915452d5d948ddb5ed90cee0db0df718
1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2 //
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.
7 //===----------------------------------------------------------------------===/
8 //
9 // This file implements semantic analysis for C++ templates.
10 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "clang/Sema/Lookup.h"
14 #include "clang/Sema/Scope.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/Sema/TemplateDeduction.h"
17 #include "TreeTransform.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Basic/LangOptions.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "llvm/ADT/StringExtras.h"
28 using namespace clang;
29 using namespace sema;
31 /// \brief Determine whether the declaration found is acceptable as the name
32 /// of a template and, if so, return that template declaration. Otherwise,
33 /// returns NULL.
34 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
35 NamedDecl *Orig) {
36 NamedDecl *D = Orig->getUnderlyingDecl();
38 if (isa<TemplateDecl>(D))
39 return Orig;
41 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
42 // C++ [temp.local]p1:
43 // Like normal (non-template) classes, class templates have an
44 // injected-class-name (Clause 9). The injected-class-name
45 // can be used with or without a template-argument-list. When
46 // it is used without a template-argument-list, it is
47 // equivalent to the injected-class-name followed by the
48 // template-parameters of the class template enclosed in
49 // <>. When it is used with a template-argument-list, it
50 // refers to the specified class template specialization,
51 // which could be the current specialization or another
52 // specialization.
53 if (Record->isInjectedClassName()) {
54 Record = cast<CXXRecordDecl>(Record->getDeclContext());
55 if (Record->getDescribedClassTemplate())
56 return Record->getDescribedClassTemplate();
58 if (ClassTemplateSpecializationDecl *Spec
59 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
60 return Spec->getSpecializedTemplate();
63 return 0;
66 return 0;
69 static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
70 // The set of class templates we've already seen.
71 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
72 LookupResult::Filter filter = R.makeFilter();
73 while (filter.hasNext()) {
74 NamedDecl *Orig = filter.next();
75 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
76 if (!Repl)
77 filter.erase();
78 else if (Repl != Orig) {
80 // C++ [temp.local]p3:
81 // A lookup that finds an injected-class-name (10.2) can result in an
82 // ambiguity in certain cases (for example, if it is found in more than
83 // one base class). If all of the injected-class-names that are found
84 // refer to specializations of the same class template, and if the name
85 // is followed by a template-argument-list, the reference refers to the
86 // class template itself and not a specialization thereof, and is not
87 // ambiguous.
89 // FIXME: Will we eventually have to do the same for alias templates?
90 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
91 if (!ClassTemplates.insert(ClassTmpl)) {
92 filter.erase();
93 continue;
96 // FIXME: we promote access to public here as a workaround to
97 // the fact that LookupResult doesn't let us remember that we
98 // found this template through a particular injected class name,
99 // which means we end up doing nasty things to the invariants.
100 // Pretending that access is public is *much* safer.
101 filter.replace(Repl, AS_public);
104 filter.done();
107 TemplateNameKind Sema::isTemplateName(Scope *S,
108 CXXScopeSpec &SS,
109 bool hasTemplateKeyword,
110 UnqualifiedId &Name,
111 ParsedType ObjectTypePtr,
112 bool EnteringContext,
113 TemplateTy &TemplateResult,
114 bool &MemberOfUnknownSpecialization) {
115 assert(getLangOptions().CPlusPlus && "No template names in C!");
117 DeclarationName TName;
118 MemberOfUnknownSpecialization = false;
120 switch (Name.getKind()) {
121 case UnqualifiedId::IK_Identifier:
122 TName = DeclarationName(Name.Identifier);
123 break;
125 case UnqualifiedId::IK_OperatorFunctionId:
126 TName = Context.DeclarationNames.getCXXOperatorName(
127 Name.OperatorFunctionId.Operator);
128 break;
130 case UnqualifiedId::IK_LiteralOperatorId:
131 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
132 break;
134 default:
135 return TNK_Non_template;
138 QualType ObjectType = ObjectTypePtr.get();
140 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
141 LookupOrdinaryName);
142 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
143 MemberOfUnknownSpecialization);
144 if (R.empty() || R.isAmbiguous()) {
145 R.suppressDiagnostics();
146 return TNK_Non_template;
149 TemplateName Template;
150 TemplateNameKind TemplateKind;
152 unsigned ResultCount = R.end() - R.begin();
153 if (ResultCount > 1) {
154 // We assume that we'll preserve the qualifier from a function
155 // template name in other ways.
156 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
157 TemplateKind = TNK_Function_template;
159 // We'll do this lookup again later.
160 R.suppressDiagnostics();
161 } else {
162 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
164 if (SS.isSet() && !SS.isInvalid()) {
165 NestedNameSpecifier *Qualifier
166 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
167 Template = Context.getQualifiedTemplateName(Qualifier,
168 hasTemplateKeyword, TD);
169 } else {
170 Template = TemplateName(TD);
173 if (isa<FunctionTemplateDecl>(TD)) {
174 TemplateKind = TNK_Function_template;
176 // We'll do this lookup again later.
177 R.suppressDiagnostics();
178 } else {
179 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
180 TemplateKind = TNK_Type_template;
184 TemplateResult = TemplateTy::make(Template);
185 return TemplateKind;
188 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
189 SourceLocation IILoc,
190 Scope *S,
191 const CXXScopeSpec *SS,
192 TemplateTy &SuggestedTemplate,
193 TemplateNameKind &SuggestedKind) {
194 // We can't recover unless there's a dependent scope specifier preceding the
195 // template name.
196 // FIXME: Typo correction?
197 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
198 computeDeclContext(*SS))
199 return false;
201 // The code is missing a 'template' keyword prior to the dependent template
202 // name.
203 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
204 Diag(IILoc, diag::err_template_kw_missing)
205 << Qualifier << II.getName()
206 << FixItHint::CreateInsertion(IILoc, "template ");
207 SuggestedTemplate
208 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
209 SuggestedKind = TNK_Dependent_template_name;
210 return true;
213 void Sema::LookupTemplateName(LookupResult &Found,
214 Scope *S, CXXScopeSpec &SS,
215 QualType ObjectType,
216 bool EnteringContext,
217 bool &MemberOfUnknownSpecialization) {
218 // Determine where to perform name lookup
219 MemberOfUnknownSpecialization = false;
220 DeclContext *LookupCtx = 0;
221 bool isDependent = false;
222 if (!ObjectType.isNull()) {
223 // This nested-name-specifier occurs in a member access expression, e.g.,
224 // x->B::f, and we are looking into the type of the object.
225 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
226 LookupCtx = computeDeclContext(ObjectType);
227 isDependent = ObjectType->isDependentType();
228 assert((isDependent || !ObjectType->isIncompleteType()) &&
229 "Caller should have completed object type");
230 } else if (SS.isSet()) {
231 // This nested-name-specifier occurs after another nested-name-specifier,
232 // so long into the context associated with the prior nested-name-specifier.
233 LookupCtx = computeDeclContext(SS, EnteringContext);
234 isDependent = isDependentScopeSpecifier(SS);
236 // The declaration context must be complete.
237 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
238 return;
241 bool ObjectTypeSearchedInScope = false;
242 if (LookupCtx) {
243 // Perform "qualified" name lookup into the declaration context we
244 // computed, which is either the type of the base of a member access
245 // expression or the declaration context associated with a prior
246 // nested-name-specifier.
247 LookupQualifiedName(Found, LookupCtx);
249 if (!ObjectType.isNull() && Found.empty()) {
250 // C++ [basic.lookup.classref]p1:
251 // In a class member access expression (5.2.5), if the . or -> token is
252 // immediately followed by an identifier followed by a <, the
253 // identifier must be looked up to determine whether the < is the
254 // beginning of a template argument list (14.2) or a less-than operator.
255 // The identifier is first looked up in the class of the object
256 // expression. If the identifier is not found, it is then looked up in
257 // the context of the entire postfix-expression and shall name a class
258 // or function template.
259 if (S) LookupName(Found, S);
260 ObjectTypeSearchedInScope = true;
262 } else if (isDependent && (!S || ObjectType.isNull())) {
263 // We cannot look into a dependent object type or nested nme
264 // specifier.
265 MemberOfUnknownSpecialization = true;
266 return;
267 } else {
268 // Perform unqualified name lookup in the current scope.
269 LookupName(Found, S);
272 if (Found.empty() && !isDependent) {
273 // If we did not find any names, attempt to correct any typos.
274 DeclarationName Name = Found.getLookupName();
275 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
276 false, CTC_CXXCasts)) {
277 FilterAcceptableTemplateNames(Context, Found);
278 if (!Found.empty()) {
279 if (LookupCtx)
280 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
281 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
282 << FixItHint::CreateReplacement(Found.getNameLoc(),
283 Found.getLookupName().getAsString());
284 else
285 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
286 << Name << Found.getLookupName()
287 << FixItHint::CreateReplacement(Found.getNameLoc(),
288 Found.getLookupName().getAsString());
289 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
290 Diag(Template->getLocation(), diag::note_previous_decl)
291 << Template->getDeclName();
293 } else {
294 Found.clear();
295 Found.setLookupName(Name);
299 FilterAcceptableTemplateNames(Context, Found);
300 if (Found.empty()) {
301 if (isDependent)
302 MemberOfUnknownSpecialization = true;
303 return;
306 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
307 // C++ [basic.lookup.classref]p1:
308 // [...] If the lookup in the class of the object expression finds a
309 // template, the name is also looked up in the context of the entire
310 // postfix-expression and [...]
312 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
313 LookupOrdinaryName);
314 LookupName(FoundOuter, S);
315 FilterAcceptableTemplateNames(Context, FoundOuter);
317 if (FoundOuter.empty()) {
318 // - if the name is not found, the name found in the class of the
319 // object expression is used, otherwise
320 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
321 // - if the name is found in the context of the entire
322 // postfix-expression and does not name a class template, the name
323 // found in the class of the object expression is used, otherwise
324 } else if (!Found.isSuppressingDiagnostics()) {
325 // - if the name found is a class template, it must refer to the same
326 // entity as the one found in the class of the object expression,
327 // otherwise the program is ill-formed.
328 if (!Found.isSingleResult() ||
329 Found.getFoundDecl()->getCanonicalDecl()
330 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
331 Diag(Found.getNameLoc(),
332 diag::ext_nested_name_member_ref_lookup_ambiguous)
333 << Found.getLookupName()
334 << ObjectType;
335 Diag(Found.getRepresentativeDecl()->getLocation(),
336 diag::note_ambig_member_ref_object_type)
337 << ObjectType;
338 Diag(FoundOuter.getFoundDecl()->getLocation(),
339 diag::note_ambig_member_ref_scope);
341 // Recover by taking the template that we found in the object
342 // expression's type.
348 /// ActOnDependentIdExpression - Handle a dependent id-expression that
349 /// was just parsed. This is only possible with an explicit scope
350 /// specifier naming a dependent type.
351 ExprResult
352 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
353 const DeclarationNameInfo &NameInfo,
354 bool isAddressOfOperand,
355 const TemplateArgumentListInfo *TemplateArgs) {
356 NestedNameSpecifier *Qualifier
357 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
359 DeclContext *DC = getFunctionLevelDeclContext();
361 if (!isAddressOfOperand &&
362 isa<CXXMethodDecl>(DC) &&
363 cast<CXXMethodDecl>(DC)->isInstance()) {
364 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
366 // Since the 'this' expression is synthesized, we don't need to
367 // perform the double-lookup check.
368 NamedDecl *FirstQualifierInScope = 0;
370 return Owned(CXXDependentScopeMemberExpr::Create(Context,
371 /*This*/ 0, ThisType,
372 /*IsArrow*/ true,
373 /*Op*/ SourceLocation(),
374 Qualifier, SS.getRange(),
375 FirstQualifierInScope,
376 NameInfo,
377 TemplateArgs));
380 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
383 ExprResult
384 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
385 const DeclarationNameInfo &NameInfo,
386 const TemplateArgumentListInfo *TemplateArgs) {
387 return Owned(DependentScopeDeclRefExpr::Create(Context,
388 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
389 SS.getRange(),
390 NameInfo,
391 TemplateArgs));
394 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
395 /// that the template parameter 'PrevDecl' is being shadowed by a new
396 /// declaration at location Loc. Returns true to indicate that this is
397 /// an error, and false otherwise.
398 bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
399 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
401 // Microsoft Visual C++ permits template parameters to be shadowed.
402 if (getLangOptions().Microsoft)
403 return false;
405 // C++ [temp.local]p4:
406 // A template-parameter shall not be redeclared within its
407 // scope (including nested scopes).
408 Diag(Loc, diag::err_template_param_shadow)
409 << cast<NamedDecl>(PrevDecl)->getDeclName();
410 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
411 return true;
414 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
415 /// the parameter D to reference the templated declaration and return a pointer
416 /// to the template declaration. Otherwise, do nothing to D and return null.
417 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
418 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
419 D = Temp->getTemplatedDecl();
420 return Temp;
422 return 0;
425 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
426 const ParsedTemplateArgument &Arg) {
428 switch (Arg.getKind()) {
429 case ParsedTemplateArgument::Type: {
430 TypeSourceInfo *DI;
431 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
432 if (!DI)
433 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
434 return TemplateArgumentLoc(TemplateArgument(T), DI);
437 case ParsedTemplateArgument::NonType: {
438 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
439 return TemplateArgumentLoc(TemplateArgument(E), E);
442 case ParsedTemplateArgument::Template: {
443 TemplateName Template = Arg.getAsTemplate().get();
444 return TemplateArgumentLoc(TemplateArgument(Template),
445 Arg.getScopeSpec().getRange(),
446 Arg.getLocation());
450 llvm_unreachable("Unhandled parsed template argument");
451 return TemplateArgumentLoc();
454 /// \brief Translates template arguments as provided by the parser
455 /// into template arguments used by semantic analysis.
456 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
457 TemplateArgumentListInfo &TemplateArgs) {
458 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
459 TemplateArgs.addArgument(translateTemplateArgument(*this,
460 TemplateArgsIn[I]));
463 /// ActOnTypeParameter - Called when a C++ template type parameter
464 /// (e.g., "typename T") has been parsed. Typename specifies whether
465 /// the keyword "typename" was used to declare the type parameter
466 /// (otherwise, "class" was used), and KeyLoc is the location of the
467 /// "class" or "typename" keyword. ParamName is the name of the
468 /// parameter (NULL indicates an unnamed template parameter) and
469 /// ParamName is the location of the parameter name (if any).
470 /// If the type parameter has a default argument, it will be added
471 /// later via ActOnTypeParameterDefault.
472 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
473 SourceLocation EllipsisLoc,
474 SourceLocation KeyLoc,
475 IdentifierInfo *ParamName,
476 SourceLocation ParamNameLoc,
477 unsigned Depth, unsigned Position,
478 SourceLocation EqualLoc,
479 ParsedType DefaultArg) {
480 assert(S->isTemplateParamScope() &&
481 "Template type parameter not in template parameter scope!");
482 bool Invalid = false;
484 if (ParamName) {
485 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
486 LookupOrdinaryName,
487 ForRedeclaration);
488 if (PrevDecl && PrevDecl->isTemplateParameter())
489 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
490 PrevDecl);
493 SourceLocation Loc = ParamNameLoc;
494 if (!ParamName)
495 Loc = KeyLoc;
497 TemplateTypeParmDecl *Param
498 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
499 Loc, Depth, Position, ParamName, Typename,
500 Ellipsis);
501 if (Invalid)
502 Param->setInvalidDecl();
504 if (ParamName) {
505 // Add the template parameter into the current scope.
506 S->AddDecl(Param);
507 IdResolver.AddDecl(Param);
510 // Handle the default argument, if provided.
511 if (DefaultArg) {
512 TypeSourceInfo *DefaultTInfo;
513 GetTypeFromParser(DefaultArg, &DefaultTInfo);
515 assert(DefaultTInfo && "expected source information for type");
517 // C++0x [temp.param]p9:
518 // A default template-argument may be specified for any kind of
519 // template-parameter that is not a template parameter pack.
520 if (Ellipsis) {
521 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
522 return Param;
525 // Check the template argument itself.
526 if (CheckTemplateArgument(Param, DefaultTInfo)) {
527 Param->setInvalidDecl();
528 return Param;
531 Param->setDefaultArgument(DefaultTInfo, false);
534 return Param;
537 /// \brief Check that the type of a non-type template parameter is
538 /// well-formed.
540 /// \returns the (possibly-promoted) parameter type if valid;
541 /// otherwise, produces a diagnostic and returns a NULL type.
542 QualType
543 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
544 // We don't allow variably-modified types as the type of non-type template
545 // parameters.
546 if (T->isVariablyModifiedType()) {
547 Diag(Loc, diag::err_variably_modified_nontype_template_param)
548 << T;
549 return QualType();
552 // C++ [temp.param]p4:
554 // A non-type template-parameter shall have one of the following
555 // (optionally cv-qualified) types:
557 // -- integral or enumeration type,
558 if (T->isIntegralOrEnumerationType() ||
559 // -- pointer to object or pointer to function,
560 T->isPointerType() ||
561 // -- reference to object or reference to function,
562 T->isReferenceType() ||
563 // -- pointer to member.
564 T->isMemberPointerType() ||
565 // If T is a dependent type, we can't do the check now, so we
566 // assume that it is well-formed.
567 T->isDependentType())
568 return T;
569 // C++ [temp.param]p8:
571 // A non-type template-parameter of type "array of T" or
572 // "function returning T" is adjusted to be of type "pointer to
573 // T" or "pointer to function returning T", respectively.
574 else if (T->isArrayType())
575 // FIXME: Keep the type prior to promotion?
576 return Context.getArrayDecayedType(T);
577 else if (T->isFunctionType())
578 // FIXME: Keep the type prior to promotion?
579 return Context.getPointerType(T);
581 Diag(Loc, diag::err_template_nontype_parm_bad_type)
582 << T;
584 return QualType();
587 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
588 unsigned Depth,
589 unsigned Position,
590 SourceLocation EqualLoc,
591 Expr *Default) {
592 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
593 QualType T = TInfo->getType();
595 assert(S->isTemplateParamScope() &&
596 "Non-type template parameter not in template parameter scope!");
597 bool Invalid = false;
599 IdentifierInfo *ParamName = D.getIdentifier();
600 if (ParamName) {
601 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
602 LookupOrdinaryName,
603 ForRedeclaration);
604 if (PrevDecl && PrevDecl->isTemplateParameter())
605 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
606 PrevDecl);
609 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
610 if (T.isNull()) {
611 T = Context.IntTy; // Recover with an 'int' type.
612 Invalid = true;
615 NonTypeTemplateParmDecl *Param
616 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
617 D.getIdentifierLoc(),
618 Depth, Position, ParamName, T, TInfo);
619 if (Invalid)
620 Param->setInvalidDecl();
622 if (D.getIdentifier()) {
623 // Add the template parameter into the current scope.
624 S->AddDecl(Param);
625 IdResolver.AddDecl(Param);
628 // Check the well-formedness of the default template argument, if provided.
629 if (Default) {
630 TemplateArgument Converted;
631 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
632 Param->setInvalidDecl();
633 return Param;
636 Param->setDefaultArgument(Default, false);
639 return Param;
642 /// ActOnTemplateTemplateParameter - Called when a C++ template template
643 /// parameter (e.g. T in template <template <typename> class T> class array)
644 /// has been parsed. S is the current scope.
645 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
646 SourceLocation TmpLoc,
647 TemplateParamsTy *Params,
648 IdentifierInfo *Name,
649 SourceLocation NameLoc,
650 unsigned Depth,
651 unsigned Position,
652 SourceLocation EqualLoc,
653 const ParsedTemplateArgument &Default) {
654 assert(S->isTemplateParamScope() &&
655 "Template template parameter not in template parameter scope!");
657 // Construct the parameter object.
658 TemplateTemplateParmDecl *Param =
659 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
660 TmpLoc, Depth, Position, Name,
661 (TemplateParameterList*)Params);
663 // If the template template parameter has a name, then link the identifier
664 // into the scope and lookup mechanisms.
665 if (Name) {
666 S->AddDecl(Param);
667 IdResolver.AddDecl(Param);
670 if (!Default.isInvalid()) {
671 // Check only that we have a template template argument. We don't want to
672 // try to check well-formedness now, because our template template parameter
673 // might have dependent types in its template parameters, which we wouldn't
674 // be able to match now.
676 // If none of the template template parameter's template arguments mention
677 // other template parameters, we could actually perform more checking here.
678 // However, it isn't worth doing.
679 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
680 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
681 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
682 << DefaultArg.getSourceRange();
683 return Param;
686 Param->setDefaultArgument(DefaultArg, false);
689 return Param;
692 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
693 /// contains the template parameters in Params/NumParams.
694 Sema::TemplateParamsTy *
695 Sema::ActOnTemplateParameterList(unsigned Depth,
696 SourceLocation ExportLoc,
697 SourceLocation TemplateLoc,
698 SourceLocation LAngleLoc,
699 Decl **Params, unsigned NumParams,
700 SourceLocation RAngleLoc) {
701 if (ExportLoc.isValid())
702 Diag(ExportLoc, diag::warn_template_export_unsupported);
704 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
705 (NamedDecl**)Params, NumParams,
706 RAngleLoc);
709 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
710 if (SS.isSet())
711 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
712 SS.getRange());
715 DeclResult
716 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
717 SourceLocation KWLoc, CXXScopeSpec &SS,
718 IdentifierInfo *Name, SourceLocation NameLoc,
719 AttributeList *Attr,
720 TemplateParameterList *TemplateParams,
721 AccessSpecifier AS) {
722 assert(TemplateParams && TemplateParams->size() > 0 &&
723 "No template parameters");
724 assert(TUK != TUK_Reference && "Can only declare or define class templates");
725 bool Invalid = false;
727 // Check that we can declare a template here.
728 if (CheckTemplateDeclScope(S, TemplateParams))
729 return true;
731 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
732 assert(Kind != TTK_Enum && "can't build template of enumerated type");
734 // There is no such thing as an unnamed class template.
735 if (!Name) {
736 Diag(KWLoc, diag::err_template_unnamed_class);
737 return true;
740 // Find any previous declaration with this name.
741 DeclContext *SemanticContext;
742 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
743 ForRedeclaration);
744 if (SS.isNotEmpty() && !SS.isInvalid()) {
745 SemanticContext = computeDeclContext(SS, true);
746 if (!SemanticContext) {
747 // FIXME: Produce a reasonable diagnostic here
748 return true;
751 if (RequireCompleteDeclContext(SS, SemanticContext))
752 return true;
754 LookupQualifiedName(Previous, SemanticContext);
755 } else {
756 SemanticContext = CurContext;
757 LookupName(Previous, S);
760 if (Previous.isAmbiguous())
761 return true;
763 NamedDecl *PrevDecl = 0;
764 if (Previous.begin() != Previous.end())
765 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
767 // If there is a previous declaration with the same name, check
768 // whether this is a valid redeclaration.
769 ClassTemplateDecl *PrevClassTemplate
770 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
772 // We may have found the injected-class-name of a class template,
773 // class template partial specialization, or class template specialization.
774 // In these cases, grab the template that is being defined or specialized.
775 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
776 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
777 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
778 PrevClassTemplate
779 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
780 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
781 PrevClassTemplate
782 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
783 ->getSpecializedTemplate();
787 if (TUK == TUK_Friend) {
788 // C++ [namespace.memdef]p3:
789 // [...] When looking for a prior declaration of a class or a function
790 // declared as a friend, and when the name of the friend class or
791 // function is neither a qualified name nor a template-id, scopes outside
792 // the innermost enclosing namespace scope are not considered.
793 if (!SS.isSet()) {
794 DeclContext *OutermostContext = CurContext;
795 while (!OutermostContext->isFileContext())
796 OutermostContext = OutermostContext->getLookupParent();
798 if (PrevDecl &&
799 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
800 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
801 SemanticContext = PrevDecl->getDeclContext();
802 } else {
803 // Declarations in outer scopes don't matter. However, the outermost
804 // context we computed is the semantic context for our new
805 // declaration.
806 PrevDecl = PrevClassTemplate = 0;
807 SemanticContext = OutermostContext;
811 if (CurContext->isDependentContext()) {
812 // If this is a dependent context, we don't want to link the friend
813 // class template to the template in scope, because that would perform
814 // checking of the template parameter lists that can't be performed
815 // until the outer context is instantiated.
816 PrevDecl = PrevClassTemplate = 0;
818 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
819 PrevDecl = PrevClassTemplate = 0;
821 if (PrevClassTemplate) {
822 // Ensure that the template parameter lists are compatible.
823 if (!TemplateParameterListsAreEqual(TemplateParams,
824 PrevClassTemplate->getTemplateParameters(),
825 /*Complain=*/true,
826 TPL_TemplateMatch))
827 return true;
829 // C++ [temp.class]p4:
830 // In a redeclaration, partial specialization, explicit
831 // specialization or explicit instantiation of a class template,
832 // the class-key shall agree in kind with the original class
833 // template declaration (7.1.5.3).
834 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
835 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
836 Diag(KWLoc, diag::err_use_with_wrong_tag)
837 << Name
838 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
839 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
840 Kind = PrevRecordDecl->getTagKind();
843 // Check for redefinition of this class template.
844 if (TUK == TUK_Definition) {
845 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
846 Diag(NameLoc, diag::err_redefinition) << Name;
847 Diag(Def->getLocation(), diag::note_previous_definition);
848 // FIXME: Would it make sense to try to "forget" the previous
849 // definition, as part of error recovery?
850 return true;
853 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
854 // Maybe we will complain about the shadowed template parameter.
855 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
856 // Just pretend that we didn't see the previous declaration.
857 PrevDecl = 0;
858 } else if (PrevDecl) {
859 // C++ [temp]p5:
860 // A class template shall not have the same name as any other
861 // template, class, function, object, enumeration, enumerator,
862 // namespace, or type in the same scope (3.3), except as specified
863 // in (14.5.4).
864 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
865 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
866 return true;
869 // Check the template parameter list of this declaration, possibly
870 // merging in the template parameter list from the previous class
871 // template declaration.
872 if (CheckTemplateParameterList(TemplateParams,
873 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
874 TPC_ClassTemplate))
875 Invalid = true;
877 if (SS.isSet()) {
878 // If the name of the template was qualified, we must be defining the
879 // template out-of-line.
880 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
881 !(TUK == TUK_Friend && CurContext->isDependentContext()))
882 Diag(NameLoc, diag::err_member_def_does_not_match)
883 << Name << SemanticContext << SS.getRange();
886 CXXRecordDecl *NewClass =
887 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
888 PrevClassTemplate?
889 PrevClassTemplate->getTemplatedDecl() : 0,
890 /*DelayTypeCreation=*/true);
891 SetNestedNameSpecifier(NewClass, SS);
893 ClassTemplateDecl *NewTemplate
894 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
895 DeclarationName(Name), TemplateParams,
896 NewClass, PrevClassTemplate);
897 NewClass->setDescribedClassTemplate(NewTemplate);
899 // Build the type for the class template declaration now.
900 QualType T = NewTemplate->getInjectedClassNameSpecialization();
901 T = Context.getInjectedClassNameType(NewClass, T);
902 assert(T->isDependentType() && "Class template type is not dependent?");
903 (void)T;
905 // If we are providing an explicit specialization of a member that is a
906 // class template, make a note of that.
907 if (PrevClassTemplate &&
908 PrevClassTemplate->getInstantiatedFromMemberTemplate())
909 PrevClassTemplate->setMemberSpecialization();
911 // Set the access specifier.
912 if (!Invalid && TUK != TUK_Friend)
913 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
915 // Set the lexical context of these templates
916 NewClass->setLexicalDeclContext(CurContext);
917 NewTemplate->setLexicalDeclContext(CurContext);
919 if (TUK == TUK_Definition)
920 NewClass->startDefinition();
922 if (Attr)
923 ProcessDeclAttributeList(S, NewClass, Attr);
925 if (TUK != TUK_Friend)
926 PushOnScopeChains(NewTemplate, S);
927 else {
928 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
929 NewTemplate->setAccess(PrevClassTemplate->getAccess());
930 NewClass->setAccess(PrevClassTemplate->getAccess());
933 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
934 PrevClassTemplate != NULL);
936 // Friend templates are visible in fairly strange ways.
937 if (!CurContext->isDependentContext()) {
938 DeclContext *DC = SemanticContext->getLookupContext();
939 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
940 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
941 PushOnScopeChains(NewTemplate, EnclosingScope,
942 /* AddToContext = */ false);
945 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
946 NewClass->getLocation(),
947 NewTemplate,
948 /*FIXME:*/NewClass->getLocation());
949 Friend->setAccess(AS_public);
950 CurContext->addDecl(Friend);
953 if (Invalid) {
954 NewTemplate->setInvalidDecl();
955 NewClass->setInvalidDecl();
957 return NewTemplate;
960 /// \brief Diagnose the presence of a default template argument on a
961 /// template parameter, which is ill-formed in certain contexts.
963 /// \returns true if the default template argument should be dropped.
964 static bool DiagnoseDefaultTemplateArgument(Sema &S,
965 Sema::TemplateParamListContext TPC,
966 SourceLocation ParamLoc,
967 SourceRange DefArgRange) {
968 switch (TPC) {
969 case Sema::TPC_ClassTemplate:
970 return false;
972 case Sema::TPC_FunctionTemplate:
973 // C++ [temp.param]p9:
974 // A default template-argument shall not be specified in a
975 // function template declaration or a function template
976 // definition [...]
977 // (This sentence is not in C++0x, per DR226).
978 if (!S.getLangOptions().CPlusPlus0x)
979 S.Diag(ParamLoc,
980 diag::err_template_parameter_default_in_function_template)
981 << DefArgRange;
982 return false;
984 case Sema::TPC_ClassTemplateMember:
985 // C++0x [temp.param]p9:
986 // A default template-argument shall not be specified in the
987 // template-parameter-lists of the definition of a member of a
988 // class template that appears outside of the member's class.
989 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
990 << DefArgRange;
991 return true;
993 case Sema::TPC_FriendFunctionTemplate:
994 // C++ [temp.param]p9:
995 // A default template-argument shall not be specified in a
996 // friend template declaration.
997 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
998 << DefArgRange;
999 return true;
1001 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1002 // for friend function templates if there is only a single
1003 // declaration (and it is a definition). Strange!
1006 return false;
1009 /// \brief Checks the validity of a template parameter list, possibly
1010 /// considering the template parameter list from a previous
1011 /// declaration.
1013 /// If an "old" template parameter list is provided, it must be
1014 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1015 /// template parameter list.
1017 /// \param NewParams Template parameter list for a new template
1018 /// declaration. This template parameter list will be updated with any
1019 /// default arguments that are carried through from the previous
1020 /// template parameter list.
1022 /// \param OldParams If provided, template parameter list from a
1023 /// previous declaration of the same template. Default template
1024 /// arguments will be merged from the old template parameter list to
1025 /// the new template parameter list.
1027 /// \param TPC Describes the context in which we are checking the given
1028 /// template parameter list.
1030 /// \returns true if an error occurred, false otherwise.
1031 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1032 TemplateParameterList *OldParams,
1033 TemplateParamListContext TPC) {
1034 bool Invalid = false;
1036 // C++ [temp.param]p10:
1037 // The set of default template-arguments available for use with a
1038 // template declaration or definition is obtained by merging the
1039 // default arguments from the definition (if in scope) and all
1040 // declarations in scope in the same way default function
1041 // arguments are (8.3.6).
1042 bool SawDefaultArgument = false;
1043 SourceLocation PreviousDefaultArgLoc;
1045 bool SawParameterPack = false;
1046 SourceLocation ParameterPackLoc;
1048 // Dummy initialization to avoid warnings.
1049 TemplateParameterList::iterator OldParam = NewParams->end();
1050 if (OldParams)
1051 OldParam = OldParams->begin();
1053 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1054 NewParamEnd = NewParams->end();
1055 NewParam != NewParamEnd; ++NewParam) {
1056 // Variables used to diagnose redundant default arguments
1057 bool RedundantDefaultArg = false;
1058 SourceLocation OldDefaultLoc;
1059 SourceLocation NewDefaultLoc;
1061 // Variables used to diagnose missing default arguments
1062 bool MissingDefaultArg = false;
1064 // C++0x [temp.param]p11:
1065 // If a template parameter of a class template is a template parameter pack,
1066 // it must be the last template parameter.
1067 if (SawParameterPack) {
1068 Diag(ParameterPackLoc,
1069 diag::err_template_param_pack_must_be_last_template_parameter);
1070 Invalid = true;
1073 if (TemplateTypeParmDecl *NewTypeParm
1074 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1075 // Check the presence of a default argument here.
1076 if (NewTypeParm->hasDefaultArgument() &&
1077 DiagnoseDefaultTemplateArgument(*this, TPC,
1078 NewTypeParm->getLocation(),
1079 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1080 .getSourceRange()))
1081 NewTypeParm->removeDefaultArgument();
1083 // Merge default arguments for template type parameters.
1084 TemplateTypeParmDecl *OldTypeParm
1085 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1087 if (NewTypeParm->isParameterPack()) {
1088 assert(!NewTypeParm->hasDefaultArgument() &&
1089 "Parameter packs can't have a default argument!");
1090 SawParameterPack = true;
1091 ParameterPackLoc = NewTypeParm->getLocation();
1092 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1093 NewTypeParm->hasDefaultArgument()) {
1094 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1095 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1096 SawDefaultArgument = true;
1097 RedundantDefaultArg = true;
1098 PreviousDefaultArgLoc = NewDefaultLoc;
1099 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1100 // Merge the default argument from the old declaration to the
1101 // new declaration.
1102 SawDefaultArgument = true;
1103 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1104 true);
1105 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1106 } else if (NewTypeParm->hasDefaultArgument()) {
1107 SawDefaultArgument = true;
1108 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1109 } else if (SawDefaultArgument)
1110 MissingDefaultArg = true;
1111 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1112 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1113 // Check the presence of a default argument here.
1114 if (NewNonTypeParm->hasDefaultArgument() &&
1115 DiagnoseDefaultTemplateArgument(*this, TPC,
1116 NewNonTypeParm->getLocation(),
1117 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1118 NewNonTypeParm->removeDefaultArgument();
1121 // Merge default arguments for non-type template parameters
1122 NonTypeTemplateParmDecl *OldNonTypeParm
1123 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1124 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1125 NewNonTypeParm->hasDefaultArgument()) {
1126 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1127 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1128 SawDefaultArgument = true;
1129 RedundantDefaultArg = true;
1130 PreviousDefaultArgLoc = NewDefaultLoc;
1131 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1132 // Merge the default argument from the old declaration to the
1133 // new declaration.
1134 SawDefaultArgument = true;
1135 // FIXME: We need to create a new kind of "default argument"
1136 // expression that points to a previous template template
1137 // parameter.
1138 NewNonTypeParm->setDefaultArgument(
1139 OldNonTypeParm->getDefaultArgument(),
1140 /*Inherited=*/ true);
1141 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1142 } else if (NewNonTypeParm->hasDefaultArgument()) {
1143 SawDefaultArgument = true;
1144 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1145 } else if (SawDefaultArgument)
1146 MissingDefaultArg = true;
1147 } else {
1148 // Check the presence of a default argument here.
1149 TemplateTemplateParmDecl *NewTemplateParm
1150 = cast<TemplateTemplateParmDecl>(*NewParam);
1151 if (NewTemplateParm->hasDefaultArgument() &&
1152 DiagnoseDefaultTemplateArgument(*this, TPC,
1153 NewTemplateParm->getLocation(),
1154 NewTemplateParm->getDefaultArgument().getSourceRange()))
1155 NewTemplateParm->removeDefaultArgument();
1157 // Merge default arguments for template template parameters
1158 TemplateTemplateParmDecl *OldTemplateParm
1159 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1160 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1161 NewTemplateParm->hasDefaultArgument()) {
1162 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1163 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1164 SawDefaultArgument = true;
1165 RedundantDefaultArg = true;
1166 PreviousDefaultArgLoc = NewDefaultLoc;
1167 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1168 // Merge the default argument from the old declaration to the
1169 // new declaration.
1170 SawDefaultArgument = true;
1171 // FIXME: We need to create a new kind of "default argument" expression
1172 // that points to a previous template template parameter.
1173 NewTemplateParm->setDefaultArgument(
1174 OldTemplateParm->getDefaultArgument(),
1175 /*Inherited=*/ true);
1176 PreviousDefaultArgLoc
1177 = OldTemplateParm->getDefaultArgument().getLocation();
1178 } else if (NewTemplateParm->hasDefaultArgument()) {
1179 SawDefaultArgument = true;
1180 PreviousDefaultArgLoc
1181 = NewTemplateParm->getDefaultArgument().getLocation();
1182 } else if (SawDefaultArgument)
1183 MissingDefaultArg = true;
1186 if (RedundantDefaultArg) {
1187 // C++ [temp.param]p12:
1188 // A template-parameter shall not be given default arguments
1189 // by two different declarations in the same scope.
1190 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1191 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1192 Invalid = true;
1193 } else if (MissingDefaultArg) {
1194 // C++ [temp.param]p11:
1195 // If a template-parameter has a default template-argument,
1196 // all subsequent template-parameters shall have a default
1197 // template-argument supplied.
1198 Diag((*NewParam)->getLocation(),
1199 diag::err_template_param_default_arg_missing);
1200 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1201 Invalid = true;
1204 // If we have an old template parameter list that we're merging
1205 // in, move on to the next parameter.
1206 if (OldParams)
1207 ++OldParam;
1210 return Invalid;
1213 /// \brief Match the given template parameter lists to the given scope
1214 /// specifier, returning the template parameter list that applies to the
1215 /// name.
1217 /// \param DeclStartLoc the start of the declaration that has a scope
1218 /// specifier or a template parameter list.
1220 /// \param SS the scope specifier that will be matched to the given template
1221 /// parameter lists. This scope specifier precedes a qualified name that is
1222 /// being declared.
1224 /// \param ParamLists the template parameter lists, from the outermost to the
1225 /// innermost template parameter lists.
1227 /// \param NumParamLists the number of template parameter lists in ParamLists.
1229 /// \param IsFriend Whether to apply the slightly different rules for
1230 /// matching template parameters to scope specifiers in friend
1231 /// declarations.
1233 /// \param IsExplicitSpecialization will be set true if the entity being
1234 /// declared is an explicit specialization, false otherwise.
1236 /// \returns the template parameter list, if any, that corresponds to the
1237 /// name that is preceded by the scope specifier @p SS. This template
1238 /// parameter list may be have template parameters (if we're declaring a
1239 /// template) or may have no template parameters (if we're declaring a
1240 /// template specialization), or may be NULL (if we were's declaring isn't
1241 /// itself a template).
1242 TemplateParameterList *
1243 Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1244 const CXXScopeSpec &SS,
1245 TemplateParameterList **ParamLists,
1246 unsigned NumParamLists,
1247 bool IsFriend,
1248 bool &IsExplicitSpecialization,
1249 bool &Invalid) {
1250 IsExplicitSpecialization = false;
1252 // Find the template-ids that occur within the nested-name-specifier. These
1253 // template-ids will match up with the template parameter lists.
1254 llvm::SmallVector<const TemplateSpecializationType *, 4>
1255 TemplateIdsInSpecifier;
1256 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1257 ExplicitSpecializationsInSpecifier;
1258 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1259 NNS; NNS = NNS->getPrefix()) {
1260 const Type *T = NNS->getAsType();
1261 if (!T) break;
1263 // C++0x [temp.expl.spec]p17:
1264 // A member or a member template may be nested within many
1265 // enclosing class templates. In an explicit specialization for
1266 // such a member, the member declaration shall be preceded by a
1267 // template<> for each enclosing class template that is
1268 // explicitly specialized.
1270 // Following the existing practice of GNU and EDG, we allow a typedef of a
1271 // template specialization type.
1272 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1273 T = TT->LookThroughTypedefs().getTypePtr();
1275 if (const TemplateSpecializationType *SpecType
1276 = dyn_cast<TemplateSpecializationType>(T)) {
1277 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1278 if (!Template)
1279 continue; // FIXME: should this be an error? probably...
1281 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
1282 ClassTemplateSpecializationDecl *SpecDecl
1283 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1284 // If the nested name specifier refers to an explicit specialization,
1285 // we don't need a template<> header.
1286 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1287 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
1288 continue;
1292 TemplateIdsInSpecifier.push_back(SpecType);
1296 // Reverse the list of template-ids in the scope specifier, so that we can
1297 // more easily match up the template-ids and the template parameter lists.
1298 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
1300 SourceLocation FirstTemplateLoc = DeclStartLoc;
1301 if (NumParamLists)
1302 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
1304 // Match the template-ids found in the specifier to the template parameter
1305 // lists.
1306 unsigned Idx = 0;
1307 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1308 Idx != NumTemplateIds; ++Idx) {
1309 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1310 bool DependentTemplateId = TemplateId->isDependentType();
1311 if (Idx >= NumParamLists) {
1312 // We have a template-id without a corresponding template parameter
1313 // list.
1315 // ...which is fine if this is a friend declaration.
1316 if (IsFriend) {
1317 IsExplicitSpecialization = true;
1318 break;
1321 if (DependentTemplateId) {
1322 // FIXME: the location information here isn't great.
1323 Diag(SS.getRange().getBegin(),
1324 diag::err_template_spec_needs_template_parameters)
1325 << TemplateId
1326 << SS.getRange();
1327 Invalid = true;
1328 } else {
1329 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1330 << SS.getRange()
1331 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
1332 IsExplicitSpecialization = true;
1334 return 0;
1337 // Check the template parameter list against its corresponding template-id.
1338 if (DependentTemplateId) {
1339 TemplateParameterList *ExpectedTemplateParams = 0;
1341 // Are there cases in (e.g.) friends where this won't match?
1342 if (const InjectedClassNameType *Injected
1343 = TemplateId->getAs<InjectedClassNameType>()) {
1344 CXXRecordDecl *Record = Injected->getDecl();
1345 if (ClassTemplatePartialSpecializationDecl *Partial =
1346 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1347 ExpectedTemplateParams = Partial->getTemplateParameters();
1348 else
1349 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1350 ->getTemplateParameters();
1353 if (ExpectedTemplateParams)
1354 TemplateParameterListsAreEqual(ParamLists[Idx],
1355 ExpectedTemplateParams,
1356 true, TPL_TemplateMatch);
1358 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
1359 } else if (ParamLists[Idx]->size() > 0)
1360 Diag(ParamLists[Idx]->getTemplateLoc(),
1361 diag::err_template_param_list_matches_nontemplate)
1362 << TemplateId
1363 << ParamLists[Idx]->getSourceRange();
1364 else
1365 IsExplicitSpecialization = true;
1368 // If there were at least as many template-ids as there were template
1369 // parameter lists, then there are no template parameter lists remaining for
1370 // the declaration itself.
1371 if (Idx >= NumParamLists)
1372 return 0;
1374 // If there were too many template parameter lists, complain about that now.
1375 if (Idx != NumParamLists - 1) {
1376 while (Idx < NumParamLists - 1) {
1377 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
1378 Diag(ParamLists[Idx]->getTemplateLoc(),
1379 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1380 : diag::err_template_spec_extra_headers)
1381 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1382 ParamLists[Idx]->getRAngleLoc());
1384 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1385 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1386 diag::note_explicit_template_spec_does_not_need_header)
1387 << ExplicitSpecializationsInSpecifier.back();
1388 ExplicitSpecializationsInSpecifier.pop_back();
1391 // We have a template parameter list with no corresponding scope, which
1392 // means that the resulting template declaration can't be instantiated
1393 // properly (we'll end up with dependent nodes when we shouldn't).
1394 if (!isExplicitSpecHeader)
1395 Invalid = true;
1397 ++Idx;
1401 // Return the last template parameter list, which corresponds to the
1402 // entity being declared.
1403 return ParamLists[NumParamLists - 1];
1406 QualType Sema::CheckTemplateIdType(TemplateName Name,
1407 SourceLocation TemplateLoc,
1408 const TemplateArgumentListInfo &TemplateArgs) {
1409 TemplateDecl *Template = Name.getAsTemplateDecl();
1410 if (!Template) {
1411 // The template name does not resolve to a template, so we just
1412 // build a dependent template-id type.
1413 return Context.getTemplateSpecializationType(Name, TemplateArgs);
1416 // Check that the template argument list is well-formed for this
1417 // template.
1418 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1419 TemplateArgs.size());
1420 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1421 false, Converted))
1422 return QualType();
1424 assert((Converted.structuredSize() ==
1425 Template->getTemplateParameters()->size()) &&
1426 "Converted template argument list is too short!");
1428 QualType CanonType;
1430 if (Name.isDependent() ||
1431 TemplateSpecializationType::anyDependentTemplateArguments(
1432 TemplateArgs)) {
1433 // This class template specialization is a dependent
1434 // type. Therefore, its canonical type is another class template
1435 // specialization type that contains all of the converted
1436 // arguments in canonical form. This ensures that, e.g., A<T> and
1437 // A<T, T> have identical types when A is declared as:
1439 // template<typename T, typename U = T> struct A;
1440 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1441 CanonType = Context.getTemplateSpecializationType(CanonName,
1442 Converted.getFlatArguments(),
1443 Converted.flatSize());
1445 // FIXME: CanonType is not actually the canonical type, and unfortunately
1446 // it is a TemplateSpecializationType that we will never use again.
1447 // In the future, we need to teach getTemplateSpecializationType to only
1448 // build the canonical type and return that to us.
1449 CanonType = Context.getCanonicalType(CanonType);
1451 // This might work out to be a current instantiation, in which
1452 // case the canonical type needs to be the InjectedClassNameType.
1454 // TODO: in theory this could be a simple hashtable lookup; most
1455 // changes to CurContext don't change the set of current
1456 // instantiations.
1457 if (isa<ClassTemplateDecl>(Template)) {
1458 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1459 // If we get out to a namespace, we're done.
1460 if (Ctx->isFileContext()) break;
1462 // If this isn't a record, keep looking.
1463 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1464 if (!Record) continue;
1466 // Look for one of the two cases with InjectedClassNameTypes
1467 // and check whether it's the same template.
1468 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1469 !Record->getDescribedClassTemplate())
1470 continue;
1472 // Fetch the injected class name type and check whether its
1473 // injected type is equal to the type we just built.
1474 QualType ICNT = Context.getTypeDeclType(Record);
1475 QualType Injected = cast<InjectedClassNameType>(ICNT)
1476 ->getInjectedSpecializationType();
1478 if (CanonType != Injected->getCanonicalTypeInternal())
1479 continue;
1481 // If so, the canonical type of this TST is the injected
1482 // class name type of the record we just found.
1483 assert(ICNT.isCanonical());
1484 CanonType = ICNT;
1485 break;
1488 } else if (ClassTemplateDecl *ClassTemplate
1489 = dyn_cast<ClassTemplateDecl>(Template)) {
1490 // Find the class template specialization declaration that
1491 // corresponds to these arguments.
1492 void *InsertPos = 0;
1493 ClassTemplateSpecializationDecl *Decl
1494 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
1495 Converted.flatSize(), InsertPos);
1496 if (!Decl) {
1497 // This is the first time we have referenced this class template
1498 // specialization. Create the canonical declaration and add it to
1499 // the set of specializations.
1500 Decl = ClassTemplateSpecializationDecl::Create(Context,
1501 ClassTemplate->getTemplatedDecl()->getTagKind(),
1502 ClassTemplate->getDeclContext(),
1503 ClassTemplate->getLocation(),
1504 ClassTemplate,
1505 Converted, 0);
1506 ClassTemplate->AddSpecialization(Decl, InsertPos);
1507 Decl->setLexicalDeclContext(CurContext);
1510 CanonType = Context.getTypeDeclType(Decl);
1511 assert(isa<RecordType>(CanonType) &&
1512 "type of non-dependent specialization is not a RecordType");
1515 // Build the fully-sugared type for this class template
1516 // specialization, which refers back to the class template
1517 // specialization we created or found.
1518 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
1521 TypeResult
1522 Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1523 SourceLocation LAngleLoc,
1524 ASTTemplateArgsPtr TemplateArgsIn,
1525 SourceLocation RAngleLoc) {
1526 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1528 // Translate the parser's template argument list in our AST format.
1529 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
1530 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
1532 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
1533 TemplateArgsIn.release();
1535 if (Result.isNull())
1536 return true;
1538 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
1539 TemplateSpecializationTypeLoc TL
1540 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1541 TL.setTemplateNameLoc(TemplateLoc);
1542 TL.setLAngleLoc(LAngleLoc);
1543 TL.setRAngleLoc(RAngleLoc);
1544 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1545 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1547 return CreateParsedType(Result, DI);
1550 TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1551 TagUseKind TUK,
1552 TypeSpecifierType TagSpec,
1553 SourceLocation TagLoc) {
1554 if (TypeResult.isInvalid())
1555 return ::TypeResult();
1557 // FIXME: preserve source info, ideally without copying the DI.
1558 TypeSourceInfo *DI;
1559 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
1561 // Verify the tag specifier.
1562 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1564 if (const RecordType *RT = Type->getAs<RecordType>()) {
1565 RecordDecl *D = RT->getDecl();
1567 IdentifierInfo *Id = D->getIdentifier();
1568 assert(Id && "templated class must have an identifier");
1570 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1571 Diag(TagLoc, diag::err_use_with_wrong_tag)
1572 << Type
1573 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
1574 Diag(D->getLocation(), diag::note_previous_use);
1578 ElaboratedTypeKeyword Keyword
1579 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1580 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
1582 return ParsedType::make(ElabType);
1585 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1586 LookupResult &R,
1587 bool RequiresADL,
1588 const TemplateArgumentListInfo &TemplateArgs) {
1589 // FIXME: Can we do any checking at this point? I guess we could check the
1590 // template arguments that we have against the template name, if the template
1591 // name refers to a single template. That's not a terribly common case,
1592 // though.
1594 // These should be filtered out by our callers.
1595 assert(!R.empty() && "empty lookup results when building templateid");
1596 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1598 NestedNameSpecifier *Qualifier = 0;
1599 SourceRange QualifierRange;
1600 if (SS.isSet()) {
1601 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1602 QualifierRange = SS.getRange();
1605 // We don't want lookup warnings at this point.
1606 R.suppressDiagnostics();
1608 bool Dependent
1609 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1610 &TemplateArgs);
1611 UnresolvedLookupExpr *ULE
1612 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
1613 Qualifier, QualifierRange,
1614 R.getLookupNameInfo(),
1615 RequiresADL, TemplateArgs,
1616 R.begin(), R.end());
1618 return Owned(ULE);
1621 // We actually only call this from template instantiation.
1622 ExprResult
1623 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
1624 const DeclarationNameInfo &NameInfo,
1625 const TemplateArgumentListInfo &TemplateArgs) {
1626 DeclContext *DC;
1627 if (!(DC = computeDeclContext(SS, false)) ||
1628 DC->isDependentContext() ||
1629 RequireCompleteDeclContext(SS, DC))
1630 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
1632 bool MemberOfUnknownSpecialization;
1633 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1634 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1635 MemberOfUnknownSpecialization);
1637 if (R.isAmbiguous())
1638 return ExprError();
1640 if (R.empty()) {
1641 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1642 << NameInfo.getName() << SS.getRange();
1643 return ExprError();
1646 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1647 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1648 << (NestedNameSpecifier*) SS.getScopeRep()
1649 << NameInfo.getName() << SS.getRange();
1650 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1651 return ExprError();
1654 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
1657 /// \brief Form a dependent template name.
1659 /// This action forms a dependent template name given the template
1660 /// name and its (presumably dependent) scope specifier. For
1661 /// example, given "MetaFun::template apply", the scope specifier \p
1662 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1663 /// of the "template" keyword, and "apply" is the \p Name.
1664 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1665 SourceLocation TemplateKWLoc,
1666 CXXScopeSpec &SS,
1667 UnqualifiedId &Name,
1668 ParsedType ObjectType,
1669 bool EnteringContext,
1670 TemplateTy &Result) {
1671 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1672 !getLangOptions().CPlusPlus0x)
1673 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1674 << FixItHint::CreateRemoval(TemplateKWLoc);
1676 DeclContext *LookupCtx = 0;
1677 if (SS.isSet())
1678 LookupCtx = computeDeclContext(SS, EnteringContext);
1679 if (!LookupCtx && ObjectType)
1680 LookupCtx = computeDeclContext(ObjectType.get());
1681 if (LookupCtx) {
1682 // C++0x [temp.names]p5:
1683 // If a name prefixed by the keyword template is not the name of
1684 // a template, the program is ill-formed. [Note: the keyword
1685 // template may not be applied to non-template members of class
1686 // templates. -end note ] [ Note: as is the case with the
1687 // typename prefix, the template prefix is allowed in cases
1688 // where it is not strictly necessary; i.e., when the
1689 // nested-name-specifier or the expression on the left of the ->
1690 // or . is not dependent on a template-parameter, or the use
1691 // does not appear in the scope of a template. -end note]
1693 // Note: C++03 was more strict here, because it banned the use of
1694 // the "template" keyword prior to a template-name that was not a
1695 // dependent name. C++ DR468 relaxed this requirement (the
1696 // "template" keyword is now permitted). We follow the C++0x
1697 // rules, even in C++03 mode with a warning, retroactively applying the DR.
1698 bool MemberOfUnknownSpecialization;
1699 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1700 ObjectType, EnteringContext, Result,
1701 MemberOfUnknownSpecialization);
1702 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1703 isa<CXXRecordDecl>(LookupCtx) &&
1704 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
1705 // This is a dependent template. Handle it below.
1706 } else if (TNK == TNK_Non_template) {
1707 Diag(Name.getSourceRange().getBegin(),
1708 diag::err_template_kw_refers_to_non_template)
1709 << GetNameFromUnqualifiedId(Name).getName()
1710 << Name.getSourceRange()
1711 << TemplateKWLoc;
1712 return TNK_Non_template;
1713 } else {
1714 // We found something; return it.
1715 return TNK;
1719 NestedNameSpecifier *Qualifier
1720 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1722 switch (Name.getKind()) {
1723 case UnqualifiedId::IK_Identifier:
1724 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1725 Name.Identifier));
1726 return TNK_Dependent_template_name;
1728 case UnqualifiedId::IK_OperatorFunctionId:
1729 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1730 Name.OperatorFunctionId.Operator));
1731 return TNK_Dependent_template_name;
1733 case UnqualifiedId::IK_LiteralOperatorId:
1734 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1736 default:
1737 break;
1740 Diag(Name.getSourceRange().getBegin(),
1741 diag::err_template_kw_refers_to_non_template)
1742 << GetNameFromUnqualifiedId(Name).getName()
1743 << Name.getSourceRange()
1744 << TemplateKWLoc;
1745 return TNK_Non_template;
1748 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1749 const TemplateArgumentLoc &AL,
1750 TemplateArgumentListBuilder &Converted) {
1751 const TemplateArgument &Arg = AL.getArgument();
1753 // Check template type parameter.
1754 switch(Arg.getKind()) {
1755 case TemplateArgument::Type:
1756 // C++ [temp.arg.type]p1:
1757 // A template-argument for a template-parameter which is a
1758 // type shall be a type-id.
1759 break;
1760 case TemplateArgument::Template: {
1761 // We have a template type parameter but the template argument
1762 // is a template without any arguments.
1763 SourceRange SR = AL.getSourceRange();
1764 TemplateName Name = Arg.getAsTemplate();
1765 Diag(SR.getBegin(), diag::err_template_missing_args)
1766 << Name << SR;
1767 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1768 Diag(Decl->getLocation(), diag::note_template_decl_here);
1770 return true;
1772 default: {
1773 // We have a template type parameter but the template argument
1774 // is not a type.
1775 SourceRange SR = AL.getSourceRange();
1776 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
1777 Diag(Param->getLocation(), diag::note_template_param_here);
1779 return true;
1783 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
1784 return true;
1786 // Add the converted template type argument.
1787 Converted.Append(
1788 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
1789 return false;
1792 /// \brief Substitute template arguments into the default template argument for
1793 /// the given template type parameter.
1795 /// \param SemaRef the semantic analysis object for which we are performing
1796 /// the substitution.
1798 /// \param Template the template that we are synthesizing template arguments
1799 /// for.
1801 /// \param TemplateLoc the location of the template name that started the
1802 /// template-id we are checking.
1804 /// \param RAngleLoc the location of the right angle bracket ('>') that
1805 /// terminates the template-id.
1807 /// \param Param the template template parameter whose default we are
1808 /// substituting into.
1810 /// \param Converted the list of template arguments provided for template
1811 /// parameters that precede \p Param in the template parameter list.
1813 /// \returns the substituted template argument, or NULL if an error occurred.
1814 static TypeSourceInfo *
1815 SubstDefaultTemplateArgument(Sema &SemaRef,
1816 TemplateDecl *Template,
1817 SourceLocation TemplateLoc,
1818 SourceLocation RAngleLoc,
1819 TemplateTypeParmDecl *Param,
1820 TemplateArgumentListBuilder &Converted) {
1821 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
1823 // If the argument type is dependent, instantiate it now based
1824 // on the previously-computed template arguments.
1825 if (ArgType->getType()->isDependentType()) {
1826 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1827 /*TakeArgs=*/false);
1829 MultiLevelTemplateArgumentList AllTemplateArgs
1830 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1832 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1833 Template, Converted.getFlatArguments(),
1834 Converted.flatSize(),
1835 SourceRange(TemplateLoc, RAngleLoc));
1837 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1838 Param->getDefaultArgumentLoc(),
1839 Param->getDeclName());
1842 return ArgType;
1845 /// \brief Substitute template arguments into the default template argument for
1846 /// the given non-type template parameter.
1848 /// \param SemaRef the semantic analysis object for which we are performing
1849 /// the substitution.
1851 /// \param Template the template that we are synthesizing template arguments
1852 /// for.
1854 /// \param TemplateLoc the location of the template name that started the
1855 /// template-id we are checking.
1857 /// \param RAngleLoc the location of the right angle bracket ('>') that
1858 /// terminates the template-id.
1860 /// \param Param the non-type template parameter whose default we are
1861 /// substituting into.
1863 /// \param Converted the list of template arguments provided for template
1864 /// parameters that precede \p Param in the template parameter list.
1866 /// \returns the substituted template argument, or NULL if an error occurred.
1867 static ExprResult
1868 SubstDefaultTemplateArgument(Sema &SemaRef,
1869 TemplateDecl *Template,
1870 SourceLocation TemplateLoc,
1871 SourceLocation RAngleLoc,
1872 NonTypeTemplateParmDecl *Param,
1873 TemplateArgumentListBuilder &Converted) {
1874 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1875 /*TakeArgs=*/false);
1877 MultiLevelTemplateArgumentList AllTemplateArgs
1878 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1880 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1881 Template, Converted.getFlatArguments(),
1882 Converted.flatSize(),
1883 SourceRange(TemplateLoc, RAngleLoc));
1885 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1888 /// \brief Substitute template arguments into the default template argument for
1889 /// the given template template parameter.
1891 /// \param SemaRef the semantic analysis object for which we are performing
1892 /// the substitution.
1894 /// \param Template the template that we are synthesizing template arguments
1895 /// for.
1897 /// \param TemplateLoc the location of the template name that started the
1898 /// template-id we are checking.
1900 /// \param RAngleLoc the location of the right angle bracket ('>') that
1901 /// terminates the template-id.
1903 /// \param Param the template template parameter whose default we are
1904 /// substituting into.
1906 /// \param Converted the list of template arguments provided for template
1907 /// parameters that precede \p Param in the template parameter list.
1909 /// \returns the substituted template argument, or NULL if an error occurred.
1910 static TemplateName
1911 SubstDefaultTemplateArgument(Sema &SemaRef,
1912 TemplateDecl *Template,
1913 SourceLocation TemplateLoc,
1914 SourceLocation RAngleLoc,
1915 TemplateTemplateParmDecl *Param,
1916 TemplateArgumentListBuilder &Converted) {
1917 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1918 /*TakeArgs=*/false);
1920 MultiLevelTemplateArgumentList AllTemplateArgs
1921 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1923 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1924 Template, Converted.getFlatArguments(),
1925 Converted.flatSize(),
1926 SourceRange(TemplateLoc, RAngleLoc));
1928 return SemaRef.SubstTemplateName(
1929 Param->getDefaultArgument().getArgument().getAsTemplate(),
1930 Param->getDefaultArgument().getTemplateNameLoc(),
1931 AllTemplateArgs);
1934 /// \brief If the given template parameter has a default template
1935 /// argument, substitute into that default template argument and
1936 /// return the corresponding template argument.
1937 TemplateArgumentLoc
1938 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1939 SourceLocation TemplateLoc,
1940 SourceLocation RAngleLoc,
1941 Decl *Param,
1942 TemplateArgumentListBuilder &Converted) {
1943 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1944 if (!TypeParm->hasDefaultArgument())
1945 return TemplateArgumentLoc();
1947 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
1948 TemplateLoc,
1949 RAngleLoc,
1950 TypeParm,
1951 Converted);
1952 if (DI)
1953 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1955 return TemplateArgumentLoc();
1958 if (NonTypeTemplateParmDecl *NonTypeParm
1959 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1960 if (!NonTypeParm->hasDefaultArgument())
1961 return TemplateArgumentLoc();
1963 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1964 TemplateLoc,
1965 RAngleLoc,
1966 NonTypeParm,
1967 Converted);
1968 if (Arg.isInvalid())
1969 return TemplateArgumentLoc();
1971 Expr *ArgE = Arg.takeAs<Expr>();
1972 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1975 TemplateTemplateParmDecl *TempTempParm
1976 = cast<TemplateTemplateParmDecl>(Param);
1977 if (!TempTempParm->hasDefaultArgument())
1978 return TemplateArgumentLoc();
1980 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
1981 TemplateLoc,
1982 RAngleLoc,
1983 TempTempParm,
1984 Converted);
1985 if (TName.isNull())
1986 return TemplateArgumentLoc();
1988 return TemplateArgumentLoc(TemplateArgument(TName),
1989 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
1990 TempTempParm->getDefaultArgument().getTemplateNameLoc());
1993 /// \brief Check that the given template argument corresponds to the given
1994 /// template parameter.
1995 bool Sema::CheckTemplateArgument(NamedDecl *Param,
1996 const TemplateArgumentLoc &Arg,
1997 TemplateDecl *Template,
1998 SourceLocation TemplateLoc,
1999 SourceLocation RAngleLoc,
2000 TemplateArgumentListBuilder &Converted,
2001 CheckTemplateArgumentKind CTAK) {
2002 // Check template type parameters.
2003 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2004 return CheckTemplateTypeArgument(TTP, Arg, Converted);
2006 // Check non-type template parameters.
2007 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2008 // Do substitution on the type of the non-type template parameter
2009 // with the template arguments we've seen thus far.
2010 QualType NTTPType = NTTP->getType();
2011 if (NTTPType->isDependentType()) {
2012 // Do substitution on the type of the non-type template parameter.
2013 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2014 NTTP, Converted.getFlatArguments(),
2015 Converted.flatSize(),
2016 SourceRange(TemplateLoc, RAngleLoc));
2018 TemplateArgumentList TemplateArgs(Context, Converted,
2019 /*TakeArgs=*/false);
2020 NTTPType = SubstType(NTTPType,
2021 MultiLevelTemplateArgumentList(TemplateArgs),
2022 NTTP->getLocation(),
2023 NTTP->getDeclName());
2024 // If that worked, check the non-type template parameter type
2025 // for validity.
2026 if (!NTTPType.isNull())
2027 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2028 NTTP->getLocation());
2029 if (NTTPType.isNull())
2030 return true;
2033 switch (Arg.getArgument().getKind()) {
2034 case TemplateArgument::Null:
2035 assert(false && "Should never see a NULL template argument here");
2036 return true;
2038 case TemplateArgument::Expression: {
2039 Expr *E = Arg.getArgument().getAsExpr();
2040 TemplateArgument Result;
2041 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
2042 return true;
2044 Converted.Append(Result);
2045 break;
2048 case TemplateArgument::Declaration:
2049 case TemplateArgument::Integral:
2050 // We've already checked this template argument, so just copy
2051 // it to the list of converted arguments.
2052 Converted.Append(Arg.getArgument());
2053 break;
2055 case TemplateArgument::Template:
2056 // We were given a template template argument. It may not be ill-formed;
2057 // see below.
2058 if (DependentTemplateName *DTN
2059 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2060 // We have a template argument such as \c T::template X, which we
2061 // parsed as a template template argument. However, since we now
2062 // know that we need a non-type template argument, convert this
2063 // template name into an expression.
2065 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2066 Arg.getTemplateNameLoc());
2068 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2069 DTN->getQualifier(),
2070 Arg.getTemplateQualifierRange(),
2071 NameInfo);
2073 TemplateArgument Result;
2074 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2075 return true;
2077 Converted.Append(Result);
2078 break;
2081 // We have a template argument that actually does refer to a class
2082 // template, template alias, or template template parameter, and
2083 // therefore cannot be a non-type template argument.
2084 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2085 << Arg.getSourceRange();
2087 Diag(Param->getLocation(), diag::note_template_param_here);
2088 return true;
2090 case TemplateArgument::Type: {
2091 // We have a non-type template parameter but the template
2092 // argument is a type.
2094 // C++ [temp.arg]p2:
2095 // In a template-argument, an ambiguity between a type-id and
2096 // an expression is resolved to a type-id, regardless of the
2097 // form of the corresponding template-parameter.
2099 // We warn specifically about this case, since it can be rather
2100 // confusing for users.
2101 QualType T = Arg.getArgument().getAsType();
2102 SourceRange SR = Arg.getSourceRange();
2103 if (T->isFunctionType())
2104 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2105 else
2106 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2107 Diag(Param->getLocation(), diag::note_template_param_here);
2108 return true;
2111 case TemplateArgument::Pack:
2112 llvm_unreachable("Caller must expand template argument packs");
2113 break;
2116 return false;
2120 // Check template template parameters.
2121 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2123 // Substitute into the template parameter list of the template
2124 // template parameter, since previously-supplied template arguments
2125 // may appear within the template template parameter.
2127 // Set up a template instantiation context.
2128 LocalInstantiationScope Scope(*this);
2129 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2130 TempParm, Converted.getFlatArguments(),
2131 Converted.flatSize(),
2132 SourceRange(TemplateLoc, RAngleLoc));
2134 TemplateArgumentList TemplateArgs(Context, Converted,
2135 /*TakeArgs=*/false);
2136 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2137 SubstDecl(TempParm, CurContext,
2138 MultiLevelTemplateArgumentList(TemplateArgs)));
2139 if (!TempParm)
2140 return true;
2142 // FIXME: TempParam is leaked.
2145 switch (Arg.getArgument().getKind()) {
2146 case TemplateArgument::Null:
2147 assert(false && "Should never see a NULL template argument here");
2148 return true;
2150 case TemplateArgument::Template:
2151 if (CheckTemplateArgument(TempParm, Arg))
2152 return true;
2154 Converted.Append(Arg.getArgument());
2155 break;
2157 case TemplateArgument::Expression:
2158 case TemplateArgument::Type:
2159 // We have a template template parameter but the template
2160 // argument does not refer to a template.
2161 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2162 return true;
2164 case TemplateArgument::Declaration:
2165 llvm_unreachable(
2166 "Declaration argument with template template parameter");
2167 break;
2168 case TemplateArgument::Integral:
2169 llvm_unreachable(
2170 "Integral argument with template template parameter");
2171 break;
2173 case TemplateArgument::Pack:
2174 llvm_unreachable("Caller must expand template argument packs");
2175 break;
2178 return false;
2181 /// \brief Check that the given template argument list is well-formed
2182 /// for specializing the given template.
2183 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2184 SourceLocation TemplateLoc,
2185 const TemplateArgumentListInfo &TemplateArgs,
2186 bool PartialTemplateArgs,
2187 TemplateArgumentListBuilder &Converted) {
2188 TemplateParameterList *Params = Template->getTemplateParameters();
2189 unsigned NumParams = Params->size();
2190 unsigned NumArgs = TemplateArgs.size();
2191 bool Invalid = false;
2193 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2195 bool HasParameterPack =
2196 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
2198 if ((NumArgs > NumParams && !HasParameterPack) ||
2199 (NumArgs < Params->getMinRequiredArguments() &&
2200 !PartialTemplateArgs)) {
2201 // FIXME: point at either the first arg beyond what we can handle,
2202 // or the '>', depending on whether we have too many or too few
2203 // arguments.
2204 SourceRange Range;
2205 if (NumArgs > NumParams)
2206 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
2207 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2208 << (NumArgs > NumParams)
2209 << (isa<ClassTemplateDecl>(Template)? 0 :
2210 isa<FunctionTemplateDecl>(Template)? 1 :
2211 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2212 << Template << Range;
2213 Diag(Template->getLocation(), diag::note_template_decl_here)
2214 << Params->getSourceRange();
2215 Invalid = true;
2218 // C++ [temp.arg]p1:
2219 // [...] The type and form of each template-argument specified in
2220 // a template-id shall match the type and form specified for the
2221 // corresponding parameter declared by the template in its
2222 // template-parameter-list.
2223 unsigned ArgIdx = 0;
2224 for (TemplateParameterList::iterator Param = Params->begin(),
2225 ParamEnd = Params->end();
2226 Param != ParamEnd; ++Param, ++ArgIdx) {
2227 if (ArgIdx > NumArgs && PartialTemplateArgs)
2228 break;
2230 // If we have a template parameter pack, check every remaining template
2231 // argument against that template parameter pack.
2232 if ((*Param)->isTemplateParameterPack()) {
2233 Converted.BeginPack();
2234 for (; ArgIdx < NumArgs; ++ArgIdx) {
2235 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2236 TemplateLoc, RAngleLoc, Converted)) {
2237 Invalid = true;
2238 break;
2241 Converted.EndPack();
2242 continue;
2245 if (ArgIdx < NumArgs) {
2246 // Check the template argument we were given.
2247 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2248 TemplateLoc, RAngleLoc, Converted))
2249 return true;
2251 continue;
2254 // We have a default template argument that we will use.
2255 TemplateArgumentLoc Arg;
2257 // Retrieve the default template argument from the template
2258 // parameter. For each kind of template parameter, we substitute the
2259 // template arguments provided thus far and any "outer" template arguments
2260 // (when the template parameter was part of a nested template) into
2261 // the default argument.
2262 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2263 if (!TTP->hasDefaultArgument()) {
2264 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2265 break;
2268 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
2269 Template,
2270 TemplateLoc,
2271 RAngleLoc,
2272 TTP,
2273 Converted);
2274 if (!ArgType)
2275 return true;
2277 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2278 ArgType);
2279 } else if (NonTypeTemplateParmDecl *NTTP
2280 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2281 if (!NTTP->hasDefaultArgument()) {
2282 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2283 break;
2286 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
2287 TemplateLoc,
2288 RAngleLoc,
2289 NTTP,
2290 Converted);
2291 if (E.isInvalid())
2292 return true;
2294 Expr *Ex = E.takeAs<Expr>();
2295 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2296 } else {
2297 TemplateTemplateParmDecl *TempParm
2298 = cast<TemplateTemplateParmDecl>(*Param);
2300 if (!TempParm->hasDefaultArgument()) {
2301 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2302 break;
2305 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2306 TemplateLoc,
2307 RAngleLoc,
2308 TempParm,
2309 Converted);
2310 if (Name.isNull())
2311 return true;
2313 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2314 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2315 TempParm->getDefaultArgument().getTemplateNameLoc());
2318 // Introduce an instantiation record that describes where we are using
2319 // the default template argument.
2320 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2321 Converted.getFlatArguments(),
2322 Converted.flatSize(),
2323 SourceRange(TemplateLoc, RAngleLoc));
2325 // Check the default template argument.
2326 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
2327 RAngleLoc, Converted))
2328 return true;
2331 return Invalid;
2334 /// \brief Check a template argument against its corresponding
2335 /// template type parameter.
2337 /// This routine implements the semantics of C++ [temp.arg.type]. It
2338 /// returns true if an error occurred, and false otherwise.
2339 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
2340 TypeSourceInfo *ArgInfo) {
2341 assert(ArgInfo && "invalid TypeSourceInfo");
2342 QualType Arg = ArgInfo->getType();
2344 // C++ [temp.arg.type]p2:
2345 // A local type, a type with no linkage, an unnamed type or a type
2346 // compounded from any of these types shall not be used as a
2347 // template-argument for a template type-parameter.
2349 // FIXME: Perform the unnamed type check.
2350 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
2351 const TagType *Tag = 0;
2352 if (const EnumType *EnumT = Arg->getAs<EnumType>())
2353 Tag = EnumT;
2354 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
2355 Tag = RecordT;
2356 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2357 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
2358 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2359 << QualType(Tag, 0) << SR;
2360 } else if (Tag && !Tag->getDecl()->getDeclName() &&
2361 !Tag->getDecl()->getTypedefForAnonDecl()) {
2362 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
2363 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2364 return true;
2365 } else if (Arg->isVariablyModifiedType()) {
2366 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2367 << Arg;
2368 return true;
2369 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2370 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
2373 return false;
2376 /// \brief Checks whether the given template argument is the address
2377 /// of an object or function according to C++ [temp.arg.nontype]p1.
2378 static bool
2379 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2380 NonTypeTemplateParmDecl *Param,
2381 QualType ParamType,
2382 Expr *ArgIn,
2383 TemplateArgument &Converted) {
2384 bool Invalid = false;
2385 Expr *Arg = ArgIn;
2386 QualType ArgType = Arg->getType();
2388 // See through any implicit casts we added to fix the type.
2389 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2390 Arg = Cast->getSubExpr();
2392 // C++ [temp.arg.nontype]p1:
2394 // A template-argument for a non-type, non-template
2395 // template-parameter shall be one of: [...]
2397 // -- the address of an object or function with external
2398 // linkage, including function templates and function
2399 // template-ids but excluding non-static class members,
2400 // expressed as & id-expression where the & is optional if
2401 // the name refers to a function or array, or if the
2402 // corresponding template-parameter is a reference; or
2403 DeclRefExpr *DRE = 0;
2405 // Ignore (and complain about) any excess parentheses.
2406 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2407 if (!Invalid) {
2408 S.Diag(Arg->getSourceRange().getBegin(),
2409 diag::err_template_arg_extra_parens)
2410 << Arg->getSourceRange();
2411 Invalid = true;
2414 Arg = Parens->getSubExpr();
2417 bool AddressTaken = false;
2418 SourceLocation AddrOpLoc;
2419 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2420 if (UnOp->getOpcode() == UO_AddrOf) {
2421 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2422 AddressTaken = true;
2423 AddrOpLoc = UnOp->getOperatorLoc();
2425 } else
2426 DRE = dyn_cast<DeclRefExpr>(Arg);
2428 if (!DRE) {
2429 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2430 << Arg->getSourceRange();
2431 S.Diag(Param->getLocation(), diag::note_template_param_here);
2432 return true;
2435 // Stop checking the precise nature of the argument if it is value dependent,
2436 // it should be checked when instantiated.
2437 if (Arg->isValueDependent()) {
2438 Converted = TemplateArgument(ArgIn->Retain());
2439 return false;
2442 if (!isa<ValueDecl>(DRE->getDecl())) {
2443 S.Diag(Arg->getSourceRange().getBegin(),
2444 diag::err_template_arg_not_object_or_func_form)
2445 << Arg->getSourceRange();
2446 S.Diag(Param->getLocation(), diag::note_template_param_here);
2447 return true;
2450 NamedDecl *Entity = 0;
2452 // Cannot refer to non-static data members
2453 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2454 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2455 << Field << Arg->getSourceRange();
2456 S.Diag(Param->getLocation(), diag::note_template_param_here);
2457 return true;
2460 // Cannot refer to non-static member functions
2461 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2462 if (!Method->isStatic()) {
2463 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
2464 << Method << Arg->getSourceRange();
2465 S.Diag(Param->getLocation(), diag::note_template_param_here);
2466 return true;
2469 // Functions must have external linkage.
2470 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2471 if (!isExternalLinkage(Func->getLinkage())) {
2472 S.Diag(Arg->getSourceRange().getBegin(),
2473 diag::err_template_arg_function_not_extern)
2474 << Func << Arg->getSourceRange();
2475 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2476 << true;
2477 return true;
2480 // Okay: we've named a function with external linkage.
2481 Entity = Func;
2483 // If the template parameter has pointer type, the function decays.
2484 if (ParamType->isPointerType() && !AddressTaken)
2485 ArgType = S.Context.getPointerType(Func->getType());
2486 else if (AddressTaken && ParamType->isReferenceType()) {
2487 // If we originally had an address-of operator, but the
2488 // parameter has reference type, complain and (if things look
2489 // like they will work) drop the address-of operator.
2490 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2491 ParamType.getNonReferenceType())) {
2492 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2493 << ParamType;
2494 S.Diag(Param->getLocation(), diag::note_template_param_here);
2495 return true;
2498 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2499 << ParamType
2500 << FixItHint::CreateRemoval(AddrOpLoc);
2501 S.Diag(Param->getLocation(), diag::note_template_param_here);
2503 ArgType = Func->getType();
2505 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2506 if (!isExternalLinkage(Var->getLinkage())) {
2507 S.Diag(Arg->getSourceRange().getBegin(),
2508 diag::err_template_arg_object_not_extern)
2509 << Var << Arg->getSourceRange();
2510 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2511 << true;
2512 return true;
2515 // A value of reference type is not an object.
2516 if (Var->getType()->isReferenceType()) {
2517 S.Diag(Arg->getSourceRange().getBegin(),
2518 diag::err_template_arg_reference_var)
2519 << Var->getType() << Arg->getSourceRange();
2520 S.Diag(Param->getLocation(), diag::note_template_param_here);
2521 return true;
2524 // Okay: we've named an object with external linkage
2525 Entity = Var;
2527 // If the template parameter has pointer type, we must have taken
2528 // the address of this object.
2529 if (ParamType->isReferenceType()) {
2530 if (AddressTaken) {
2531 // If we originally had an address-of operator, but the
2532 // parameter has reference type, complain and (if things look
2533 // like they will work) drop the address-of operator.
2534 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2535 ParamType.getNonReferenceType())) {
2536 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2537 << ParamType;
2538 S.Diag(Param->getLocation(), diag::note_template_param_here);
2539 return true;
2542 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2543 << ParamType
2544 << FixItHint::CreateRemoval(AddrOpLoc);
2545 S.Diag(Param->getLocation(), diag::note_template_param_here);
2547 ArgType = Var->getType();
2549 } else if (!AddressTaken && ParamType->isPointerType()) {
2550 if (Var->getType()->isArrayType()) {
2551 // Array-to-pointer decay.
2552 ArgType = S.Context.getArrayDecayedType(Var->getType());
2553 } else {
2554 // If the template parameter has pointer type but the address of
2555 // this object was not taken, complain and (possibly) recover by
2556 // taking the address of the entity.
2557 ArgType = S.Context.getPointerType(Var->getType());
2558 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2559 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2560 << ParamType;
2561 S.Diag(Param->getLocation(), diag::note_template_param_here);
2562 return true;
2565 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2566 << ParamType
2567 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2569 S.Diag(Param->getLocation(), diag::note_template_param_here);
2572 } else {
2573 // We found something else, but we don't know specifically what it is.
2574 S.Diag(Arg->getSourceRange().getBegin(),
2575 diag::err_template_arg_not_object_or_func)
2576 << Arg->getSourceRange();
2577 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2578 return true;
2581 if (ParamType->isPointerType() &&
2582 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2583 S.IsQualificationConversion(ArgType, ParamType)) {
2584 // For pointer-to-object types, qualification conversions are
2585 // permitted.
2586 } else {
2587 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2588 if (!ParamRef->getPointeeType()->isFunctionType()) {
2589 // C++ [temp.arg.nontype]p5b3:
2590 // For a non-type template-parameter of type reference to
2591 // object, no conversions apply. The type referred to by the
2592 // reference may be more cv-qualified than the (otherwise
2593 // identical) type of the template- argument. The
2594 // template-parameter is bound directly to the
2595 // template-argument, which shall be an lvalue.
2597 // FIXME: Other qualifiers?
2598 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2599 unsigned ArgQuals = ArgType.getCVRQualifiers();
2601 if ((ParamQuals | ArgQuals) != ParamQuals) {
2602 S.Diag(Arg->getSourceRange().getBegin(),
2603 diag::err_template_arg_ref_bind_ignores_quals)
2604 << ParamType << Arg->getType()
2605 << Arg->getSourceRange();
2606 S.Diag(Param->getLocation(), diag::note_template_param_here);
2607 return true;
2612 // At this point, the template argument refers to an object or
2613 // function with external linkage. We now need to check whether the
2614 // argument and parameter types are compatible.
2615 if (!S.Context.hasSameUnqualifiedType(ArgType,
2616 ParamType.getNonReferenceType())) {
2617 // We can't perform this conversion or binding.
2618 if (ParamType->isReferenceType())
2619 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2620 << ParamType << Arg->getType() << Arg->getSourceRange();
2621 else
2622 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2623 << Arg->getType() << ParamType << Arg->getSourceRange();
2624 S.Diag(Param->getLocation(), diag::note_template_param_here);
2625 return true;
2629 // Create the template argument.
2630 Converted = TemplateArgument(Entity->getCanonicalDecl());
2631 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
2632 return false;
2635 /// \brief Checks whether the given template argument is a pointer to
2636 /// member constant according to C++ [temp.arg.nontype]p1.
2637 bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2638 TemplateArgument &Converted) {
2639 bool Invalid = false;
2641 // See through any implicit casts we added to fix the type.
2642 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2643 Arg = Cast->getSubExpr();
2645 // C++ [temp.arg.nontype]p1:
2647 // A template-argument for a non-type, non-template
2648 // template-parameter shall be one of: [...]
2650 // -- a pointer to member expressed as described in 5.3.1.
2651 DeclRefExpr *DRE = 0;
2653 // Ignore (and complain about) any excess parentheses.
2654 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2655 if (!Invalid) {
2656 Diag(Arg->getSourceRange().getBegin(),
2657 diag::err_template_arg_extra_parens)
2658 << Arg->getSourceRange();
2659 Invalid = true;
2662 Arg = Parens->getSubExpr();
2665 // A pointer-to-member constant written &Class::member.
2666 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2667 if (UnOp->getOpcode() == UO_AddrOf) {
2668 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2669 if (DRE && !DRE->getQualifier())
2670 DRE = 0;
2673 // A constant of pointer-to-member type.
2674 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2675 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2676 if (VD->getType()->isMemberPointerType()) {
2677 if (isa<NonTypeTemplateParmDecl>(VD) ||
2678 (isa<VarDecl>(VD) &&
2679 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2680 if (Arg->isTypeDependent() || Arg->isValueDependent())
2681 Converted = TemplateArgument(Arg->Retain());
2682 else
2683 Converted = TemplateArgument(VD->getCanonicalDecl());
2684 return Invalid;
2689 DRE = 0;
2692 if (!DRE)
2693 return Diag(Arg->getSourceRange().getBegin(),
2694 diag::err_template_arg_not_pointer_to_member_form)
2695 << Arg->getSourceRange();
2697 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2698 assert((isa<FieldDecl>(DRE->getDecl()) ||
2699 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2700 "Only non-static member pointers can make it here");
2702 // Okay: this is the address of a non-static member, and therefore
2703 // a member pointer constant.
2704 if (Arg->isTypeDependent() || Arg->isValueDependent())
2705 Converted = TemplateArgument(Arg->Retain());
2706 else
2707 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
2708 return Invalid;
2711 // We found something else, but we don't know specifically what it is.
2712 Diag(Arg->getSourceRange().getBegin(),
2713 diag::err_template_arg_not_pointer_to_member_form)
2714 << Arg->getSourceRange();
2715 Diag(DRE->getDecl()->getLocation(),
2716 diag::note_template_arg_refers_here);
2717 return true;
2720 /// \brief Check a template argument against its corresponding
2721 /// non-type template parameter.
2723 /// This routine implements the semantics of C++ [temp.arg.nontype].
2724 /// It returns true if an error occurred, and false otherwise. \p
2725 /// InstantiatedParamType is the type of the non-type template
2726 /// parameter after it has been instantiated.
2728 /// If no error was detected, Converted receives the converted template argument.
2729 bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
2730 QualType InstantiatedParamType, Expr *&Arg,
2731 TemplateArgument &Converted,
2732 CheckTemplateArgumentKind CTAK) {
2733 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2735 // If either the parameter has a dependent type or the argument is
2736 // type-dependent, there's nothing we can check now.
2737 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2738 // FIXME: Produce a cloned, canonical expression?
2739 Converted = TemplateArgument(Arg);
2740 return false;
2743 // C++ [temp.arg.nontype]p5:
2744 // The following conversions are performed on each expression used
2745 // as a non-type template-argument. If a non-type
2746 // template-argument cannot be converted to the type of the
2747 // corresponding template-parameter then the program is
2748 // ill-formed.
2750 // -- for a non-type template-parameter of integral or
2751 // enumeration type, integral promotions (4.5) and integral
2752 // conversions (4.7) are applied.
2753 QualType ParamType = InstantiatedParamType;
2754 QualType ArgType = Arg->getType();
2755 if (ParamType->isIntegralOrEnumerationType()) {
2756 // C++ [temp.arg.nontype]p1:
2757 // A template-argument for a non-type, non-template
2758 // template-parameter shall be one of:
2760 // -- an integral constant-expression of integral or enumeration
2761 // type; or
2762 // -- the name of a non-type template-parameter; or
2763 SourceLocation NonConstantLoc;
2764 llvm::APSInt Value;
2765 if (!ArgType->isIntegralOrEnumerationType()) {
2766 Diag(Arg->getSourceRange().getBegin(),
2767 diag::err_template_arg_not_integral_or_enumeral)
2768 << ArgType << Arg->getSourceRange();
2769 Diag(Param->getLocation(), diag::note_template_param_here);
2770 return true;
2771 } else if (!Arg->isValueDependent() &&
2772 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
2773 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2774 << ArgType << Arg->getSourceRange();
2775 return true;
2778 // From here on out, all we care about are the unqualified forms
2779 // of the parameter and argument types.
2780 ParamType = ParamType.getUnqualifiedType();
2781 ArgType = ArgType.getUnqualifiedType();
2783 // Try to convert the argument to the parameter's type.
2784 if (Context.hasSameType(ParamType, ArgType)) {
2785 // Okay: no conversion necessary
2786 } else if (CTAK == CTAK_Deduced) {
2787 // C++ [temp.deduct.type]p17:
2788 // If, in the declaration of a function template with a non-type
2789 // template-parameter, the non-type template- parameter is used
2790 // in an expression in the function parameter-list and, if the
2791 // corresponding template-argument is deduced, the
2792 // template-argument type shall match the type of the
2793 // template-parameter exactly, except that a template-argument
2794 // deduced from an array bound may be of any integral type.
2795 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2796 << ArgType << ParamType;
2797 Diag(Param->getLocation(), diag::note_template_param_here);
2798 return true;
2799 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2800 !ParamType->isEnumeralType()) {
2801 // This is an integral promotion or conversion.
2802 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
2803 } else {
2804 // We can't perform this conversion.
2805 Diag(Arg->getSourceRange().getBegin(),
2806 diag::err_template_arg_not_convertible)
2807 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2808 Diag(Param->getLocation(), diag::note_template_param_here);
2809 return true;
2812 QualType IntegerType = Context.getCanonicalType(ParamType);
2813 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
2814 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
2816 if (!Arg->isValueDependent()) {
2817 llvm::APSInt OldValue = Value;
2819 // Coerce the template argument's value to the value it will have
2820 // based on the template parameter's type.
2821 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2822 if (Value.getBitWidth() != AllowedBits)
2823 Value.extOrTrunc(AllowedBits);
2824 Value.setIsSigned(IntegerType->isSignedIntegerType());
2826 // Complain if an unsigned parameter received a negative value.
2827 if (IntegerType->isUnsignedIntegerType()
2828 && (OldValue.isSigned() && OldValue.isNegative())) {
2829 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2830 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2831 << Arg->getSourceRange();
2832 Diag(Param->getLocation(), diag::note_template_param_here);
2835 // Complain if we overflowed the template parameter's type.
2836 unsigned RequiredBits;
2837 if (IntegerType->isUnsignedIntegerType())
2838 RequiredBits = OldValue.getActiveBits();
2839 else if (OldValue.isUnsigned())
2840 RequiredBits = OldValue.getActiveBits() + 1;
2841 else
2842 RequiredBits = OldValue.getMinSignedBits();
2843 if (RequiredBits > AllowedBits) {
2844 Diag(Arg->getSourceRange().getBegin(),
2845 diag::warn_template_arg_too_large)
2846 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2847 << Arg->getSourceRange();
2848 Diag(Param->getLocation(), diag::note_template_param_here);
2852 // Add the value of this argument to the list of converted
2853 // arguments. We use the bitwidth and signedness of the template
2854 // parameter.
2855 if (Arg->isValueDependent()) {
2856 // The argument is value-dependent. Create a new
2857 // TemplateArgument with the converted expression.
2858 Converted = TemplateArgument(Arg);
2859 return false;
2862 Converted = TemplateArgument(Value,
2863 ParamType->isEnumeralType() ? ParamType
2864 : IntegerType);
2865 return false;
2868 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2870 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2871 // from a template argument of type std::nullptr_t to a non-type
2872 // template parameter of type pointer to object, pointer to
2873 // function, or pointer-to-member, respectively.
2874 if (ArgType->isNullPtrType() &&
2875 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2876 Converted = TemplateArgument((NamedDecl *)0);
2877 return false;
2880 // Handle pointer-to-function, reference-to-function, and
2881 // pointer-to-member-function all in (roughly) the same way.
2882 if (// -- For a non-type template-parameter of type pointer to
2883 // function, only the function-to-pointer conversion (4.3) is
2884 // applied. If the template-argument represents a set of
2885 // overloaded functions (or a pointer to such), the matching
2886 // function is selected from the set (13.4).
2887 (ParamType->isPointerType() &&
2888 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
2889 // -- For a non-type template-parameter of type reference to
2890 // function, no conversions apply. If the template-argument
2891 // represents a set of overloaded functions, the matching
2892 // function is selected from the set (13.4).
2893 (ParamType->isReferenceType() &&
2894 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
2895 // -- For a non-type template-parameter of type pointer to
2896 // member function, no conversions apply. If the
2897 // template-argument represents a set of overloaded member
2898 // functions, the matching member function is selected from
2899 // the set (13.4).
2900 (ParamType->isMemberPointerType() &&
2901 ParamType->getAs<MemberPointerType>()->getPointeeType()
2902 ->isFunctionType())) {
2904 if (Arg->getType() == Context.OverloadTy) {
2905 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2906 true,
2907 FoundResult)) {
2908 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2909 return true;
2911 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2912 ArgType = Arg->getType();
2913 } else
2914 return true;
2917 if (!ParamType->isMemberPointerType())
2918 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2919 ParamType,
2920 Arg, Converted);
2922 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2923 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
2924 } else if (!Context.hasSameUnqualifiedType(ArgType,
2925 ParamType.getNonReferenceType())) {
2926 // We can't perform this conversion.
2927 Diag(Arg->getSourceRange().getBegin(),
2928 diag::err_template_arg_not_convertible)
2929 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2930 Diag(Param->getLocation(), diag::note_template_param_here);
2931 return true;
2934 return CheckTemplateArgumentPointerToMember(Arg, Converted);
2937 if (ParamType->isPointerType()) {
2938 // -- for a non-type template-parameter of type pointer to
2939 // object, qualification conversions (4.4) and the
2940 // array-to-pointer conversion (4.2) are applied.
2941 // C++0x also allows a value of std::nullptr_t.
2942 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
2943 "Only object pointers allowed here");
2945 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2946 ParamType,
2947 Arg, Converted);
2950 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
2951 // -- For a non-type template-parameter of type reference to
2952 // object, no conversions apply. The type referred to by the
2953 // reference may be more cv-qualified than the (otherwise
2954 // identical) type of the template-argument. The
2955 // template-parameter is bound directly to the
2956 // template-argument, which must be an lvalue.
2957 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
2958 "Only object references allowed here");
2960 if (Arg->getType() == Context.OverloadTy) {
2961 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2962 ParamRefType->getPointeeType(),
2963 true,
2964 FoundResult)) {
2965 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2966 return true;
2968 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2969 ArgType = Arg->getType();
2970 } else
2971 return true;
2974 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2975 ParamType,
2976 Arg, Converted);
2979 // -- For a non-type template-parameter of type pointer to data
2980 // member, qualification conversions (4.4) are applied.
2981 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
2983 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
2984 // Types match exactly: nothing more to do here.
2985 } else if (IsQualificationConversion(ArgType, ParamType)) {
2986 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
2987 } else {
2988 // We can't perform this conversion.
2989 Diag(Arg->getSourceRange().getBegin(),
2990 diag::err_template_arg_not_convertible)
2991 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2992 Diag(Param->getLocation(), diag::note_template_param_here);
2993 return true;
2996 return CheckTemplateArgumentPointerToMember(Arg, Converted);
2999 /// \brief Check a template argument against its corresponding
3000 /// template template parameter.
3002 /// This routine implements the semantics of C++ [temp.arg.template].
3003 /// It returns true if an error occurred, and false otherwise.
3004 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
3005 const TemplateArgumentLoc &Arg) {
3006 TemplateName Name = Arg.getArgument().getAsTemplate();
3007 TemplateDecl *Template = Name.getAsTemplateDecl();
3008 if (!Template) {
3009 // Any dependent template name is fine.
3010 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3011 return false;
3014 // C++ [temp.arg.template]p1:
3015 // A template-argument for a template template-parameter shall be
3016 // the name of a class template, expressed as id-expression. Only
3017 // primary class templates are considered when matching the
3018 // template template argument with the corresponding parameter;
3019 // partial specializations are not considered even if their
3020 // parameter lists match that of the template template parameter.
3022 // Note that we also allow template template parameters here, which
3023 // will happen when we are dealing with, e.g., class template
3024 // partial specializations.
3025 if (!isa<ClassTemplateDecl>(Template) &&
3026 !isa<TemplateTemplateParmDecl>(Template)) {
3027 assert(isa<FunctionTemplateDecl>(Template) &&
3028 "Only function templates are possible here");
3029 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
3030 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
3031 << Template;
3034 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3035 Param->getTemplateParameters(),
3036 true,
3037 TPL_TemplateTemplateArgumentMatch,
3038 Arg.getLocation());
3041 /// \brief Given a non-type template argument that refers to a
3042 /// declaration and the type of its corresponding non-type template
3043 /// parameter, produce an expression that properly refers to that
3044 /// declaration.
3045 ExprResult
3046 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3047 QualType ParamType,
3048 SourceLocation Loc) {
3049 assert(Arg.getKind() == TemplateArgument::Declaration &&
3050 "Only declaration template arguments permitted here");
3051 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3053 if (VD->getDeclContext()->isRecord() &&
3054 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3055 // If the value is a class member, we might have a pointer-to-member.
3056 // Determine whether the non-type template template parameter is of
3057 // pointer-to-member type. If so, we need to build an appropriate
3058 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3059 // would refer to the member itself.
3060 if (ParamType->isMemberPointerType()) {
3061 QualType ClassType
3062 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3063 NestedNameSpecifier *Qualifier
3064 = NestedNameSpecifier::Create(Context, 0, false,
3065 ClassType.getTypePtr());
3066 CXXScopeSpec SS;
3067 SS.setScopeRep(Qualifier);
3068 ExprResult RefExpr = BuildDeclRefExpr(VD,
3069 VD->getType().getNonReferenceType(),
3070 Loc,
3071 &SS);
3072 if (RefExpr.isInvalid())
3073 return ExprError();
3075 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
3077 // We might need to perform a trailing qualification conversion, since
3078 // the element type on the parameter could be more qualified than the
3079 // element type in the expression we constructed.
3080 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3081 ParamType.getUnqualifiedType())) {
3082 Expr *RefE = RefExpr.takeAs<Expr>();
3083 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
3084 RefExpr = Owned(RefE);
3087 assert(!RefExpr.isInvalid() &&
3088 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
3089 ParamType.getUnqualifiedType()));
3090 return move(RefExpr);
3094 QualType T = VD->getType().getNonReferenceType();
3095 if (ParamType->isPointerType()) {
3096 // When the non-type template parameter is a pointer, take the
3097 // address of the declaration.
3098 ExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3099 if (RefExpr.isInvalid())
3100 return ExprError();
3102 if (T->isFunctionType() || T->isArrayType()) {
3103 // Decay functions and arrays.
3104 Expr *RefE = (Expr *)RefExpr.get();
3105 DefaultFunctionArrayConversion(RefE);
3106 if (RefE != RefExpr.get()) {
3107 RefExpr.release();
3108 RefExpr = Owned(RefE);
3111 return move(RefExpr);
3114 // Take the address of everything else
3115 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
3118 // If the non-type template parameter has reference type, qualify the
3119 // resulting declaration reference with the extra qualifiers on the
3120 // type that the reference refers to.
3121 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3122 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3124 return BuildDeclRefExpr(VD, T, Loc);
3127 /// \brief Construct a new expression that refers to the given
3128 /// integral template argument with the given source-location
3129 /// information.
3131 /// This routine takes care of the mapping from an integral template
3132 /// argument (which may have any integral type) to the appropriate
3133 /// literal value.
3134 ExprResult
3135 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3136 SourceLocation Loc) {
3137 assert(Arg.getKind() == TemplateArgument::Integral &&
3138 "Operation is only value for integral template arguments");
3139 QualType T = Arg.getIntegralType();
3140 if (T->isCharType() || T->isWideCharType())
3141 return Owned(new (Context) CharacterLiteral(
3142 Arg.getAsIntegral()->getZExtValue(),
3143 T->isWideCharType(),
3145 Loc));
3146 if (T->isBooleanType())
3147 return Owned(new (Context) CXXBoolLiteralExpr(
3148 Arg.getAsIntegral()->getBoolValue(),
3150 Loc));
3152 return Owned(IntegerLiteral::Create(Context, *Arg.getAsIntegral(), T, Loc));
3156 /// \brief Determine whether the given template parameter lists are
3157 /// equivalent.
3159 /// \param New The new template parameter list, typically written in the
3160 /// source code as part of a new template declaration.
3162 /// \param Old The old template parameter list, typically found via
3163 /// name lookup of the template declared with this template parameter
3164 /// list.
3166 /// \param Complain If true, this routine will produce a diagnostic if
3167 /// the template parameter lists are not equivalent.
3169 /// \param Kind describes how we are to match the template parameter lists.
3171 /// \param TemplateArgLoc If this source location is valid, then we
3172 /// are actually checking the template parameter list of a template
3173 /// argument (New) against the template parameter list of its
3174 /// corresponding template template parameter (Old). We produce
3175 /// slightly different diagnostics in this scenario.
3177 /// \returns True if the template parameter lists are equal, false
3178 /// otherwise.
3179 bool
3180 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3181 TemplateParameterList *Old,
3182 bool Complain,
3183 TemplateParameterListEqualKind Kind,
3184 SourceLocation TemplateArgLoc) {
3185 if (Old->size() != New->size()) {
3186 if (Complain) {
3187 unsigned NextDiag = diag::err_template_param_list_different_arity;
3188 if (TemplateArgLoc.isValid()) {
3189 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3190 NextDiag = diag::note_template_param_list_different_arity;
3192 Diag(New->getTemplateLoc(), NextDiag)
3193 << (New->size() > Old->size())
3194 << (Kind != TPL_TemplateMatch)
3195 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
3196 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
3197 << (Kind != TPL_TemplateMatch)
3198 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3201 return false;
3204 for (TemplateParameterList::iterator OldParm = Old->begin(),
3205 OldParmEnd = Old->end(), NewParm = New->begin();
3206 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3207 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
3208 if (Complain) {
3209 unsigned NextDiag = diag::err_template_param_different_kind;
3210 if (TemplateArgLoc.isValid()) {
3211 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3212 NextDiag = diag::note_template_param_different_kind;
3214 Diag((*NewParm)->getLocation(), NextDiag)
3215 << (Kind != TPL_TemplateMatch);
3216 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
3217 << (Kind != TPL_TemplateMatch);
3219 return false;
3222 if (TemplateTypeParmDecl *OldTTP
3223 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3224 // Template type parameters are equivalent if either both are template
3225 // type parameter packs or neither are (since we know we're at the same
3226 // index).
3227 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3228 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3229 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3230 // allow one to match a template parameter pack in the template
3231 // parameter list of a template template parameter to one or more
3232 // template parameters in the template parameter list of the
3233 // corresponding template template argument.
3234 if (Complain) {
3235 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3236 if (TemplateArgLoc.isValid()) {
3237 Diag(TemplateArgLoc,
3238 diag::err_template_arg_template_params_mismatch);
3239 NextDiag = diag::note_template_parameter_pack_non_pack;
3241 Diag(NewTTP->getLocation(), NextDiag)
3242 << 0 << NewTTP->isParameterPack();
3243 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3244 << 0 << OldTTP->isParameterPack();
3246 return false;
3248 } else if (NonTypeTemplateParmDecl *OldNTTP
3249 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3250 // The types of non-type template parameters must agree.
3251 NonTypeTemplateParmDecl *NewNTTP
3252 = cast<NonTypeTemplateParmDecl>(*NewParm);
3254 // If we are matching a template template argument to a template
3255 // template parameter and one of the non-type template parameter types
3256 // is dependent, then we must wait until template instantiation time
3257 // to actually compare the arguments.
3258 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3259 (OldNTTP->getType()->isDependentType() ||
3260 NewNTTP->getType()->isDependentType()))
3261 continue;
3263 if (Context.getCanonicalType(OldNTTP->getType()) !=
3264 Context.getCanonicalType(NewNTTP->getType())) {
3265 if (Complain) {
3266 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3267 if (TemplateArgLoc.isValid()) {
3268 Diag(TemplateArgLoc,
3269 diag::err_template_arg_template_params_mismatch);
3270 NextDiag = diag::note_template_nontype_parm_different_type;
3272 Diag(NewNTTP->getLocation(), NextDiag)
3273 << NewNTTP->getType()
3274 << (Kind != TPL_TemplateMatch);
3275 Diag(OldNTTP->getLocation(),
3276 diag::note_template_nontype_parm_prev_declaration)
3277 << OldNTTP->getType();
3279 return false;
3281 } else {
3282 // The template parameter lists of template template
3283 // parameters must agree.
3284 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
3285 "Only template template parameters handled here");
3286 TemplateTemplateParmDecl *OldTTP
3287 = cast<TemplateTemplateParmDecl>(*OldParm);
3288 TemplateTemplateParmDecl *NewTTP
3289 = cast<TemplateTemplateParmDecl>(*NewParm);
3290 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3291 OldTTP->getTemplateParameters(),
3292 Complain,
3293 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
3294 TemplateArgLoc))
3295 return false;
3299 return true;
3302 /// \brief Check whether a template can be declared within this scope.
3304 /// If the template declaration is valid in this scope, returns
3305 /// false. Otherwise, issues a diagnostic and returns true.
3306 bool
3307 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
3308 // Find the nearest enclosing declaration scope.
3309 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3310 (S->getFlags() & Scope::TemplateParamScope) != 0)
3311 S = S->getParent();
3313 // C++ [temp]p2:
3314 // A template-declaration can appear only as a namespace scope or
3315 // class scope declaration.
3316 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
3317 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3318 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
3319 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
3320 << TemplateParams->getSourceRange();
3322 while (Ctx && isa<LinkageSpecDecl>(Ctx))
3323 Ctx = Ctx->getParent();
3325 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3326 return false;
3328 return Diag(TemplateParams->getTemplateLoc(),
3329 diag::err_template_outside_namespace_or_class_scope)
3330 << TemplateParams->getSourceRange();
3333 /// \brief Determine what kind of template specialization the given declaration
3334 /// is.
3335 static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3336 if (!D)
3337 return TSK_Undeclared;
3339 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3340 return Record->getTemplateSpecializationKind();
3341 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3342 return Function->getTemplateSpecializationKind();
3343 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3344 return Var->getTemplateSpecializationKind();
3346 return TSK_Undeclared;
3349 /// \brief Check whether a specialization is well-formed in the current
3350 /// context.
3352 /// This routine determines whether a template specialization can be declared
3353 /// in the current context (C++ [temp.expl.spec]p2).
3355 /// \param S the semantic analysis object for which this check is being
3356 /// performed.
3358 /// \param Specialized the entity being specialized or instantiated, which
3359 /// may be a kind of template (class template, function template, etc.) or
3360 /// a member of a class template (member function, static data member,
3361 /// member class).
3363 /// \param PrevDecl the previous declaration of this entity, if any.
3365 /// \param Loc the location of the explicit specialization or instantiation of
3366 /// this entity.
3368 /// \param IsPartialSpecialization whether this is a partial specialization of
3369 /// a class template.
3371 /// \returns true if there was an error that we cannot recover from, false
3372 /// otherwise.
3373 static bool CheckTemplateSpecializationScope(Sema &S,
3374 NamedDecl *Specialized,
3375 NamedDecl *PrevDecl,
3376 SourceLocation Loc,
3377 bool IsPartialSpecialization) {
3378 // Keep these "kind" numbers in sync with the %select statements in the
3379 // various diagnostics emitted by this routine.
3380 int EntityKind = 0;
3381 bool isTemplateSpecialization = false;
3382 if (isa<ClassTemplateDecl>(Specialized)) {
3383 EntityKind = IsPartialSpecialization? 1 : 0;
3384 isTemplateSpecialization = true;
3385 } else if (isa<FunctionTemplateDecl>(Specialized)) {
3386 EntityKind = 2;
3387 isTemplateSpecialization = true;
3388 } else if (isa<CXXMethodDecl>(Specialized))
3389 EntityKind = 3;
3390 else if (isa<VarDecl>(Specialized))
3391 EntityKind = 4;
3392 else if (isa<RecordDecl>(Specialized))
3393 EntityKind = 5;
3394 else {
3395 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3396 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3397 return true;
3400 // C++ [temp.expl.spec]p2:
3401 // An explicit specialization shall be declared in the namespace
3402 // of which the template is a member, or, for member templates, in
3403 // the namespace of which the enclosing class or enclosing class
3404 // template is a member. An explicit specialization of a member
3405 // function, member class or static data member of a class
3406 // template shall be declared in the namespace of which the class
3407 // template is a member. Such a declaration may also be a
3408 // definition. If the declaration is not a definition, the
3409 // specialization may be defined later in the name- space in which
3410 // the explicit specialization was declared, or in a namespace
3411 // that encloses the one in which the explicit specialization was
3412 // declared.
3413 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3414 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
3415 << Specialized;
3416 return true;
3419 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3420 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
3421 << Specialized;
3422 return true;
3425 // C++ [temp.class.spec]p6:
3426 // A class template partial specialization may be declared or redeclared
3427 // in any namespace scope in which its definition may be defined (14.5.1
3428 // and 14.5.2).
3429 bool ComplainedAboutScope = false;
3430 DeclContext *SpecializedContext
3431 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
3432 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
3433 if ((!PrevDecl ||
3434 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3435 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3436 // There is no prior declaration of this entity, so this
3437 // specialization must be in the same context as the template
3438 // itself.
3439 if (!DC->Equals(SpecializedContext)) {
3440 if (isa<TranslationUnitDecl>(SpecializedContext))
3441 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3442 << EntityKind << Specialized;
3443 else if (isa<NamespaceDecl>(SpecializedContext))
3444 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3445 << EntityKind << Specialized
3446 << cast<NamedDecl>(SpecializedContext);
3448 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3449 ComplainedAboutScope = true;
3453 // Make sure that this redeclaration (or definition) occurs in an enclosing
3454 // namespace.
3455 // Note that HandleDeclarator() performs this check for explicit
3456 // specializations of function templates, static data members, and member
3457 // functions, so we skip the check here for those kinds of entities.
3458 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
3459 // Should we refactor that check, so that it occurs later?
3460 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
3461 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3462 isa<FunctionDecl>(Specialized))) {
3463 if (isa<TranslationUnitDecl>(SpecializedContext))
3464 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3465 << EntityKind << Specialized;
3466 else if (isa<NamespaceDecl>(SpecializedContext))
3467 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3468 << EntityKind << Specialized
3469 << cast<NamedDecl>(SpecializedContext);
3471 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3474 // FIXME: check for specialization-after-instantiation errors and such.
3476 return false;
3479 /// \brief Check the non-type template arguments of a class template
3480 /// partial specialization according to C++ [temp.class.spec]p9.
3482 /// \param TemplateParams the template parameters of the primary class
3483 /// template.
3485 /// \param TemplateArg the template arguments of the class template
3486 /// partial specialization.
3488 /// \param MirrorsPrimaryTemplate will be set true if the class
3489 /// template partial specialization arguments are identical to the
3490 /// implicit template arguments of the primary template. This is not
3491 /// necessarily an error (C++0x), and it is left to the caller to diagnose
3492 /// this condition when it is an error.
3494 /// \returns true if there was an error, false otherwise.
3495 bool Sema::CheckClassTemplatePartialSpecializationArgs(
3496 TemplateParameterList *TemplateParams,
3497 const TemplateArgumentListBuilder &TemplateArgs,
3498 bool &MirrorsPrimaryTemplate) {
3499 // FIXME: the interface to this function will have to change to
3500 // accommodate variadic templates.
3501 MirrorsPrimaryTemplate = true;
3503 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
3505 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3506 // Determine whether the template argument list of the partial
3507 // specialization is identical to the implicit argument list of
3508 // the primary template. The caller may need to diagnostic this as
3509 // an error per C++ [temp.class.spec]p9b3.
3510 if (MirrorsPrimaryTemplate) {
3511 if (TemplateTypeParmDecl *TTP
3512 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3513 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
3514 Context.getCanonicalType(ArgList[I].getAsType()))
3515 MirrorsPrimaryTemplate = false;
3516 } else if (TemplateTemplateParmDecl *TTP
3517 = dyn_cast<TemplateTemplateParmDecl>(
3518 TemplateParams->getParam(I))) {
3519 TemplateName Name = ArgList[I].getAsTemplate();
3520 TemplateTemplateParmDecl *ArgDecl
3521 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
3522 if (!ArgDecl ||
3523 ArgDecl->getIndex() != TTP->getIndex() ||
3524 ArgDecl->getDepth() != TTP->getDepth())
3525 MirrorsPrimaryTemplate = false;
3529 NonTypeTemplateParmDecl *Param
3530 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
3531 if (!Param) {
3532 continue;
3535 Expr *ArgExpr = ArgList[I].getAsExpr();
3536 if (!ArgExpr) {
3537 MirrorsPrimaryTemplate = false;
3538 continue;
3541 // C++ [temp.class.spec]p8:
3542 // A non-type argument is non-specialized if it is the name of a
3543 // non-type parameter. All other non-type arguments are
3544 // specialized.
3546 // Below, we check the two conditions that only apply to
3547 // specialized non-type arguments, so skip any non-specialized
3548 // arguments.
3549 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
3550 if (NonTypeTemplateParmDecl *NTTP
3551 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
3552 if (MirrorsPrimaryTemplate &&
3553 (Param->getIndex() != NTTP->getIndex() ||
3554 Param->getDepth() != NTTP->getDepth()))
3555 MirrorsPrimaryTemplate = false;
3557 continue;
3560 // C++ [temp.class.spec]p9:
3561 // Within the argument list of a class template partial
3562 // specialization, the following restrictions apply:
3563 // -- A partially specialized non-type argument expression
3564 // shall not involve a template parameter of the partial
3565 // specialization except when the argument expression is a
3566 // simple identifier.
3567 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
3568 Diag(ArgExpr->getLocStart(),
3569 diag::err_dependent_non_type_arg_in_partial_spec)
3570 << ArgExpr->getSourceRange();
3571 return true;
3574 // -- The type of a template parameter corresponding to a
3575 // specialized non-type argument shall not be dependent on a
3576 // parameter of the specialization.
3577 if (Param->getType()->isDependentType()) {
3578 Diag(ArgExpr->getLocStart(),
3579 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3580 << Param->getType()
3581 << ArgExpr->getSourceRange();
3582 Diag(Param->getLocation(), diag::note_template_param_here);
3583 return true;
3586 MirrorsPrimaryTemplate = false;
3589 return false;
3592 /// \brief Retrieve the previous declaration of the given declaration.
3593 static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3594 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3595 return VD->getPreviousDeclaration();
3596 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3597 return FD->getPreviousDeclaration();
3598 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3599 return TD->getPreviousDeclaration();
3600 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3601 return TD->getPreviousDeclaration();
3602 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3603 return FTD->getPreviousDeclaration();
3604 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3605 return CTD->getPreviousDeclaration();
3606 return 0;
3609 DeclResult
3610 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3611 TagUseKind TUK,
3612 SourceLocation KWLoc,
3613 CXXScopeSpec &SS,
3614 TemplateTy TemplateD,
3615 SourceLocation TemplateNameLoc,
3616 SourceLocation LAngleLoc,
3617 ASTTemplateArgsPtr TemplateArgsIn,
3618 SourceLocation RAngleLoc,
3619 AttributeList *Attr,
3620 MultiTemplateParamsArg TemplateParameterLists) {
3621 assert(TUK != TUK_Reference && "References are not specializations");
3623 // Find the class template we're specializing
3624 TemplateName Name = TemplateD.getAsVal<TemplateName>();
3625 ClassTemplateDecl *ClassTemplate
3626 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3628 if (!ClassTemplate) {
3629 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3630 << (Name.getAsTemplateDecl() &&
3631 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3632 return true;
3635 bool isExplicitSpecialization = false;
3636 bool isPartialSpecialization = false;
3638 // Check the validity of the template headers that introduce this
3639 // template.
3640 // FIXME: We probably shouldn't complain about these headers for
3641 // friend declarations.
3642 bool Invalid = false;
3643 TemplateParameterList *TemplateParams
3644 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3645 (TemplateParameterList**)TemplateParameterLists.get(),
3646 TemplateParameterLists.size(),
3647 TUK == TUK_Friend,
3648 isExplicitSpecialization,
3649 Invalid);
3650 if (Invalid)
3651 return true;
3653 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3654 if (TemplateParams)
3655 --NumMatchedTemplateParamLists;
3657 if (TemplateParams && TemplateParams->size() > 0) {
3658 isPartialSpecialization = true;
3660 // C++ [temp.class.spec]p10:
3661 // The template parameter list of a specialization shall not
3662 // contain default template argument values.
3663 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3664 Decl *Param = TemplateParams->getParam(I);
3665 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3666 if (TTP->hasDefaultArgument()) {
3667 Diag(TTP->getDefaultArgumentLoc(),
3668 diag::err_default_arg_in_partial_spec);
3669 TTP->removeDefaultArgument();
3671 } else if (NonTypeTemplateParmDecl *NTTP
3672 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3673 if (Expr *DefArg = NTTP->getDefaultArgument()) {
3674 Diag(NTTP->getDefaultArgumentLoc(),
3675 diag::err_default_arg_in_partial_spec)
3676 << DefArg->getSourceRange();
3677 NTTP->removeDefaultArgument();
3679 } else {
3680 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
3681 if (TTP->hasDefaultArgument()) {
3682 Diag(TTP->getDefaultArgument().getLocation(),
3683 diag::err_default_arg_in_partial_spec)
3684 << TTP->getDefaultArgument().getSourceRange();
3685 TTP->removeDefaultArgument();
3689 } else if (TemplateParams) {
3690 if (TUK == TUK_Friend)
3691 Diag(KWLoc, diag::err_template_spec_friend)
3692 << FixItHint::CreateRemoval(
3693 SourceRange(TemplateParams->getTemplateLoc(),
3694 TemplateParams->getRAngleLoc()))
3695 << SourceRange(LAngleLoc, RAngleLoc);
3696 else
3697 isExplicitSpecialization = true;
3698 } else if (TUK != TUK_Friend) {
3699 Diag(KWLoc, diag::err_template_spec_needs_header)
3700 << FixItHint::CreateInsertion(KWLoc, "template<> ");
3701 isExplicitSpecialization = true;
3704 // Check that the specialization uses the same tag kind as the
3705 // original template.
3706 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3707 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
3708 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
3709 Kind, KWLoc,
3710 *ClassTemplate->getIdentifier())) {
3711 Diag(KWLoc, diag::err_use_with_wrong_tag)
3712 << ClassTemplate
3713 << FixItHint::CreateReplacement(KWLoc,
3714 ClassTemplate->getTemplatedDecl()->getKindName());
3715 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
3716 diag::note_previous_use);
3717 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3720 // Translate the parser's template argument list in our AST format.
3721 TemplateArgumentListInfo TemplateArgs;
3722 TemplateArgs.setLAngleLoc(LAngleLoc);
3723 TemplateArgs.setRAngleLoc(RAngleLoc);
3724 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3726 // Check that the template argument list is well-formed for this
3727 // template.
3728 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3729 TemplateArgs.size());
3730 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3731 TemplateArgs, false, Converted))
3732 return true;
3734 assert((Converted.structuredSize() ==
3735 ClassTemplate->getTemplateParameters()->size()) &&
3736 "Converted template argument list is too short!");
3738 // Find the class template (partial) specialization declaration that
3739 // corresponds to these arguments.
3740 if (isPartialSpecialization) {
3741 bool MirrorsPrimaryTemplate;
3742 if (CheckClassTemplatePartialSpecializationArgs(
3743 ClassTemplate->getTemplateParameters(),
3744 Converted, MirrorsPrimaryTemplate))
3745 return true;
3747 if (MirrorsPrimaryTemplate) {
3748 // C++ [temp.class.spec]p9b3:
3750 // -- The argument list of the specialization shall not be identical
3751 // to the implicit argument list of the primary template.
3752 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3753 << (TUK == TUK_Definition)
3754 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3755 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
3756 ClassTemplate->getIdentifier(),
3757 TemplateNameLoc,
3758 Attr,
3759 TemplateParams,
3760 AS_none);
3763 // FIXME: Diagnose friend partial specializations
3765 if (!Name.isDependent() &&
3766 !TemplateSpecializationType::anyDependentTemplateArguments(
3767 TemplateArgs.getArgumentArray(),
3768 TemplateArgs.size())) {
3769 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3770 << ClassTemplate->getDeclName();
3771 isPartialSpecialization = false;
3775 void *InsertPos = 0;
3776 ClassTemplateSpecializationDecl *PrevDecl = 0;
3778 if (isPartialSpecialization)
3779 // FIXME: Template parameter list matters, too
3780 PrevDecl
3781 = ClassTemplate->findPartialSpecialization(Converted.getFlatArguments(),
3782 Converted.flatSize(),
3783 InsertPos);
3784 else
3785 PrevDecl
3786 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
3787 Converted.flatSize(), InsertPos);
3789 ClassTemplateSpecializationDecl *Specialization = 0;
3791 // Check whether we can declare a class template specialization in
3792 // the current scope.
3793 if (TUK != TUK_Friend &&
3794 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
3795 TemplateNameLoc,
3796 isPartialSpecialization))
3797 return true;
3799 // The canonical type
3800 QualType CanonType;
3801 if (PrevDecl &&
3802 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3803 TUK == TUK_Friend)) {
3804 // Since the only prior class template specialization with these
3805 // arguments was referenced but not declared, or we're only
3806 // referencing this specialization as a friend, reuse that
3807 // declaration node as our own, updating its source location to
3808 // reflect our new declaration.
3809 Specialization = PrevDecl;
3810 Specialization->setLocation(TemplateNameLoc);
3811 PrevDecl = 0;
3812 CanonType = Context.getTypeDeclType(Specialization);
3813 } else if (isPartialSpecialization) {
3814 // Build the canonical type that describes the converted template
3815 // arguments of the class template partial specialization.
3816 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3817 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
3818 Converted.getFlatArguments(),
3819 Converted.flatSize());
3821 // Create a new class template partial specialization declaration node.
3822 ClassTemplatePartialSpecializationDecl *PrevPartial
3823 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
3824 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3825 : ClassTemplate->getNextPartialSpecSequenceNumber();
3826 ClassTemplatePartialSpecializationDecl *Partial
3827 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
3828 ClassTemplate->getDeclContext(),
3829 TemplateNameLoc,
3830 TemplateParams,
3831 ClassTemplate,
3832 Converted,
3833 TemplateArgs,
3834 CanonType,
3835 PrevPartial,
3836 SequenceNumber);
3837 SetNestedNameSpecifier(Partial, SS);
3838 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
3839 Partial->setTemplateParameterListsInfo(Context,
3840 NumMatchedTemplateParamLists,
3841 (TemplateParameterList**) TemplateParameterLists.release());
3844 if (!PrevPartial)
3845 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
3846 Specialization = Partial;
3848 // If we are providing an explicit specialization of a member class
3849 // template specialization, make a note of that.
3850 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3851 PrevPartial->setMemberSpecialization();
3853 // Check that all of the template parameters of the class template
3854 // partial specialization are deducible from the template
3855 // arguments. If not, this class template partial specialization
3856 // will never be used.
3857 llvm::SmallVector<bool, 8> DeducibleParams;
3858 DeducibleParams.resize(TemplateParams->size());
3859 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3860 TemplateParams->getDepth(),
3861 DeducibleParams);
3862 unsigned NumNonDeducible = 0;
3863 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3864 if (!DeducibleParams[I])
3865 ++NumNonDeducible;
3867 if (NumNonDeducible) {
3868 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3869 << (NumNonDeducible > 1)
3870 << SourceRange(TemplateNameLoc, RAngleLoc);
3871 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3872 if (!DeducibleParams[I]) {
3873 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3874 if (Param->getDeclName())
3875 Diag(Param->getLocation(),
3876 diag::note_partial_spec_unused_parameter)
3877 << Param->getDeclName();
3878 else
3879 Diag(Param->getLocation(),
3880 diag::note_partial_spec_unused_parameter)
3881 << "<anonymous>";
3885 } else {
3886 // Create a new class template specialization declaration node for
3887 // this explicit specialization or friend declaration.
3888 Specialization
3889 = ClassTemplateSpecializationDecl::Create(Context, Kind,
3890 ClassTemplate->getDeclContext(),
3891 TemplateNameLoc,
3892 ClassTemplate,
3893 Converted,
3894 PrevDecl);
3895 SetNestedNameSpecifier(Specialization, SS);
3896 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
3897 Specialization->setTemplateParameterListsInfo(Context,
3898 NumMatchedTemplateParamLists,
3899 (TemplateParameterList**) TemplateParameterLists.release());
3902 if (!PrevDecl)
3903 ClassTemplate->AddSpecialization(Specialization, InsertPos);
3905 CanonType = Context.getTypeDeclType(Specialization);
3908 // C++ [temp.expl.spec]p6:
3909 // If a template, a member template or the member of a class template is
3910 // explicitly specialized then that specialization shall be declared
3911 // before the first use of that specialization that would cause an implicit
3912 // instantiation to take place, in every translation unit in which such a
3913 // use occurs; no diagnostic is required.
3914 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3915 bool Okay = false;
3916 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3917 // Is there any previous explicit specialization declaration?
3918 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3919 Okay = true;
3920 break;
3924 if (!Okay) {
3925 SourceRange Range(TemplateNameLoc, RAngleLoc);
3926 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3927 << Context.getTypeDeclType(Specialization) << Range;
3929 Diag(PrevDecl->getPointOfInstantiation(),
3930 diag::note_instantiation_required_here)
3931 << (PrevDecl->getTemplateSpecializationKind()
3932 != TSK_ImplicitInstantiation);
3933 return true;
3937 // If this is not a friend, note that this is an explicit specialization.
3938 if (TUK != TUK_Friend)
3939 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3941 // Check that this isn't a redefinition of this specialization.
3942 if (TUK == TUK_Definition) {
3943 if (RecordDecl *Def = Specialization->getDefinition()) {
3944 SourceRange Range(TemplateNameLoc, RAngleLoc);
3945 Diag(TemplateNameLoc, diag::err_redefinition)
3946 << Context.getTypeDeclType(Specialization) << Range;
3947 Diag(Def->getLocation(), diag::note_previous_definition);
3948 Specialization->setInvalidDecl();
3949 return true;
3953 // Build the fully-sugared type for this class template
3954 // specialization as the user wrote in the specialization
3955 // itself. This means that we'll pretty-print the type retrieved
3956 // from the specialization's declaration the way that the user
3957 // actually wrote the specialization, rather than formatting the
3958 // name based on the "canonical" representation used to store the
3959 // template arguments in the specialization.
3960 TypeSourceInfo *WrittenTy
3961 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3962 TemplateArgs, CanonType);
3963 if (TUK != TUK_Friend) {
3964 Specialization->setTypeAsWritten(WrittenTy);
3965 if (TemplateParams)
3966 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
3968 TemplateArgsIn.release();
3970 // C++ [temp.expl.spec]p9:
3971 // A template explicit specialization is in the scope of the
3972 // namespace in which the template was defined.
3974 // We actually implement this paragraph where we set the semantic
3975 // context (in the creation of the ClassTemplateSpecializationDecl),
3976 // but we also maintain the lexical context where the actual
3977 // definition occurs.
3978 Specialization->setLexicalDeclContext(CurContext);
3980 // We may be starting the definition of this specialization.
3981 if (TUK == TUK_Definition)
3982 Specialization->startDefinition();
3984 if (TUK == TUK_Friend) {
3985 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3986 TemplateNameLoc,
3987 WrittenTy,
3988 /*FIXME:*/KWLoc);
3989 Friend->setAccess(AS_public);
3990 CurContext->addDecl(Friend);
3991 } else {
3992 // Add the specialization into its lexical context, so that it can
3993 // be seen when iterating through the list of declarations in that
3994 // context. However, specializations are not found by name lookup.
3995 CurContext->addDecl(Specialization);
3997 return Specialization;
4000 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
4001 MultiTemplateParamsArg TemplateParameterLists,
4002 Declarator &D) {
4003 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4006 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
4007 MultiTemplateParamsArg TemplateParameterLists,
4008 Declarator &D) {
4009 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4010 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4011 "Not a function declarator!");
4012 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4014 if (FTI.hasPrototype) {
4015 // FIXME: Diagnose arguments without names in C.
4018 Scope *ParentScope = FnBodyScope->getParent();
4020 Decl *DP = HandleDeclarator(ParentScope, D,
4021 move(TemplateParameterLists),
4022 /*IsFunctionDefinition=*/true);
4023 if (FunctionTemplateDecl *FunctionTemplate
4024 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
4025 return ActOnStartOfFunctionDef(FnBodyScope,
4026 FunctionTemplate->getTemplatedDecl());
4027 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4028 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4029 return 0;
4032 /// \brief Strips various properties off an implicit instantiation
4033 /// that has just been explicitly specialized.
4034 static void StripImplicitInstantiation(NamedDecl *D) {
4035 D->dropAttrs();
4037 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4038 FD->setInlineSpecified(false);
4042 /// \brief Diagnose cases where we have an explicit template specialization
4043 /// before/after an explicit template instantiation, producing diagnostics
4044 /// for those cases where they are required and determining whether the
4045 /// new specialization/instantiation will have any effect.
4047 /// \param NewLoc the location of the new explicit specialization or
4048 /// instantiation.
4050 /// \param NewTSK the kind of the new explicit specialization or instantiation.
4052 /// \param PrevDecl the previous declaration of the entity.
4054 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4056 /// \param PrevPointOfInstantiation if valid, indicates where the previus
4057 /// declaration was instantiated (either implicitly or explicitly).
4059 /// \param HasNoEffect will be set to true to indicate that the new
4060 /// specialization or instantiation has no effect and should be ignored.
4062 /// \returns true if there was an error that should prevent the introduction of
4063 /// the new declaration into the AST, false otherwise.
4064 bool
4065 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4066 TemplateSpecializationKind NewTSK,
4067 NamedDecl *PrevDecl,
4068 TemplateSpecializationKind PrevTSK,
4069 SourceLocation PrevPointOfInstantiation,
4070 bool &HasNoEffect) {
4071 HasNoEffect = false;
4073 switch (NewTSK) {
4074 case TSK_Undeclared:
4075 case TSK_ImplicitInstantiation:
4076 assert(false && "Don't check implicit instantiations here");
4077 return false;
4079 case TSK_ExplicitSpecialization:
4080 switch (PrevTSK) {
4081 case TSK_Undeclared:
4082 case TSK_ExplicitSpecialization:
4083 // Okay, we're just specializing something that is either already
4084 // explicitly specialized or has merely been mentioned without any
4085 // instantiation.
4086 return false;
4088 case TSK_ImplicitInstantiation:
4089 if (PrevPointOfInstantiation.isInvalid()) {
4090 // The declaration itself has not actually been instantiated, so it is
4091 // still okay to specialize it.
4092 StripImplicitInstantiation(PrevDecl);
4093 return false;
4095 // Fall through
4097 case TSK_ExplicitInstantiationDeclaration:
4098 case TSK_ExplicitInstantiationDefinition:
4099 assert((PrevTSK == TSK_ImplicitInstantiation ||
4100 PrevPointOfInstantiation.isValid()) &&
4101 "Explicit instantiation without point of instantiation?");
4103 // C++ [temp.expl.spec]p6:
4104 // If a template, a member template or the member of a class template
4105 // is explicitly specialized then that specialization shall be declared
4106 // before the first use of that specialization that would cause an
4107 // implicit instantiation to take place, in every translation unit in
4108 // which such a use occurs; no diagnostic is required.
4109 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4110 // Is there any previous explicit specialization declaration?
4111 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4112 return false;
4115 Diag(NewLoc, diag::err_specialization_after_instantiation)
4116 << PrevDecl;
4117 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
4118 << (PrevTSK != TSK_ImplicitInstantiation);
4120 return true;
4122 break;
4124 case TSK_ExplicitInstantiationDeclaration:
4125 switch (PrevTSK) {
4126 case TSK_ExplicitInstantiationDeclaration:
4127 // This explicit instantiation declaration is redundant (that's okay).
4128 HasNoEffect = true;
4129 return false;
4131 case TSK_Undeclared:
4132 case TSK_ImplicitInstantiation:
4133 // We're explicitly instantiating something that may have already been
4134 // implicitly instantiated; that's fine.
4135 return false;
4137 case TSK_ExplicitSpecialization:
4138 // C++0x [temp.explicit]p4:
4139 // For a given set of template parameters, if an explicit instantiation
4140 // of a template appears after a declaration of an explicit
4141 // specialization for that template, the explicit instantiation has no
4142 // effect.
4143 HasNoEffect = true;
4144 return false;
4146 case TSK_ExplicitInstantiationDefinition:
4147 // C++0x [temp.explicit]p10:
4148 // If an entity is the subject of both an explicit instantiation
4149 // declaration and an explicit instantiation definition in the same
4150 // translation unit, the definition shall follow the declaration.
4151 Diag(NewLoc,
4152 diag::err_explicit_instantiation_declaration_after_definition);
4153 Diag(PrevPointOfInstantiation,
4154 diag::note_explicit_instantiation_definition_here);
4155 assert(PrevPointOfInstantiation.isValid() &&
4156 "Explicit instantiation without point of instantiation?");
4157 HasNoEffect = true;
4158 return false;
4160 break;
4162 case TSK_ExplicitInstantiationDefinition:
4163 switch (PrevTSK) {
4164 case TSK_Undeclared:
4165 case TSK_ImplicitInstantiation:
4166 // We're explicitly instantiating something that may have already been
4167 // implicitly instantiated; that's fine.
4168 return false;
4170 case TSK_ExplicitSpecialization:
4171 // C++ DR 259, C++0x [temp.explicit]p4:
4172 // For a given set of template parameters, if an explicit
4173 // instantiation of a template appears after a declaration of
4174 // an explicit specialization for that template, the explicit
4175 // instantiation has no effect.
4177 // In C++98/03 mode, we only give an extension warning here, because it
4178 // is not harmful to try to explicitly instantiate something that
4179 // has been explicitly specialized.
4180 if (!getLangOptions().CPlusPlus0x) {
4181 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
4182 << PrevDecl;
4183 Diag(PrevDecl->getLocation(),
4184 diag::note_previous_template_specialization);
4186 HasNoEffect = true;
4187 return false;
4189 case TSK_ExplicitInstantiationDeclaration:
4190 // We're explicity instantiating a definition for something for which we
4191 // were previously asked to suppress instantiations. That's fine.
4192 return false;
4194 case TSK_ExplicitInstantiationDefinition:
4195 // C++0x [temp.spec]p5:
4196 // For a given template and a given set of template-arguments,
4197 // - an explicit instantiation definition shall appear at most once
4198 // in a program,
4199 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
4200 << PrevDecl;
4201 Diag(PrevPointOfInstantiation,
4202 diag::note_previous_explicit_instantiation);
4203 HasNoEffect = true;
4204 return false;
4206 break;
4209 assert(false && "Missing specialization/instantiation case?");
4211 return false;
4214 /// \brief Perform semantic analysis for the given dependent function
4215 /// template specialization. The only possible way to get a dependent
4216 /// function template specialization is with a friend declaration,
4217 /// like so:
4219 /// template <class T> void foo(T);
4220 /// template <class T> class A {
4221 /// friend void foo<>(T);
4222 /// };
4224 /// There really isn't any useful analysis we can do here, so we
4225 /// just store the information.
4226 bool
4227 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4228 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4229 LookupResult &Previous) {
4230 // Remove anything from Previous that isn't a function template in
4231 // the correct context.
4232 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4233 LookupResult::Filter F = Previous.makeFilter();
4234 while (F.hasNext()) {
4235 NamedDecl *D = F.next()->getUnderlyingDecl();
4236 if (!isa<FunctionTemplateDecl>(D) ||
4237 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4238 F.erase();
4240 F.done();
4242 // Should this be diagnosed here?
4243 if (Previous.empty()) return true;
4245 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4246 ExplicitTemplateArgs);
4247 return false;
4250 /// \brief Perform semantic analysis for the given function template
4251 /// specialization.
4253 /// This routine performs all of the semantic analysis required for an
4254 /// explicit function template specialization. On successful completion,
4255 /// the function declaration \p FD will become a function template
4256 /// specialization.
4258 /// \param FD the function declaration, which will be updated to become a
4259 /// function template specialization.
4261 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4262 /// if any. Note that this may be valid info even when 0 arguments are
4263 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4264 /// as it anyway contains info on the angle brackets locations.
4266 /// \param PrevDecl the set of declarations that may be specialized by
4267 /// this function specialization.
4268 bool
4269 Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
4270 const TemplateArgumentListInfo *ExplicitTemplateArgs,
4271 LookupResult &Previous) {
4272 // The set of function template specializations that could match this
4273 // explicit function template specialization.
4274 UnresolvedSet<8> Candidates;
4276 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4277 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4278 I != E; ++I) {
4279 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4280 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
4281 // Only consider templates found within the same semantic lookup scope as
4282 // FD.
4283 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4284 continue;
4286 // C++ [temp.expl.spec]p11:
4287 // A trailing template-argument can be left unspecified in the
4288 // template-id naming an explicit function template specialization
4289 // provided it can be deduced from the function argument type.
4290 // Perform template argument deduction to determine whether we may be
4291 // specializing this template.
4292 // FIXME: It is somewhat wasteful to build
4293 TemplateDeductionInfo Info(Context, FD->getLocation());
4294 FunctionDecl *Specialization = 0;
4295 if (TemplateDeductionResult TDK
4296 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
4297 FD->getType(),
4298 Specialization,
4299 Info)) {
4300 // FIXME: Template argument deduction failed; record why it failed, so
4301 // that we can provide nifty diagnostics.
4302 (void)TDK;
4303 continue;
4306 // Record this candidate.
4307 Candidates.addDecl(Specialization, I.getAccess());
4311 // Find the most specialized function template.
4312 UnresolvedSetIterator Result
4313 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4314 TPOC_Other, FD->getLocation(),
4315 PDiag(diag::err_function_template_spec_no_match)
4316 << FD->getDeclName(),
4317 PDiag(diag::err_function_template_spec_ambiguous)
4318 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
4319 PDiag(diag::note_function_template_spec_matched));
4320 if (Result == Candidates.end())
4321 return true;
4323 // Ignore access information; it doesn't figure into redeclaration checking.
4324 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
4325 Specialization->setLocation(FD->getLocation());
4327 // FIXME: Check if the prior specialization has a point of instantiation.
4328 // If so, we have run afoul of .
4330 // If this is a friend declaration, then we're not really declaring
4331 // an explicit specialization.
4332 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
4334 // Check the scope of this explicit specialization.
4335 if (!isFriend &&
4336 CheckTemplateSpecializationScope(*this,
4337 Specialization->getPrimaryTemplate(),
4338 Specialization, FD->getLocation(),
4339 false))
4340 return true;
4342 // C++ [temp.expl.spec]p6:
4343 // If a template, a member template or the member of a class template is
4344 // explicitly specialized then that specialization shall be declared
4345 // before the first use of that specialization that would cause an implicit
4346 // instantiation to take place, in every translation unit in which such a
4347 // use occurs; no diagnostic is required.
4348 FunctionTemplateSpecializationInfo *SpecInfo
4349 = Specialization->getTemplateSpecializationInfo();
4350 assert(SpecInfo && "Function template specialization info missing?");
4352 bool HasNoEffect = false;
4353 if (!isFriend &&
4354 CheckSpecializationInstantiationRedecl(FD->getLocation(),
4355 TSK_ExplicitSpecialization,
4356 Specialization,
4357 SpecInfo->getTemplateSpecializationKind(),
4358 SpecInfo->getPointOfInstantiation(),
4359 HasNoEffect))
4360 return true;
4362 // Mark the prior declaration as an explicit specialization, so that later
4363 // clients know that this is an explicit specialization.
4364 if (!isFriend) {
4365 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
4366 MarkUnusedFileScopedDecl(Specialization);
4369 // Turn the given function declaration into a function template
4370 // specialization, with the template arguments from the previous
4371 // specialization.
4372 // Take copies of (semantic and syntactic) template argument lists.
4373 const TemplateArgumentList* TemplArgs = new (Context)
4374 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4375 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4376 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
4377 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
4378 TemplArgs, /*InsertPos=*/0,
4379 SpecInfo->getTemplateSpecializationKind(),
4380 TemplArgsAsWritten);
4382 // The "previous declaration" for this function template specialization is
4383 // the prior function template specialization.
4384 Previous.clear();
4385 Previous.addDecl(Specialization);
4386 return false;
4389 /// \brief Perform semantic analysis for the given non-template member
4390 /// specialization.
4392 /// This routine performs all of the semantic analysis required for an
4393 /// explicit member function specialization. On successful completion,
4394 /// the function declaration \p FD will become a member function
4395 /// specialization.
4397 /// \param Member the member declaration, which will be updated to become a
4398 /// specialization.
4400 /// \param Previous the set of declarations, one of which may be specialized
4401 /// by this function specialization; the set will be modified to contain the
4402 /// redeclared member.
4403 bool
4404 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
4405 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
4407 // Try to find the member we are instantiating.
4408 NamedDecl *Instantiation = 0;
4409 NamedDecl *InstantiatedFrom = 0;
4410 MemberSpecializationInfo *MSInfo = 0;
4412 if (Previous.empty()) {
4413 // Nowhere to look anyway.
4414 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
4415 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4416 I != E; ++I) {
4417 NamedDecl *D = (*I)->getUnderlyingDecl();
4418 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4419 if (Context.hasSameType(Function->getType(), Method->getType())) {
4420 Instantiation = Method;
4421 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
4422 MSInfo = Method->getMemberSpecializationInfo();
4423 break;
4427 } else if (isa<VarDecl>(Member)) {
4428 VarDecl *PrevVar;
4429 if (Previous.isSingleResult() &&
4430 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
4431 if (PrevVar->isStaticDataMember()) {
4432 Instantiation = PrevVar;
4433 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
4434 MSInfo = PrevVar->getMemberSpecializationInfo();
4436 } else if (isa<RecordDecl>(Member)) {
4437 CXXRecordDecl *PrevRecord;
4438 if (Previous.isSingleResult() &&
4439 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4440 Instantiation = PrevRecord;
4441 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
4442 MSInfo = PrevRecord->getMemberSpecializationInfo();
4446 if (!Instantiation) {
4447 // There is no previous declaration that matches. Since member
4448 // specializations are always out-of-line, the caller will complain about
4449 // this mismatch later.
4450 return false;
4453 // If this is a friend, just bail out here before we start turning
4454 // things into explicit specializations.
4455 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4456 // Preserve instantiation information.
4457 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4458 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4459 cast<CXXMethodDecl>(InstantiatedFrom),
4460 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4461 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4462 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4463 cast<CXXRecordDecl>(InstantiatedFrom),
4464 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4467 Previous.clear();
4468 Previous.addDecl(Instantiation);
4469 return false;
4472 // Make sure that this is a specialization of a member.
4473 if (!InstantiatedFrom) {
4474 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4475 << Member;
4476 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4477 return true;
4480 // C++ [temp.expl.spec]p6:
4481 // If a template, a member template or the member of a class template is
4482 // explicitly specialized then that spe- cialization shall be declared
4483 // before the first use of that specialization that would cause an implicit
4484 // instantiation to take place, in every translation unit in which such a
4485 // use occurs; no diagnostic is required.
4486 assert(MSInfo && "Member specialization info missing?");
4488 bool HasNoEffect = false;
4489 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4490 TSK_ExplicitSpecialization,
4491 Instantiation,
4492 MSInfo->getTemplateSpecializationKind(),
4493 MSInfo->getPointOfInstantiation(),
4494 HasNoEffect))
4495 return true;
4497 // Check the scope of this explicit specialization.
4498 if (CheckTemplateSpecializationScope(*this,
4499 InstantiatedFrom,
4500 Instantiation, Member->getLocation(),
4501 false))
4502 return true;
4504 // Note that this is an explicit instantiation of a member.
4505 // the original declaration to note that it is an explicit specialization
4506 // (if it was previously an implicit instantiation). This latter step
4507 // makes bookkeeping easier.
4508 if (isa<FunctionDecl>(Member)) {
4509 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4510 if (InstantiationFunction->getTemplateSpecializationKind() ==
4511 TSK_ImplicitInstantiation) {
4512 InstantiationFunction->setTemplateSpecializationKind(
4513 TSK_ExplicitSpecialization);
4514 InstantiationFunction->setLocation(Member->getLocation());
4517 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4518 cast<CXXMethodDecl>(InstantiatedFrom),
4519 TSK_ExplicitSpecialization);
4520 MarkUnusedFileScopedDecl(InstantiationFunction);
4521 } else if (isa<VarDecl>(Member)) {
4522 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4523 if (InstantiationVar->getTemplateSpecializationKind() ==
4524 TSK_ImplicitInstantiation) {
4525 InstantiationVar->setTemplateSpecializationKind(
4526 TSK_ExplicitSpecialization);
4527 InstantiationVar->setLocation(Member->getLocation());
4530 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4531 cast<VarDecl>(InstantiatedFrom),
4532 TSK_ExplicitSpecialization);
4533 MarkUnusedFileScopedDecl(InstantiationVar);
4534 } else {
4535 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
4536 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4537 if (InstantiationClass->getTemplateSpecializationKind() ==
4538 TSK_ImplicitInstantiation) {
4539 InstantiationClass->setTemplateSpecializationKind(
4540 TSK_ExplicitSpecialization);
4541 InstantiationClass->setLocation(Member->getLocation());
4544 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4545 cast<CXXRecordDecl>(InstantiatedFrom),
4546 TSK_ExplicitSpecialization);
4549 // Save the caller the trouble of having to figure out which declaration
4550 // this specialization matches.
4551 Previous.clear();
4552 Previous.addDecl(Instantiation);
4553 return false;
4556 /// \brief Check the scope of an explicit instantiation.
4558 /// \returns true if a serious error occurs, false otherwise.
4559 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4560 SourceLocation InstLoc,
4561 bool WasQualifiedName) {
4562 DeclContext *ExpectedContext
4563 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4564 DeclContext *CurContext = S.CurContext->getLookupContext();
4566 if (CurContext->isRecord()) {
4567 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4568 << D;
4569 return true;
4572 // C++0x [temp.explicit]p2:
4573 // An explicit instantiation shall appear in an enclosing namespace of its
4574 // template.
4576 // This is DR275, which we do not retroactively apply to C++98/03.
4577 if (S.getLangOptions().CPlusPlus0x &&
4578 !CurContext->Encloses(ExpectedContext)) {
4579 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4580 S.Diag(InstLoc,
4581 S.getLangOptions().CPlusPlus0x?
4582 diag::err_explicit_instantiation_out_of_scope
4583 : diag::warn_explicit_instantiation_out_of_scope_0x)
4584 << D << NS;
4585 else
4586 S.Diag(InstLoc,
4587 S.getLangOptions().CPlusPlus0x?
4588 diag::err_explicit_instantiation_must_be_global
4589 : diag::warn_explicit_instantiation_out_of_scope_0x)
4590 << D;
4591 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4592 return false;
4595 // C++0x [temp.explicit]p2:
4596 // If the name declared in the explicit instantiation is an unqualified
4597 // name, the explicit instantiation shall appear in the namespace where
4598 // its template is declared or, if that namespace is inline (7.3.1), any
4599 // namespace from its enclosing namespace set.
4600 if (WasQualifiedName)
4601 return false;
4603 if (CurContext->Equals(ExpectedContext))
4604 return false;
4606 S.Diag(InstLoc,
4607 S.getLangOptions().CPlusPlus0x?
4608 diag::err_explicit_instantiation_unqualified_wrong_namespace
4609 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
4610 << D << ExpectedContext;
4611 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4612 return false;
4615 /// \brief Determine whether the given scope specifier has a template-id in it.
4616 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4617 if (!SS.isSet())
4618 return false;
4620 // C++0x [temp.explicit]p2:
4621 // If the explicit instantiation is for a member function, a member class
4622 // or a static data member of a class template specialization, the name of
4623 // the class template specialization in the qualified-id for the member
4624 // name shall be a simple-template-id.
4626 // C++98 has the same restriction, just worded differently.
4627 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4628 NNS; NNS = NNS->getPrefix())
4629 if (Type *T = NNS->getAsType())
4630 if (isa<TemplateSpecializationType>(T))
4631 return true;
4633 return false;
4636 // Explicit instantiation of a class template specialization
4637 DeclResult
4638 Sema::ActOnExplicitInstantiation(Scope *S,
4639 SourceLocation ExternLoc,
4640 SourceLocation TemplateLoc,
4641 unsigned TagSpec,
4642 SourceLocation KWLoc,
4643 const CXXScopeSpec &SS,
4644 TemplateTy TemplateD,
4645 SourceLocation TemplateNameLoc,
4646 SourceLocation LAngleLoc,
4647 ASTTemplateArgsPtr TemplateArgsIn,
4648 SourceLocation RAngleLoc,
4649 AttributeList *Attr) {
4650 // Find the class template we're specializing
4651 TemplateName Name = TemplateD.getAsVal<TemplateName>();
4652 ClassTemplateDecl *ClassTemplate
4653 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4655 // Check that the specialization uses the same tag kind as the
4656 // original template.
4657 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4658 assert(Kind != TTK_Enum &&
4659 "Invalid enum tag in class template explicit instantiation!");
4660 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
4661 Kind, KWLoc,
4662 *ClassTemplate->getIdentifier())) {
4663 Diag(KWLoc, diag::err_use_with_wrong_tag)
4664 << ClassTemplate
4665 << FixItHint::CreateReplacement(KWLoc,
4666 ClassTemplate->getTemplatedDecl()->getKindName());
4667 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
4668 diag::note_previous_use);
4669 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4672 // C++0x [temp.explicit]p2:
4673 // There are two forms of explicit instantiation: an explicit instantiation
4674 // definition and an explicit instantiation declaration. An explicit
4675 // instantiation declaration begins with the extern keyword. [...]
4676 TemplateSpecializationKind TSK
4677 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4678 : TSK_ExplicitInstantiationDeclaration;
4680 // Translate the parser's template argument list in our AST format.
4681 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4682 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4684 // Check that the template argument list is well-formed for this
4685 // template.
4686 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4687 TemplateArgs.size());
4688 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4689 TemplateArgs, false, Converted))
4690 return true;
4692 assert((Converted.structuredSize() ==
4693 ClassTemplate->getTemplateParameters()->size()) &&
4694 "Converted template argument list is too short!");
4696 // Find the class template specialization declaration that
4697 // corresponds to these arguments.
4698 void *InsertPos = 0;
4699 ClassTemplateSpecializationDecl *PrevDecl
4700 = ClassTemplate->findSpecialization(Converted.getFlatArguments(),
4701 Converted.flatSize(), InsertPos);
4703 TemplateSpecializationKind PrevDecl_TSK
4704 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4706 // C++0x [temp.explicit]p2:
4707 // [...] An explicit instantiation shall appear in an enclosing
4708 // namespace of its template. [...]
4710 // This is C++ DR 275.
4711 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4712 SS.isSet()))
4713 return true;
4715 ClassTemplateSpecializationDecl *Specialization = 0;
4717 bool ReusedDecl = false;
4718 bool HasNoEffect = false;
4719 if (PrevDecl) {
4720 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
4721 PrevDecl, PrevDecl_TSK,
4722 PrevDecl->getPointOfInstantiation(),
4723 HasNoEffect))
4724 return PrevDecl;
4726 // Even though HasNoEffect == true means that this explicit instantiation
4727 // has no effect on semantics, we go on to put its syntax in the AST.
4729 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4730 PrevDecl_TSK == TSK_Undeclared) {
4731 // Since the only prior class template specialization with these
4732 // arguments was referenced but not declared, reuse that
4733 // declaration node as our own, updating the source location
4734 // for the template name to reflect our new declaration.
4735 // (Other source locations will be updated later.)
4736 Specialization = PrevDecl;
4737 Specialization->setLocation(TemplateNameLoc);
4738 PrevDecl = 0;
4739 ReusedDecl = true;
4743 if (!Specialization) {
4744 // Create a new class template specialization declaration node for
4745 // this explicit specialization.
4746 Specialization
4747 = ClassTemplateSpecializationDecl::Create(Context, Kind,
4748 ClassTemplate->getDeclContext(),
4749 TemplateNameLoc,
4750 ClassTemplate,
4751 Converted, PrevDecl);
4752 SetNestedNameSpecifier(Specialization, SS);
4754 if (!HasNoEffect && !PrevDecl) {
4755 // Insert the new specialization.
4756 ClassTemplate->AddSpecialization(Specialization, InsertPos);
4760 // Build the fully-sugared type for this explicit instantiation as
4761 // the user wrote in the explicit instantiation itself. This means
4762 // that we'll pretty-print the type retrieved from the
4763 // specialization's declaration the way that the user actually wrote
4764 // the explicit instantiation, rather than formatting the name based
4765 // on the "canonical" representation used to store the template
4766 // arguments in the specialization.
4767 TypeSourceInfo *WrittenTy
4768 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4769 TemplateArgs,
4770 Context.getTypeDeclType(Specialization));
4771 Specialization->setTypeAsWritten(WrittenTy);
4772 TemplateArgsIn.release();
4774 // Set source locations for keywords.
4775 Specialization->setExternLoc(ExternLoc);
4776 Specialization->setTemplateKeywordLoc(TemplateLoc);
4778 // Add the explicit instantiation into its lexical context. However,
4779 // since explicit instantiations are never found by name lookup, we
4780 // just put it into the declaration context directly.
4781 Specialization->setLexicalDeclContext(CurContext);
4782 CurContext->addDecl(Specialization);
4784 // Syntax is now OK, so return if it has no other effect on semantics.
4785 if (HasNoEffect) {
4786 // Set the template specialization kind.
4787 Specialization->setTemplateSpecializationKind(TSK);
4788 return Specialization;
4791 // C++ [temp.explicit]p3:
4792 // A definition of a class template or class member template
4793 // shall be in scope at the point of the explicit instantiation of
4794 // the class template or class member template.
4796 // This check comes when we actually try to perform the
4797 // instantiation.
4798 ClassTemplateSpecializationDecl *Def
4799 = cast_or_null<ClassTemplateSpecializationDecl>(
4800 Specialization->getDefinition());
4801 if (!Def)
4802 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
4803 else if (TSK == TSK_ExplicitInstantiationDefinition) {
4804 MarkVTableUsed(TemplateNameLoc, Specialization, true);
4805 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4808 // Instantiate the members of this class template specialization.
4809 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4810 Specialization->getDefinition());
4811 if (Def) {
4812 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4814 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4815 // TSK_ExplicitInstantiationDefinition
4816 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4817 TSK == TSK_ExplicitInstantiationDefinition)
4818 Def->setTemplateSpecializationKind(TSK);
4820 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
4823 // Set the template specialization kind.
4824 Specialization->setTemplateSpecializationKind(TSK);
4825 return Specialization;
4828 // Explicit instantiation of a member class of a class template.
4829 DeclResult
4830 Sema::ActOnExplicitInstantiation(Scope *S,
4831 SourceLocation ExternLoc,
4832 SourceLocation TemplateLoc,
4833 unsigned TagSpec,
4834 SourceLocation KWLoc,
4835 CXXScopeSpec &SS,
4836 IdentifierInfo *Name,
4837 SourceLocation NameLoc,
4838 AttributeList *Attr) {
4840 bool Owned = false;
4841 bool IsDependent = false;
4842 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
4843 KWLoc, SS, Name, NameLoc, Attr, AS_none,
4844 MultiTemplateParamsArg(*this, 0, 0),
4845 Owned, IsDependent);
4846 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4848 if (!TagD)
4849 return true;
4851 TagDecl *Tag = cast<TagDecl>(TagD);
4852 if (Tag->isEnum()) {
4853 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4854 << Context.getTypeDeclType(Tag);
4855 return true;
4858 if (Tag->isInvalidDecl())
4859 return true;
4861 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4862 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4863 if (!Pattern) {
4864 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4865 << Context.getTypeDeclType(Record);
4866 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4867 return true;
4870 // C++0x [temp.explicit]p2:
4871 // If the explicit instantiation is for a class or member class, the
4872 // elaborated-type-specifier in the declaration shall include a
4873 // simple-template-id.
4875 // C++98 has the same restriction, just worded differently.
4876 if (!ScopeSpecifierHasTemplateId(SS))
4877 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
4878 << Record << SS.getRange();
4880 // C++0x [temp.explicit]p2:
4881 // There are two forms of explicit instantiation: an explicit instantiation
4882 // definition and an explicit instantiation declaration. An explicit
4883 // instantiation declaration begins with the extern keyword. [...]
4884 TemplateSpecializationKind TSK
4885 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4886 : TSK_ExplicitInstantiationDeclaration;
4888 // C++0x [temp.explicit]p2:
4889 // [...] An explicit instantiation shall appear in an enclosing
4890 // namespace of its template. [...]
4892 // This is C++ DR 275.
4893 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
4895 // Verify that it is okay to explicitly instantiate here.
4896 CXXRecordDecl *PrevDecl
4897 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4898 if (!PrevDecl && Record->getDefinition())
4899 PrevDecl = Record;
4900 if (PrevDecl) {
4901 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4902 bool HasNoEffect = false;
4903 assert(MSInfo && "No member specialization information?");
4904 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
4905 PrevDecl,
4906 MSInfo->getTemplateSpecializationKind(),
4907 MSInfo->getPointOfInstantiation(),
4908 HasNoEffect))
4909 return true;
4910 if (HasNoEffect)
4911 return TagD;
4914 CXXRecordDecl *RecordDef
4915 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4916 if (!RecordDef) {
4917 // C++ [temp.explicit]p3:
4918 // A definition of a member class of a class template shall be in scope
4919 // at the point of an explicit instantiation of the member class.
4920 CXXRecordDecl *Def
4921 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
4922 if (!Def) {
4923 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4924 << 0 << Record->getDeclName() << Record->getDeclContext();
4925 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4926 << Pattern;
4927 return true;
4928 } else {
4929 if (InstantiateClass(NameLoc, Record, Def,
4930 getTemplateInstantiationArgs(Record),
4931 TSK))
4932 return true;
4934 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4935 if (!RecordDef)
4936 return true;
4940 // Instantiate all of the members of the class.
4941 InstantiateClassMembers(NameLoc, RecordDef,
4942 getTemplateInstantiationArgs(Record), TSK);
4944 if (TSK == TSK_ExplicitInstantiationDefinition)
4945 MarkVTableUsed(NameLoc, RecordDef, true);
4947 // FIXME: We don't have any representation for explicit instantiations of
4948 // member classes. Such a representation is not needed for compilation, but it
4949 // should be available for clients that want to see all of the declarations in
4950 // the source code.
4951 return TagD;
4954 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4955 SourceLocation ExternLoc,
4956 SourceLocation TemplateLoc,
4957 Declarator &D) {
4958 // Explicit instantiations always require a name.
4959 // TODO: check if/when DNInfo should replace Name.
4960 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4961 DeclarationName Name = NameInfo.getName();
4962 if (!Name) {
4963 if (!D.isInvalidType())
4964 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4965 diag::err_explicit_instantiation_requires_name)
4966 << D.getDeclSpec().getSourceRange()
4967 << D.getSourceRange();
4969 return true;
4972 // The scope passed in may not be a decl scope. Zip up the scope tree until
4973 // we find one that is.
4974 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4975 (S->getFlags() & Scope::TemplateParamScope) != 0)
4976 S = S->getParent();
4978 // Determine the type of the declaration.
4979 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4980 QualType R = T->getType();
4981 if (R.isNull())
4982 return true;
4984 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4985 // Cannot explicitly instantiate a typedef.
4986 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4987 << Name;
4988 return true;
4991 // C++0x [temp.explicit]p1:
4992 // [...] An explicit instantiation of a function template shall not use the
4993 // inline or constexpr specifiers.
4994 // Presumably, this also applies to member functions of class templates as
4995 // well.
4996 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4997 Diag(D.getDeclSpec().getInlineSpecLoc(),
4998 diag::err_explicit_instantiation_inline)
4999 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5001 // FIXME: check for constexpr specifier.
5003 // C++0x [temp.explicit]p2:
5004 // There are two forms of explicit instantiation: an explicit instantiation
5005 // definition and an explicit instantiation declaration. An explicit
5006 // instantiation declaration begins with the extern keyword. [...]
5007 TemplateSpecializationKind TSK
5008 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5009 : TSK_ExplicitInstantiationDeclaration;
5011 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
5012 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
5014 if (!R->isFunctionType()) {
5015 // C++ [temp.explicit]p1:
5016 // A [...] static data member of a class template can be explicitly
5017 // instantiated from the member definition associated with its class
5018 // template.
5019 if (Previous.isAmbiguous())
5020 return true;
5022 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
5023 if (!Prev || !Prev->isStaticDataMember()) {
5024 // We expect to see a data data member here.
5025 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5026 << Name;
5027 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5028 P != PEnd; ++P)
5029 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
5030 return true;
5033 if (!Prev->getInstantiatedFromStaticDataMember()) {
5034 // FIXME: Check for explicit specialization?
5035 Diag(D.getIdentifierLoc(),
5036 diag::err_explicit_instantiation_data_member_not_instantiated)
5037 << Prev;
5038 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5039 // FIXME: Can we provide a note showing where this was declared?
5040 return true;
5043 // C++0x [temp.explicit]p2:
5044 // If the explicit instantiation is for a member function, a member class
5045 // or a static data member of a class template specialization, the name of
5046 // the class template specialization in the qualified-id for the member
5047 // name shall be a simple-template-id.
5049 // C++98 has the same restriction, just worded differently.
5050 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5051 Diag(D.getIdentifierLoc(),
5052 diag::ext_explicit_instantiation_without_qualified_id)
5053 << Prev << D.getCXXScopeSpec().getRange();
5055 // Check the scope of this explicit instantiation.
5056 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5058 // Verify that it is okay to explicitly instantiate here.
5059 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5060 assert(MSInfo && "Missing static data member specialization info?");
5061 bool HasNoEffect = false;
5062 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
5063 MSInfo->getTemplateSpecializationKind(),
5064 MSInfo->getPointOfInstantiation(),
5065 HasNoEffect))
5066 return true;
5067 if (HasNoEffect)
5068 return (Decl*) 0;
5070 // Instantiate static data member.
5071 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
5072 if (TSK == TSK_ExplicitInstantiationDefinition)
5073 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
5075 // FIXME: Create an ExplicitInstantiation node?
5076 return (Decl*) 0;
5079 // If the declarator is a template-id, translate the parser's template
5080 // argument list into our AST format.
5081 bool HasExplicitTemplateArgs = false;
5082 TemplateArgumentListInfo TemplateArgs;
5083 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5084 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5085 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5086 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5087 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5088 TemplateId->getTemplateArgs(),
5089 TemplateId->NumArgs);
5090 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
5091 HasExplicitTemplateArgs = true;
5092 TemplateArgsPtr.release();
5095 // C++ [temp.explicit]p1:
5096 // A [...] function [...] can be explicitly instantiated from its template.
5097 // A member function [...] of a class template can be explicitly
5098 // instantiated from the member definition associated with its class
5099 // template.
5100 UnresolvedSet<8> Matches;
5101 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5102 P != PEnd; ++P) {
5103 NamedDecl *Prev = *P;
5104 if (!HasExplicitTemplateArgs) {
5105 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5106 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5107 Matches.clear();
5109 Matches.addDecl(Method, P.getAccess());
5110 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5111 break;
5116 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5117 if (!FunTmpl)
5118 continue;
5120 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
5121 FunctionDecl *Specialization = 0;
5122 if (TemplateDeductionResult TDK
5123 = DeduceTemplateArguments(FunTmpl,
5124 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5125 R, Specialization, Info)) {
5126 // FIXME: Keep track of almost-matches?
5127 (void)TDK;
5128 continue;
5131 Matches.addDecl(Specialization, P.getAccess());
5134 // Find the most specialized function template specialization.
5135 UnresolvedSetIterator Result
5136 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
5137 D.getIdentifierLoc(),
5138 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5139 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5140 PDiag(diag::note_explicit_instantiation_candidate));
5142 if (Result == Matches.end())
5143 return true;
5145 // Ignore access control bits, we don't need them for redeclaration checking.
5146 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
5148 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
5149 Diag(D.getIdentifierLoc(),
5150 diag::err_explicit_instantiation_member_function_not_instantiated)
5151 << Specialization
5152 << (Specialization->getTemplateSpecializationKind() ==
5153 TSK_ExplicitSpecialization);
5154 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5155 return true;
5158 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
5159 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5160 PrevDecl = Specialization;
5162 if (PrevDecl) {
5163 bool HasNoEffect = false;
5164 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
5165 PrevDecl,
5166 PrevDecl->getTemplateSpecializationKind(),
5167 PrevDecl->getPointOfInstantiation(),
5168 HasNoEffect))
5169 return true;
5171 // FIXME: We may still want to build some representation of this
5172 // explicit specialization.
5173 if (HasNoEffect)
5174 return (Decl*) 0;
5177 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
5179 if (TSK == TSK_ExplicitInstantiationDefinition)
5180 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
5182 // C++0x [temp.explicit]p2:
5183 // If the explicit instantiation is for a member function, a member class
5184 // or a static data member of a class template specialization, the name of
5185 // the class template specialization in the qualified-id for the member
5186 // name shall be a simple-template-id.
5188 // C++98 has the same restriction, just worded differently.
5189 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
5190 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
5191 D.getCXXScopeSpec().isSet() &&
5192 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5193 Diag(D.getIdentifierLoc(),
5194 diag::ext_explicit_instantiation_without_qualified_id)
5195 << Specialization << D.getCXXScopeSpec().getRange();
5197 CheckExplicitInstantiationScope(*this,
5198 FunTmpl? (NamedDecl *)FunTmpl
5199 : Specialization->getInstantiatedFromMemberFunction(),
5200 D.getIdentifierLoc(),
5201 D.getCXXScopeSpec().isSet());
5203 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5204 return (Decl*) 0;
5207 TypeResult
5208 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5209 const CXXScopeSpec &SS, IdentifierInfo *Name,
5210 SourceLocation TagLoc, SourceLocation NameLoc) {
5211 // This has to hold, because SS is expected to be defined.
5212 assert(Name && "Expected a name in a dependent tag");
5214 NestedNameSpecifier *NNS
5215 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5216 if (!NNS)
5217 return true;
5219 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5221 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5222 Diag(NameLoc, diag::err_dependent_tag_decl)
5223 << (TUK == TUK_Definition) << Kind << SS.getRange();
5224 return true;
5227 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5228 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
5231 TypeResult
5232 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5233 const CXXScopeSpec &SS, const IdentifierInfo &II,
5234 SourceLocation IdLoc) {
5235 NestedNameSpecifier *NNS
5236 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5237 if (!NNS)
5238 return true;
5240 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5241 !getLangOptions().CPlusPlus0x)
5242 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5243 << FixItHint::CreateRemoval(TypenameLoc);
5245 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
5246 TypenameLoc, SS.getRange(), IdLoc);
5247 if (T.isNull())
5248 return true;
5250 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5251 if (isa<DependentNameType>(T)) {
5252 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5253 TL.setKeywordLoc(TypenameLoc);
5254 TL.setQualifierRange(SS.getRange());
5255 TL.setNameLoc(IdLoc);
5256 } else {
5257 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
5258 TL.setKeywordLoc(TypenameLoc);
5259 TL.setQualifierRange(SS.getRange());
5260 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
5263 return CreateParsedType(T, TSI);
5266 TypeResult
5267 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5268 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
5269 ParsedType Ty) {
5270 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5271 !getLangOptions().CPlusPlus0x)
5272 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5273 << FixItHint::CreateRemoval(TypenameLoc);
5275 TypeSourceInfo *InnerTSI = 0;
5276 QualType T = GetTypeFromParser(Ty, &InnerTSI);
5278 assert(isa<TemplateSpecializationType>(T) &&
5279 "Expected a template specialization type");
5281 if (computeDeclContext(SS, false)) {
5282 // If we can compute a declaration context, then the "typename"
5283 // keyword was superfluous. Just build an ElaboratedType to keep
5284 // track of the nested-name-specifier.
5286 // Push the inner type, preserving its source locations if possible.
5287 TypeLocBuilder Builder;
5288 if (InnerTSI)
5289 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5290 else
5291 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5293 /* Note: NNS already embedded in template specialization type T. */
5294 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
5295 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5296 TL.setKeywordLoc(TypenameLoc);
5297 TL.setQualifierRange(SS.getRange());
5299 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
5300 return CreateParsedType(T, TSI);
5303 // TODO: it's really silly that we make a template specialization
5304 // type earlier only to drop it again here.
5305 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5306 DependentTemplateName *DTN =
5307 TST->getTemplateName().getAsDependentTemplateName();
5308 assert(DTN && "dependent template has non-dependent name?");
5309 assert(DTN->getQualifier()
5310 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5311 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5312 DTN->getQualifier(),
5313 DTN->getIdentifier(),
5314 TST->getNumArgs(),
5315 TST->getArgs());
5316 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5317 DependentTemplateSpecializationTypeLoc TL =
5318 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5319 if (InnerTSI) {
5320 TemplateSpecializationTypeLoc TSTL =
5321 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5322 TL.setLAngleLoc(TSTL.getLAngleLoc());
5323 TL.setRAngleLoc(TSTL.getRAngleLoc());
5324 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5325 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5326 } else {
5327 TL.initializeLocal(SourceLocation());
5329 TL.setKeywordLoc(TypenameLoc);
5330 TL.setQualifierRange(SS.getRange());
5331 return CreateParsedType(T, TSI);
5334 /// \brief Build the type that describes a C++ typename specifier,
5335 /// e.g., "typename T::type".
5336 QualType
5337 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5338 NestedNameSpecifier *NNS, const IdentifierInfo &II,
5339 SourceLocation KeywordLoc, SourceRange NNSRange,
5340 SourceLocation IILoc) {
5341 CXXScopeSpec SS;
5342 SS.setScopeRep(NNS);
5343 SS.setRange(NNSRange);
5345 DeclContext *Ctx = computeDeclContext(SS);
5346 if (!Ctx) {
5347 // If the nested-name-specifier is dependent and couldn't be
5348 // resolved to a type, build a typename type.
5349 assert(NNS->isDependent());
5350 return Context.getDependentNameType(Keyword, NNS, &II);
5353 // If the nested-name-specifier refers to the current instantiation,
5354 // the "typename" keyword itself is superfluous. In C++03, the
5355 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5356 // allows such extraneous "typename" keywords, and we retroactively
5357 // apply this DR to C++03 code with only a warning. In any case we continue.
5359 if (RequireCompleteDeclContext(SS, Ctx))
5360 return QualType();
5362 DeclarationName Name(&II);
5363 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
5364 LookupQualifiedName(Result, Ctx);
5365 unsigned DiagID = 0;
5366 Decl *Referenced = 0;
5367 switch (Result.getResultKind()) {
5368 case LookupResult::NotFound:
5369 DiagID = diag::err_typename_nested_not_found;
5370 break;
5372 case LookupResult::NotFoundInCurrentInstantiation:
5373 // Okay, it's a member of an unknown instantiation.
5374 return Context.getDependentNameType(Keyword, NNS, &II);
5376 case LookupResult::Found:
5377 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
5378 // We found a type. Build an ElaboratedType, since the
5379 // typename-specifier was just sugar.
5380 return Context.getElaboratedType(ETK_Typename, NNS,
5381 Context.getTypeDeclType(Type));
5384 DiagID = diag::err_typename_nested_not_type;
5385 Referenced = Result.getFoundDecl();
5386 break;
5388 case LookupResult::FoundUnresolvedValue:
5389 llvm_unreachable("unresolved using decl in non-dependent context");
5390 return QualType();
5392 case LookupResult::FoundOverloaded:
5393 DiagID = diag::err_typename_nested_not_type;
5394 Referenced = *Result.begin();
5395 break;
5397 case LookupResult::Ambiguous:
5398 return QualType();
5401 // If we get here, it's because name lookup did not find a
5402 // type. Emit an appropriate diagnostic and return an error.
5403 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5404 IILoc);
5405 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
5406 if (Referenced)
5407 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5408 << Name;
5409 return QualType();
5412 namespace {
5413 // See Sema::RebuildTypeInCurrentInstantiation
5414 class CurrentInstantiationRebuilder
5415 : public TreeTransform<CurrentInstantiationRebuilder> {
5416 SourceLocation Loc;
5417 DeclarationName Entity;
5419 public:
5420 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5422 CurrentInstantiationRebuilder(Sema &SemaRef,
5423 SourceLocation Loc,
5424 DeclarationName Entity)
5425 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
5426 Loc(Loc), Entity(Entity) { }
5428 /// \brief Determine whether the given type \p T has already been
5429 /// transformed.
5431 /// For the purposes of type reconstruction, a type has already been
5432 /// transformed if it is NULL or if it is not dependent.
5433 bool AlreadyTransformed(QualType T) {
5434 return T.isNull() || !T->isDependentType();
5437 /// \brief Returns the location of the entity whose type is being
5438 /// rebuilt.
5439 SourceLocation getBaseLocation() { return Loc; }
5441 /// \brief Returns the name of the entity whose type is being rebuilt.
5442 DeclarationName getBaseEntity() { return Entity; }
5444 /// \brief Sets the "base" location and entity when that
5445 /// information is known based on another transformation.
5446 void setBase(SourceLocation Loc, DeclarationName Entity) {
5447 this->Loc = Loc;
5448 this->Entity = Entity;
5453 /// \brief Rebuilds a type within the context of the current instantiation.
5455 /// The type \p T is part of the type of an out-of-line member definition of
5456 /// a class template (or class template partial specialization) that was parsed
5457 /// and constructed before we entered the scope of the class template (or
5458 /// partial specialization thereof). This routine will rebuild that type now
5459 /// that we have entered the declarator's scope, which may produce different
5460 /// canonical types, e.g.,
5462 /// \code
5463 /// template<typename T>
5464 /// struct X {
5465 /// typedef T* pointer;
5466 /// pointer data();
5467 /// };
5469 /// template<typename T>
5470 /// typename X<T>::pointer X<T>::data() { ... }
5471 /// \endcode
5473 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
5474 /// since we do not know that we can look into X<T> when we parsed the type.
5475 /// This function will rebuild the type, performing the lookup of "pointer"
5476 /// in X<T> and returning an ElaboratedType whose canonical type is the same
5477 /// as the canonical type of T*, allowing the return types of the out-of-line
5478 /// definition and the declaration to match.
5479 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5480 SourceLocation Loc,
5481 DeclarationName Name) {
5482 if (!T || !T->getType()->isDependentType())
5483 return T;
5485 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5486 return Rebuilder.TransformType(T);
5489 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
5490 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5491 DeclarationName());
5492 return Rebuilder.TransformExpr(E);
5495 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5496 if (SS.isInvalid()) return true;
5498 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5499 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5500 DeclarationName());
5501 NestedNameSpecifier *Rebuilt =
5502 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
5503 if (!Rebuilt) return true;
5505 SS.setScopeRep(Rebuilt);
5506 return false;
5509 /// \brief Produces a formatted string that describes the binding of
5510 /// template parameters to template arguments.
5511 std::string
5512 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5513 const TemplateArgumentList &Args) {
5514 // FIXME: For variadic templates, we'll need to get the structured list.
5515 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5516 Args.flat_size());
5519 std::string
5520 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5521 const TemplateArgument *Args,
5522 unsigned NumArgs) {
5523 std::string Result;
5525 if (!Params || Params->size() == 0 || NumArgs == 0)
5526 return Result;
5528 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5529 if (I >= NumArgs)
5530 break;
5532 if (I == 0)
5533 Result += "[with ";
5534 else
5535 Result += ", ";
5537 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5538 Result += Id->getName();
5539 } else {
5540 Result += '$';
5541 Result += llvm::utostr(I);
5544 Result += " = ";
5546 switch (Args[I].getKind()) {
5547 case TemplateArgument::Null:
5548 Result += "<no value>";
5549 break;
5551 case TemplateArgument::Type: {
5552 std::string TypeStr;
5553 Args[I].getAsType().getAsStringInternal(TypeStr,
5554 Context.PrintingPolicy);
5555 Result += TypeStr;
5556 break;
5559 case TemplateArgument::Declaration: {
5560 bool Unnamed = true;
5561 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5562 if (ND->getDeclName()) {
5563 Unnamed = false;
5564 Result += ND->getNameAsString();
5568 if (Unnamed) {
5569 Result += "<anonymous>";
5571 break;
5574 case TemplateArgument::Template: {
5575 std::string Str;
5576 llvm::raw_string_ostream OS(Str);
5577 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5578 Result += OS.str();
5579 break;
5582 case TemplateArgument::Integral: {
5583 Result += Args[I].getAsIntegral()->toString(10);
5584 break;
5587 case TemplateArgument::Expression: {
5588 // FIXME: This is non-optimal, since we're regurgitating the
5589 // expression we were given.
5590 std::string Str;
5592 llvm::raw_string_ostream OS(Str);
5593 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5594 Context.PrintingPolicy);
5596 Result += Str;
5597 break;
5600 case TemplateArgument::Pack:
5601 // FIXME: Format template argument packs
5602 Result += "<template argument pack>";
5603 break;
5607 Result += ']';
5608 return Result;