SemaTemplate.cpp revision 26416068d3eb883a280fdceeffa74fffc9131031
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//===----------------------------------------------------------------------===/ 11 12#include "Sema.h" 13#include "Lookup.h" 14#include "TreeTransform.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/Expr.h" 17#include "clang/AST/ExprCXX.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/Parse/DeclSpec.h" 20#include "clang/Parse/Template.h" 21#include "clang/Basic/LangOptions.h" 22#include "clang/Basic/PartialDiagnostic.h" 23#include "llvm/Support/Compiler.h" 24#include "llvm/ADT/StringExtras.h" 25using namespace clang; 26 27/// \brief Determine whether the declaration found is acceptable as the name 28/// of a template and, if so, return that template declaration. Otherwise, 29/// returns NULL. 30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) { 31 if (!D) 32 return 0; 33 34 if (isa<TemplateDecl>(D)) 35 return D; 36 37 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 38 // C++ [temp.local]p1: 39 // Like normal (non-template) classes, class templates have an 40 // injected-class-name (Clause 9). The injected-class-name 41 // can be used with or without a template-argument-list. When 42 // it is used without a template-argument-list, it is 43 // equivalent to the injected-class-name followed by the 44 // template-parameters of the class template enclosed in 45 // <>. When it is used with a template-argument-list, it 46 // refers to the specified class template specialization, 47 // which could be the current specialization or another 48 // specialization. 49 if (Record->isInjectedClassName()) { 50 Record = cast<CXXRecordDecl>(Record->getDeclContext()); 51 if (Record->getDescribedClassTemplate()) 52 return Record->getDescribedClassTemplate(); 53 54 if (ClassTemplateSpecializationDecl *Spec 55 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) 56 return Spec->getSpecializedTemplate(); 57 } 58 59 return 0; 60 } 61 62 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D); 63 if (!Ovl) 64 return 0; 65 66 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 67 FEnd = Ovl->function_end(); 68 F != FEnd; ++F) { 69 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) { 70 // We've found a function template. Determine whether there are 71 // any other function templates we need to bundle together in an 72 // OverloadedFunctionDecl 73 for (++F; F != FEnd; ++F) { 74 if (isa<FunctionTemplateDecl>(*F)) 75 break; 76 } 77 78 if (F != FEnd) { 79 // Build an overloaded function decl containing only the 80 // function templates in Ovl. 81 OverloadedFunctionDecl *OvlTemplate 82 = OverloadedFunctionDecl::Create(Context, 83 Ovl->getDeclContext(), 84 Ovl->getDeclName()); 85 OvlTemplate->addOverload(FuncTmpl); 86 OvlTemplate->addOverload(*F); 87 for (++F; F != FEnd; ++F) { 88 if (isa<FunctionTemplateDecl>(*F)) 89 OvlTemplate->addOverload(*F); 90 } 91 92 return OvlTemplate; 93 } 94 95 return FuncTmpl; 96 } 97 } 98 99 return 0; 100} 101 102static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) { 103 LookupResult::Filter filter = R.makeFilter(); 104 while (filter.hasNext()) { 105 NamedDecl *Orig = filter.next(); 106 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl()); 107 if (!Repl) 108 filter.erase(); 109 else if (Repl != Orig) 110 filter.replace(Repl); 111 } 112 filter.done(); 113} 114 115TemplateNameKind Sema::isTemplateName(Scope *S, 116 const CXXScopeSpec &SS, 117 UnqualifiedId &Name, 118 TypeTy *ObjectTypePtr, 119 bool EnteringContext, 120 TemplateTy &TemplateResult) { 121 DeclarationName TName; 122 123 switch (Name.getKind()) { 124 case UnqualifiedId::IK_Identifier: 125 TName = DeclarationName(Name.Identifier); 126 break; 127 128 case UnqualifiedId::IK_OperatorFunctionId: 129 TName = Context.DeclarationNames.getCXXOperatorName( 130 Name.OperatorFunctionId.Operator); 131 break; 132 133 default: 134 return TNK_Non_template; 135 } 136 137 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr); 138 139 LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName); 140 R.suppressDiagnostics(); 141 LookupTemplateName(R, S, SS, ObjectType, EnteringContext); 142 if (R.empty()) 143 return TNK_Non_template; 144 145 NamedDecl *Template = R.getAsSingleDecl(Context); 146 147 if (SS.isSet() && !SS.isInvalid()) { 148 NestedNameSpecifier *Qualifier 149 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 150 if (OverloadedFunctionDecl *Ovl 151 = dyn_cast<OverloadedFunctionDecl>(Template)) 152 TemplateResult 153 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false, 154 Ovl)); 155 else 156 TemplateResult 157 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false, 158 cast<TemplateDecl>(Template))); 159 } else if (OverloadedFunctionDecl *Ovl 160 = dyn_cast<OverloadedFunctionDecl>(Template)) { 161 TemplateResult = TemplateTy::make(TemplateName(Ovl)); 162 } else { 163 TemplateResult = TemplateTy::make( 164 TemplateName(cast<TemplateDecl>(Template))); 165 } 166 167 if (isa<ClassTemplateDecl>(Template) || 168 isa<TemplateTemplateParmDecl>(Template)) 169 return TNK_Type_template; 170 171 assert((isa<FunctionTemplateDecl>(Template) || 172 isa<OverloadedFunctionDecl>(Template)) && 173 "Unhandled template kind in Sema::isTemplateName"); 174 return TNK_Function_template; 175} 176 177void Sema::LookupTemplateName(LookupResult &Found, 178 Scope *S, const CXXScopeSpec &SS, 179 QualType ObjectType, 180 bool EnteringContext) { 181 // Determine where to perform name lookup 182 DeclContext *LookupCtx = 0; 183 bool isDependent = false; 184 if (!ObjectType.isNull()) { 185 // This nested-name-specifier occurs in a member access expression, e.g., 186 // x->B::f, and we are looking into the type of the object. 187 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 188 LookupCtx = computeDeclContext(ObjectType); 189 isDependent = ObjectType->isDependentType(); 190 assert((isDependent || !ObjectType->isIncompleteType()) && 191 "Caller should have completed object type"); 192 } else if (SS.isSet()) { 193 // This nested-name-specifier occurs after another nested-name-specifier, 194 // so long into the context associated with the prior nested-name-specifier. 195 LookupCtx = computeDeclContext(SS, EnteringContext); 196 isDependent = isDependentScopeSpecifier(SS); 197 198 // The declaration context must be complete. 199 if (LookupCtx && RequireCompleteDeclContext(SS)) 200 return; 201 } 202 203 bool ObjectTypeSearchedInScope = false; 204 if (LookupCtx) { 205 // Perform "qualified" name lookup into the declaration context we 206 // computed, which is either the type of the base of a member access 207 // expression or the declaration context associated with a prior 208 // nested-name-specifier. 209 LookupQualifiedName(Found, LookupCtx); 210 211 if (!ObjectType.isNull() && Found.empty()) { 212 // C++ [basic.lookup.classref]p1: 213 // In a class member access expression (5.2.5), if the . or -> token is 214 // immediately followed by an identifier followed by a <, the 215 // identifier must be looked up to determine whether the < is the 216 // beginning of a template argument list (14.2) or a less-than operator. 217 // The identifier is first looked up in the class of the object 218 // expression. If the identifier is not found, it is then looked up in 219 // the context of the entire postfix-expression and shall name a class 220 // or function template. 221 // 222 // FIXME: When we're instantiating a template, do we actually have to 223 // look in the scope of the template? Seems fishy... 224 if (S) LookupName(Found, S); 225 ObjectTypeSearchedInScope = true; 226 } 227 } else if (isDependent) { 228 // We cannot look into a dependent object type or 229 return; 230 } else { 231 // Perform unqualified name lookup in the current scope. 232 LookupName(Found, S); 233 } 234 235 // FIXME: Cope with ambiguous name-lookup results. 236 assert(!Found.isAmbiguous() && 237 "Cannot handle template name-lookup ambiguities"); 238 239 FilterAcceptableTemplateNames(Context, Found); 240 if (Found.empty()) 241 return; 242 243 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) { 244 // C++ [basic.lookup.classref]p1: 245 // [...] If the lookup in the class of the object expression finds a 246 // template, the name is also looked up in the context of the entire 247 // postfix-expression and [...] 248 // 249 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), 250 LookupOrdinaryName); 251 LookupName(FoundOuter, S); 252 FilterAcceptableTemplateNames(Context, FoundOuter); 253 // FIXME: Handle ambiguities in this lookup better 254 255 if (FoundOuter.empty()) { 256 // - if the name is not found, the name found in the class of the 257 // object expression is used, otherwise 258 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) { 259 // - if the name is found in the context of the entire 260 // postfix-expression and does not name a class template, the name 261 // found in the class of the object expression is used, otherwise 262 } else { 263 // - if the name found is a class template, it must refer to the same 264 // entity as the one found in the class of the object expression, 265 // otherwise the program is ill-formed. 266 if (!Found.isSingleResult() || 267 Found.getFoundDecl()->getCanonicalDecl() 268 != FoundOuter.getFoundDecl()->getCanonicalDecl()) { 269 Diag(Found.getNameLoc(), 270 diag::err_nested_name_member_ref_lookup_ambiguous) 271 << Found.getLookupName(); 272 Diag(Found.getRepresentativeDecl()->getLocation(), 273 diag::note_ambig_member_ref_object_type) 274 << ObjectType; 275 Diag(FoundOuter.getFoundDecl()->getLocation(), 276 diag::note_ambig_member_ref_scope); 277 278 // Recover by taking the template that we found in the object 279 // expression's type. 280 } 281 } 282 } 283} 284 285/// Constructs a full type for the given nested-name-specifier. 286static QualType GetTypeForQualifier(ASTContext &Context, 287 NestedNameSpecifier *Qualifier) { 288 // Three possibilities: 289 290 // 1. A namespace (global or not). 291 assert(!Qualifier->getAsNamespace() && "can't construct type for namespace"); 292 293 // 2. A type (templated or not). 294 Type *Ty = Qualifier->getAsType(); 295 if (Ty) return QualType(Ty, 0); 296 297 // 3. A dependent identifier. 298 assert(Qualifier->getAsIdentifier()); 299 return Context.getTypenameType(Qualifier->getPrefix(), 300 Qualifier->getAsIdentifier()); 301} 302 303static bool HasDependentTypeAsBase(ASTContext &Context, 304 CXXRecordDecl *Record, 305 CanQualType T) { 306 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(), 307 E = Record->bases_end(); I != E; ++I) { 308 CanQualType BaseT = Context.getCanonicalType((*I).getType()); 309 if (BaseT == T) 310 return true; 311 312 // We have to recurse here to cover some really bizarre cases. 313 // Obviously, we can only have the dependent type as an indirect 314 // base class through a dependent base class, and usually it's 315 // impossible to know which instantiation a dependent base class 316 // will have. But! If we're actually *inside* the dependent base 317 // class, then we know its instantiation and can therefore be 318 // reasonably expected to look into it. 319 320 // template <class T> class A : Base<T> { 321 // class Inner : A<T> { 322 // void foo() { 323 // Base<T>::foo(); // statically known to be an implicit member 324 // reference 325 // } 326 // }; 327 // }; 328 329 CanQual<RecordType> RT = BaseT->getAs<RecordType>(); 330 331 // Base might be a dependent member type, in which case we 332 // obviously can't look into it. 333 if (!RT) continue; 334 335 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(RT->getDecl()); 336 if (BaseRecord->isDefinition() && 337 HasDependentTypeAsBase(Context, BaseRecord, T)) 338 return true; 339 } 340 341 return false; 342} 343 344/// Checks whether the given dependent nested-name specifier 345/// introduces an implicit member reference. This is only true if the 346/// nested-name specifier names a type identical to one of the current 347/// instance method's context's (possibly indirect) base classes. 348static bool IsImplicitDependentMemberReference(Sema &SemaRef, 349 NestedNameSpecifier *Qualifier, 350 QualType &ThisType) { 351 // If the context isn't a C++ method, then it isn't an implicit 352 // member reference. 353 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext); 354 if (!MD || MD->isStatic()) 355 return false; 356 357 ASTContext &Context = SemaRef.Context; 358 359 // We want to check whether the method's context is known to inherit 360 // from the type named by the nested name specifier. The trivial 361 // case here is: 362 // template <class T> class Base { ... }; 363 // template <class T> class Derived : Base<T> { 364 // void foo() { 365 // Base<T>::foo(); 366 // } 367 // }; 368 369 QualType QT = GetTypeForQualifier(Context, Qualifier); 370 CanQualType T = Context.getCanonicalType(QT); 371 372 // And now, just walk the non-dependent type hierarchy, trying to 373 // find the given type as a literal base class. 374 CXXRecordDecl *Record = cast<CXXRecordDecl>(MD->getParent()); 375 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T || 376 HasDependentTypeAsBase(Context, Record, T)) { 377 ThisType = MD->getThisType(Context); 378 return true; 379 } 380 381 return false; 382} 383 384/// ActOnDependentIdExpression - Handle a dependent declaration name 385/// that was just parsed. 386Sema::OwningExprResult 387Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, 388 DeclarationName Name, 389 SourceLocation NameLoc, 390 bool CheckForImplicitMember, 391 const TemplateArgumentListInfo *TemplateArgs) { 392 NestedNameSpecifier *Qualifier 393 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 394 395 QualType ThisType; 396 if (CheckForImplicitMember && 397 IsImplicitDependentMemberReference(*this, Qualifier, ThisType)) { 398 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType); 399 400 // Since the 'this' expression is synthesized, we don't need to 401 // perform the double-lookup check. 402 NamedDecl *FirstQualifierInScope = 0; 403 404 return Owned(CXXDependentScopeMemberExpr::Create(Context, This, true, 405 /*Op*/ SourceLocation(), 406 Qualifier, SS.getRange(), 407 FirstQualifierInScope, 408 Name, NameLoc, 409 TemplateArgs)); 410 } 411 412 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs); 413} 414 415Sema::OwningExprResult 416Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 417 DeclarationName Name, 418 SourceLocation NameLoc, 419 const TemplateArgumentListInfo *TemplateArgs) { 420 return Owned(DependentScopeDeclRefExpr::Create(Context, 421 static_cast<NestedNameSpecifier*>(SS.getScopeRep()), 422 SS.getRange(), 423 Name, NameLoc, 424 TemplateArgs)); 425} 426 427/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 428/// that the template parameter 'PrevDecl' is being shadowed by a new 429/// declaration at location Loc. Returns true to indicate that this is 430/// an error, and false otherwise. 431bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 432 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 433 434 // Microsoft Visual C++ permits template parameters to be shadowed. 435 if (getLangOptions().Microsoft) 436 return false; 437 438 // C++ [temp.local]p4: 439 // A template-parameter shall not be redeclared within its 440 // scope (including nested scopes). 441 Diag(Loc, diag::err_template_param_shadow) 442 << cast<NamedDecl>(PrevDecl)->getDeclName(); 443 Diag(PrevDecl->getLocation(), diag::note_template_param_here); 444 return true; 445} 446 447/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 448/// the parameter D to reference the templated declaration and return a pointer 449/// to the template declaration. Otherwise, do nothing to D and return null. 450TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) { 451 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) { 452 D = DeclPtrTy::make(Temp->getTemplatedDecl()); 453 return Temp; 454 } 455 return 0; 456} 457 458static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, 459 const ParsedTemplateArgument &Arg) { 460 461 switch (Arg.getKind()) { 462 case ParsedTemplateArgument::Type: { 463 DeclaratorInfo *DI; 464 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); 465 if (!DI) 466 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation()); 467 return TemplateArgumentLoc(TemplateArgument(T), DI); 468 } 469 470 case ParsedTemplateArgument::NonType: { 471 Expr *E = static_cast<Expr *>(Arg.getAsExpr()); 472 return TemplateArgumentLoc(TemplateArgument(E), E); 473 } 474 475 case ParsedTemplateArgument::Template: { 476 TemplateName Template 477 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get()); 478 return TemplateArgumentLoc(TemplateArgument(Template), 479 Arg.getScopeSpec().getRange(), 480 Arg.getLocation()); 481 } 482 } 483 484 llvm::llvm_unreachable("Unhandled parsed template argument"); 485 return TemplateArgumentLoc(); 486} 487 488/// \brief Translates template arguments as provided by the parser 489/// into template arguments used by semantic analysis. 490void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, 491 TemplateArgumentListInfo &TemplateArgs) { 492 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) 493 TemplateArgs.addArgument(translateTemplateArgument(*this, 494 TemplateArgsIn[I])); 495} 496 497/// ActOnTypeParameter - Called when a C++ template type parameter 498/// (e.g., "typename T") has been parsed. Typename specifies whether 499/// the keyword "typename" was used to declare the type parameter 500/// (otherwise, "class" was used), and KeyLoc is the location of the 501/// "class" or "typename" keyword. ParamName is the name of the 502/// parameter (NULL indicates an unnamed template parameter) and 503/// ParamName is the location of the parameter name (if any). 504/// If the type parameter has a default argument, it will be added 505/// later via ActOnTypeParameterDefault. 506Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 507 SourceLocation EllipsisLoc, 508 SourceLocation KeyLoc, 509 IdentifierInfo *ParamName, 510 SourceLocation ParamNameLoc, 511 unsigned Depth, unsigned Position) { 512 assert(S->isTemplateParamScope() && 513 "Template type parameter not in template parameter scope!"); 514 bool Invalid = false; 515 516 if (ParamName) { 517 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName); 518 if (PrevDecl && PrevDecl->isTemplateParameter()) 519 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc, 520 PrevDecl); 521 } 522 523 SourceLocation Loc = ParamNameLoc; 524 if (!ParamName) 525 Loc = KeyLoc; 526 527 TemplateTypeParmDecl *Param 528 = TemplateTypeParmDecl::Create(Context, CurContext, Loc, 529 Depth, Position, ParamName, Typename, 530 Ellipsis); 531 if (Invalid) 532 Param->setInvalidDecl(); 533 534 if (ParamName) { 535 // Add the template parameter into the current scope. 536 S->AddDecl(DeclPtrTy::make(Param)); 537 IdResolver.AddDecl(Param); 538 } 539 540 return DeclPtrTy::make(Param); 541} 542 543/// ActOnTypeParameterDefault - Adds a default argument (the type 544/// Default) to the given template type parameter (TypeParam). 545void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam, 546 SourceLocation EqualLoc, 547 SourceLocation DefaultLoc, 548 TypeTy *DefaultT) { 549 TemplateTypeParmDecl *Parm 550 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>()); 551 552 DeclaratorInfo *DefaultDInfo; 553 GetTypeFromParser(DefaultT, &DefaultDInfo); 554 555 assert(DefaultDInfo && "expected source information for type"); 556 557 // C++0x [temp.param]p9: 558 // A default template-argument may be specified for any kind of 559 // template-parameter that is not a template parameter pack. 560 if (Parm->isParameterPack()) { 561 Diag(DefaultLoc, diag::err_template_param_pack_default_arg); 562 return; 563 } 564 565 // C++ [temp.param]p14: 566 // A template-parameter shall not be used in its own default argument. 567 // FIXME: Implement this check! Needs a recursive walk over the types. 568 569 // Check the template argument itself. 570 if (CheckTemplateArgument(Parm, DefaultDInfo)) { 571 Parm->setInvalidDecl(); 572 return; 573 } 574 575 Parm->setDefaultArgument(DefaultDInfo, false); 576} 577 578/// \brief Check that the type of a non-type template parameter is 579/// well-formed. 580/// 581/// \returns the (possibly-promoted) parameter type if valid; 582/// otherwise, produces a diagnostic and returns a NULL type. 583QualType 584Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) { 585 // C++ [temp.param]p4: 586 // 587 // A non-type template-parameter shall have one of the following 588 // (optionally cv-qualified) types: 589 // 590 // -- integral or enumeration type, 591 if (T->isIntegralType() || T->isEnumeralType() || 592 // -- pointer to object or pointer to function, 593 (T->isPointerType() && 594 (T->getAs<PointerType>()->getPointeeType()->isObjectType() || 595 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) || 596 // -- reference to object or reference to function, 597 T->isReferenceType() || 598 // -- pointer to member. 599 T->isMemberPointerType() || 600 // If T is a dependent type, we can't do the check now, so we 601 // assume that it is well-formed. 602 T->isDependentType()) 603 return T; 604 // C++ [temp.param]p8: 605 // 606 // A non-type template-parameter of type "array of T" or 607 // "function returning T" is adjusted to be of type "pointer to 608 // T" or "pointer to function returning T", respectively. 609 else if (T->isArrayType()) 610 // FIXME: Keep the type prior to promotion? 611 return Context.getArrayDecayedType(T); 612 else if (T->isFunctionType()) 613 // FIXME: Keep the type prior to promotion? 614 return Context.getPointerType(T); 615 616 Diag(Loc, diag::err_template_nontype_parm_bad_type) 617 << T; 618 619 return QualType(); 620} 621 622/// ActOnNonTypeTemplateParameter - Called when a C++ non-type 623/// template parameter (e.g., "int Size" in "template<int Size> 624/// class Array") has been parsed. S is the current scope and D is 625/// the parsed declarator. 626Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 627 unsigned Depth, 628 unsigned Position) { 629 DeclaratorInfo *DInfo = 0; 630 QualType T = GetTypeForDeclarator(D, S, &DInfo); 631 632 assert(S->isTemplateParamScope() && 633 "Non-type template parameter not in template parameter scope!"); 634 bool Invalid = false; 635 636 IdentifierInfo *ParamName = D.getIdentifier(); 637 if (ParamName) { 638 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName); 639 if (PrevDecl && PrevDecl->isTemplateParameter()) 640 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 641 PrevDecl); 642 } 643 644 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc()); 645 if (T.isNull()) { 646 T = Context.IntTy; // Recover with an 'int' type. 647 Invalid = true; 648 } 649 650 NonTypeTemplateParmDecl *Param 651 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(), 652 Depth, Position, ParamName, T, DInfo); 653 if (Invalid) 654 Param->setInvalidDecl(); 655 656 if (D.getIdentifier()) { 657 // Add the template parameter into the current scope. 658 S->AddDecl(DeclPtrTy::make(Param)); 659 IdResolver.AddDecl(Param); 660 } 661 return DeclPtrTy::make(Param); 662} 663 664/// \brief Adds a default argument to the given non-type template 665/// parameter. 666void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD, 667 SourceLocation EqualLoc, 668 ExprArg DefaultE) { 669 NonTypeTemplateParmDecl *TemplateParm 670 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>()); 671 Expr *Default = static_cast<Expr *>(DefaultE.get()); 672 673 // C++ [temp.param]p14: 674 // A template-parameter shall not be used in its own default argument. 675 // FIXME: Implement this check! Needs a recursive walk over the types. 676 677 // Check the well-formedness of the default template argument. 678 TemplateArgument Converted; 679 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default, 680 Converted)) { 681 TemplateParm->setInvalidDecl(); 682 return; 683 } 684 685 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>()); 686} 687 688 689/// ActOnTemplateTemplateParameter - Called when a C++ template template 690/// parameter (e.g. T in template <template <typename> class T> class array) 691/// has been parsed. S is the current scope. 692Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S, 693 SourceLocation TmpLoc, 694 TemplateParamsTy *Params, 695 IdentifierInfo *Name, 696 SourceLocation NameLoc, 697 unsigned Depth, 698 unsigned Position) { 699 assert(S->isTemplateParamScope() && 700 "Template template parameter not in template parameter scope!"); 701 702 // Construct the parameter object. 703 TemplateTemplateParmDecl *Param = 704 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth, 705 Position, Name, 706 (TemplateParameterList*)Params); 707 708 // Make sure the parameter is valid. 709 // FIXME: Decl object is not currently invalidated anywhere so this doesn't 710 // do anything yet. However, if the template parameter list or (eventual) 711 // default value is ever invalidated, that will propagate here. 712 bool Invalid = false; 713 if (Invalid) { 714 Param->setInvalidDecl(); 715 } 716 717 // If the tt-param has a name, then link the identifier into the scope 718 // and lookup mechanisms. 719 if (Name) { 720 S->AddDecl(DeclPtrTy::make(Param)); 721 IdResolver.AddDecl(Param); 722 } 723 724 return DeclPtrTy::make(Param); 725} 726 727/// \brief Adds a default argument to the given template template 728/// parameter. 729void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD, 730 SourceLocation EqualLoc, 731 const ParsedTemplateArgument &Default) { 732 TemplateTemplateParmDecl *TemplateParm 733 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>()); 734 735 // C++ [temp.param]p14: 736 // A template-parameter shall not be used in its own default argument. 737 // FIXME: Implement this check! Needs a recursive walk over the types. 738 739 // Check only that we have a template template argument. We don't want to 740 // try to check well-formedness now, because our template template parameter 741 // might have dependent types in its template parameters, which we wouldn't 742 // be able to match now. 743 // 744 // If none of the template template parameter's template arguments mention 745 // other template parameters, we could actually perform more checking here. 746 // However, it isn't worth doing. 747 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); 748 if (DefaultArg.getArgument().getAsTemplate().isNull()) { 749 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template) 750 << DefaultArg.getSourceRange(); 751 return; 752 } 753 754 TemplateParm->setDefaultArgument(DefaultArg); 755} 756 757/// ActOnTemplateParameterList - Builds a TemplateParameterList that 758/// contains the template parameters in Params/NumParams. 759Sema::TemplateParamsTy * 760Sema::ActOnTemplateParameterList(unsigned Depth, 761 SourceLocation ExportLoc, 762 SourceLocation TemplateLoc, 763 SourceLocation LAngleLoc, 764 DeclPtrTy *Params, unsigned NumParams, 765 SourceLocation RAngleLoc) { 766 if (ExportLoc.isValid()) 767 Diag(ExportLoc, diag::note_template_export_unsupported); 768 769 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, 770 (NamedDecl**)Params, NumParams, 771 RAngleLoc); 772} 773 774Sema::DeclResult 775Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 776 SourceLocation KWLoc, const CXXScopeSpec &SS, 777 IdentifierInfo *Name, SourceLocation NameLoc, 778 AttributeList *Attr, 779 TemplateParameterList *TemplateParams, 780 AccessSpecifier AS) { 781 assert(TemplateParams && TemplateParams->size() > 0 && 782 "No template parameters"); 783 assert(TUK != TUK_Reference && "Can only declare or define class templates"); 784 bool Invalid = false; 785 786 // Check that we can declare a template here. 787 if (CheckTemplateDeclScope(S, TemplateParams)) 788 return true; 789 790 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec); 791 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type"); 792 793 // There is no such thing as an unnamed class template. 794 if (!Name) { 795 Diag(KWLoc, diag::err_template_unnamed_class); 796 return true; 797 } 798 799 // Find any previous declaration with this name. 800 DeclContext *SemanticContext; 801 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName, 802 ForRedeclaration); 803 if (SS.isNotEmpty() && !SS.isInvalid()) { 804 if (RequireCompleteDeclContext(SS)) 805 return true; 806 807 SemanticContext = computeDeclContext(SS, true); 808 if (!SemanticContext) { 809 // FIXME: Produce a reasonable diagnostic here 810 return true; 811 } 812 813 LookupQualifiedName(Previous, SemanticContext); 814 } else { 815 SemanticContext = CurContext; 816 LookupName(Previous, S); 817 } 818 819 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?"); 820 NamedDecl *PrevDecl = 0; 821 if (Previous.begin() != Previous.end()) 822 PrevDecl = *Previous.begin(); 823 824 if (PrevDecl && TUK == TUK_Friend) { 825 // C++ [namespace.memdef]p3: 826 // [...] When looking for a prior declaration of a class or a function 827 // declared as a friend, and when the name of the friend class or 828 // function is neither a qualified name nor a template-id, scopes outside 829 // the innermost enclosing namespace scope are not considered. 830 DeclContext *OutermostContext = CurContext; 831 while (!OutermostContext->isFileContext()) 832 OutermostContext = OutermostContext->getLookupParent(); 833 834 if (OutermostContext->Equals(PrevDecl->getDeclContext()) || 835 OutermostContext->Encloses(PrevDecl->getDeclContext())) { 836 SemanticContext = PrevDecl->getDeclContext(); 837 } else { 838 // Declarations in outer scopes don't matter. However, the outermost 839 // context we computed is the semantic context for our new 840 // declaration. 841 PrevDecl = 0; 842 SemanticContext = OutermostContext; 843 } 844 845 if (CurContext->isDependentContext()) { 846 // If this is a dependent context, we don't want to link the friend 847 // class template to the template in scope, because that would perform 848 // checking of the template parameter lists that can't be performed 849 // until the outer context is instantiated. 850 PrevDecl = 0; 851 } 852 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S)) 853 PrevDecl = 0; 854 855 // If there is a previous declaration with the same name, check 856 // whether this is a valid redeclaration. 857 ClassTemplateDecl *PrevClassTemplate 858 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); 859 860 // We may have found the injected-class-name of a class template, 861 // class template partial specialization, or class template specialization. 862 // In these cases, grab the template that is being defined or specialized. 863 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && 864 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { 865 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); 866 PrevClassTemplate 867 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); 868 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { 869 PrevClassTemplate 870 = cast<ClassTemplateSpecializationDecl>(PrevDecl) 871 ->getSpecializedTemplate(); 872 } 873 } 874 875 if (PrevClassTemplate) { 876 // Ensure that the template parameter lists are compatible. 877 if (!TemplateParameterListsAreEqual(TemplateParams, 878 PrevClassTemplate->getTemplateParameters(), 879 /*Complain=*/true, 880 TPL_TemplateMatch)) 881 return true; 882 883 // C++ [temp.class]p4: 884 // In a redeclaration, partial specialization, explicit 885 // specialization or explicit instantiation of a class template, 886 // the class-key shall agree in kind with the original class 887 // template declaration (7.1.5.3). 888 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 889 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) { 890 Diag(KWLoc, diag::err_use_with_wrong_tag) 891 << Name 892 << CodeModificationHint::CreateReplacement(KWLoc, 893 PrevRecordDecl->getKindName()); 894 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 895 Kind = PrevRecordDecl->getTagKind(); 896 } 897 898 // Check for redefinition of this class template. 899 if (TUK == TUK_Definition) { 900 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) { 901 Diag(NameLoc, diag::err_redefinition) << Name; 902 Diag(Def->getLocation(), diag::note_previous_definition); 903 // FIXME: Would it make sense to try to "forget" the previous 904 // definition, as part of error recovery? 905 return true; 906 } 907 } 908 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 909 // Maybe we will complain about the shadowed template parameter. 910 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 911 // Just pretend that we didn't see the previous declaration. 912 PrevDecl = 0; 913 } else if (PrevDecl) { 914 // C++ [temp]p5: 915 // A class template shall not have the same name as any other 916 // template, class, function, object, enumeration, enumerator, 917 // namespace, or type in the same scope (3.3), except as specified 918 // in (14.5.4). 919 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 920 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 921 return true; 922 } 923 924 // Check the template parameter list of this declaration, possibly 925 // merging in the template parameter list from the previous class 926 // template declaration. 927 if (CheckTemplateParameterList(TemplateParams, 928 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0)) 929 Invalid = true; 930 931 // FIXME: If we had a scope specifier, we better have a previous template 932 // declaration! 933 934 CXXRecordDecl *NewClass = 935 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc, 936 PrevClassTemplate? 937 PrevClassTemplate->getTemplatedDecl() : 0, 938 /*DelayTypeCreation=*/true); 939 940 ClassTemplateDecl *NewTemplate 941 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 942 DeclarationName(Name), TemplateParams, 943 NewClass, PrevClassTemplate); 944 NewClass->setDescribedClassTemplate(NewTemplate); 945 946 // Build the type for the class template declaration now. 947 QualType T = 948 Context.getTypeDeclType(NewClass, 949 PrevClassTemplate? 950 PrevClassTemplate->getTemplatedDecl() : 0); 951 assert(T->isDependentType() && "Class template type is not dependent?"); 952 (void)T; 953 954 // If we are providing an explicit specialization of a member that is a 955 // class template, make a note of that. 956 if (PrevClassTemplate && 957 PrevClassTemplate->getInstantiatedFromMemberTemplate()) 958 PrevClassTemplate->setMemberSpecialization(); 959 960 // Set the access specifier. 961 if (!Invalid && TUK != TUK_Friend) 962 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); 963 964 // Set the lexical context of these templates 965 NewClass->setLexicalDeclContext(CurContext); 966 NewTemplate->setLexicalDeclContext(CurContext); 967 968 if (TUK == TUK_Definition) 969 NewClass->startDefinition(); 970 971 if (Attr) 972 ProcessDeclAttributeList(S, NewClass, Attr); 973 974 if (TUK != TUK_Friend) 975 PushOnScopeChains(NewTemplate, S); 976 else { 977 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { 978 NewTemplate->setAccess(PrevClassTemplate->getAccess()); 979 NewClass->setAccess(PrevClassTemplate->getAccess()); 980 } 981 982 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */ 983 PrevClassTemplate != NULL); 984 985 // Friend templates are visible in fairly strange ways. 986 if (!CurContext->isDependentContext()) { 987 DeclContext *DC = SemanticContext->getLookupContext(); 988 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false); 989 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 990 PushOnScopeChains(NewTemplate, EnclosingScope, 991 /* AddToContext = */ false); 992 } 993 994 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 995 NewClass->getLocation(), 996 NewTemplate, 997 /*FIXME:*/NewClass->getLocation()); 998 Friend->setAccess(AS_public); 999 CurContext->addDecl(Friend); 1000 } 1001 1002 if (Invalid) { 1003 NewTemplate->setInvalidDecl(); 1004 NewClass->setInvalidDecl(); 1005 } 1006 return DeclPtrTy::make(NewTemplate); 1007} 1008 1009/// \brief Checks the validity of a template parameter list, possibly 1010/// considering the template parameter list from a previous 1011/// declaration. 1012/// 1013/// If an "old" template parameter list is provided, it must be 1014/// equivalent (per TemplateParameterListsAreEqual) to the "new" 1015/// template parameter list. 1016/// 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. 1021/// 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. 1026/// 1027/// \returns true if an error occurred, false otherwise. 1028bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, 1029 TemplateParameterList *OldParams) { 1030 bool Invalid = false; 1031 1032 // C++ [temp.param]p10: 1033 // The set of default template-arguments available for use with a 1034 // template declaration or definition is obtained by merging the 1035 // default arguments from the definition (if in scope) and all 1036 // declarations in scope in the same way default function 1037 // arguments are (8.3.6). 1038 bool SawDefaultArgument = false; 1039 SourceLocation PreviousDefaultArgLoc; 1040 1041 bool SawParameterPack = false; 1042 SourceLocation ParameterPackLoc; 1043 1044 // Dummy initialization to avoid warnings. 1045 TemplateParameterList::iterator OldParam = NewParams->end(); 1046 if (OldParams) 1047 OldParam = OldParams->begin(); 1048 1049 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 1050 NewParamEnd = NewParams->end(); 1051 NewParam != NewParamEnd; ++NewParam) { 1052 // Variables used to diagnose redundant default arguments 1053 bool RedundantDefaultArg = false; 1054 SourceLocation OldDefaultLoc; 1055 SourceLocation NewDefaultLoc; 1056 1057 // Variables used to diagnose missing default arguments 1058 bool MissingDefaultArg = false; 1059 1060 // C++0x [temp.param]p11: 1061 // If a template parameter of a class template is a template parameter pack, 1062 // it must be the last template parameter. 1063 if (SawParameterPack) { 1064 Diag(ParameterPackLoc, 1065 diag::err_template_param_pack_must_be_last_template_parameter); 1066 Invalid = true; 1067 } 1068 1069 // Merge default arguments for template type parameters. 1070 if (TemplateTypeParmDecl *NewTypeParm 1071 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { 1072 TemplateTypeParmDecl *OldTypeParm 1073 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0; 1074 1075 if (NewTypeParm->isParameterPack()) { 1076 assert(!NewTypeParm->hasDefaultArgument() && 1077 "Parameter packs can't have a default argument!"); 1078 SawParameterPack = true; 1079 ParameterPackLoc = NewTypeParm->getLocation(); 1080 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() && 1081 NewTypeParm->hasDefaultArgument()) { 1082 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); 1083 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); 1084 SawDefaultArgument = true; 1085 RedundantDefaultArg = true; 1086 PreviousDefaultArgLoc = NewDefaultLoc; 1087 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { 1088 // Merge the default argument from the old declaration to the 1089 // new declaration. 1090 SawDefaultArgument = true; 1091 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(), 1092 true); 1093 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); 1094 } else if (NewTypeParm->hasDefaultArgument()) { 1095 SawDefaultArgument = true; 1096 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); 1097 } else if (SawDefaultArgument) 1098 MissingDefaultArg = true; 1099 } else if (NonTypeTemplateParmDecl *NewNonTypeParm 1100 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { 1101 // Merge default arguments for non-type template parameters 1102 NonTypeTemplateParmDecl *OldNonTypeParm 1103 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0; 1104 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() && 1105 NewNonTypeParm->hasDefaultArgument()) { 1106 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1107 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1108 SawDefaultArgument = true; 1109 RedundantDefaultArg = true; 1110 PreviousDefaultArgLoc = NewDefaultLoc; 1111 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { 1112 // Merge the default argument from the old declaration to the 1113 // new declaration. 1114 SawDefaultArgument = true; 1115 // FIXME: We need to create a new kind of "default argument" 1116 // expression that points to a previous template template 1117 // parameter. 1118 NewNonTypeParm->setDefaultArgument( 1119 OldNonTypeParm->getDefaultArgument()); 1120 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1121 } else if (NewNonTypeParm->hasDefaultArgument()) { 1122 SawDefaultArgument = true; 1123 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1124 } else if (SawDefaultArgument) 1125 MissingDefaultArg = true; 1126 } else { 1127 // Merge default arguments for template template parameters 1128 TemplateTemplateParmDecl *NewTemplateParm 1129 = cast<TemplateTemplateParmDecl>(*NewParam); 1130 TemplateTemplateParmDecl *OldTemplateParm 1131 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0; 1132 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() && 1133 NewTemplateParm->hasDefaultArgument()) { 1134 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); 1135 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); 1136 SawDefaultArgument = true; 1137 RedundantDefaultArg = true; 1138 PreviousDefaultArgLoc = NewDefaultLoc; 1139 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { 1140 // Merge the default argument from the old declaration to the 1141 // new declaration. 1142 SawDefaultArgument = true; 1143 // FIXME: We need to create a new kind of "default argument" expression 1144 // that points to a previous template template parameter. 1145 NewTemplateParm->setDefaultArgument( 1146 OldTemplateParm->getDefaultArgument()); 1147 PreviousDefaultArgLoc 1148 = OldTemplateParm->getDefaultArgument().getLocation(); 1149 } else if (NewTemplateParm->hasDefaultArgument()) { 1150 SawDefaultArgument = true; 1151 PreviousDefaultArgLoc 1152 = NewTemplateParm->getDefaultArgument().getLocation(); 1153 } else if (SawDefaultArgument) 1154 MissingDefaultArg = true; 1155 } 1156 1157 if (RedundantDefaultArg) { 1158 // C++ [temp.param]p12: 1159 // A template-parameter shall not be given default arguments 1160 // by two different declarations in the same scope. 1161 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); 1162 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); 1163 Invalid = true; 1164 } else if (MissingDefaultArg) { 1165 // C++ [temp.param]p11: 1166 // If a template-parameter has a default template-argument, 1167 // all subsequent template-parameters shall have a default 1168 // template-argument supplied. 1169 Diag((*NewParam)->getLocation(), 1170 diag::err_template_param_default_arg_missing); 1171 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); 1172 Invalid = true; 1173 } 1174 1175 // If we have an old template parameter list that we're merging 1176 // in, move on to the next parameter. 1177 if (OldParams) 1178 ++OldParam; 1179 } 1180 1181 return Invalid; 1182} 1183 1184/// \brief Match the given template parameter lists to the given scope 1185/// specifier, returning the template parameter list that applies to the 1186/// name. 1187/// 1188/// \param DeclStartLoc the start of the declaration that has a scope 1189/// specifier or a template parameter list. 1190/// 1191/// \param SS the scope specifier that will be matched to the given template 1192/// parameter lists. This scope specifier precedes a qualified name that is 1193/// being declared. 1194/// 1195/// \param ParamLists the template parameter lists, from the outermost to the 1196/// innermost template parameter lists. 1197/// 1198/// \param NumParamLists the number of template parameter lists in ParamLists. 1199/// 1200/// \param IsExplicitSpecialization will be set true if the entity being 1201/// declared is an explicit specialization, false otherwise. 1202/// 1203/// \returns the template parameter list, if any, that corresponds to the 1204/// name that is preceded by the scope specifier @p SS. This template 1205/// parameter list may be have template parameters (if we're declaring a 1206/// template) or may have no template parameters (if we're declaring a 1207/// template specialization), or may be NULL (if we were's declaring isn't 1208/// itself a template). 1209TemplateParameterList * 1210Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 1211 const CXXScopeSpec &SS, 1212 TemplateParameterList **ParamLists, 1213 unsigned NumParamLists, 1214 bool &IsExplicitSpecialization) { 1215 IsExplicitSpecialization = false; 1216 1217 // Find the template-ids that occur within the nested-name-specifier. These 1218 // template-ids will match up with the template parameter lists. 1219 llvm::SmallVector<const TemplateSpecializationType *, 4> 1220 TemplateIdsInSpecifier; 1221 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4> 1222 ExplicitSpecializationsInSpecifier; 1223 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 1224 NNS; NNS = NNS->getPrefix()) { 1225 if (const TemplateSpecializationType *SpecType 1226 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) { 1227 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl(); 1228 if (!Template) 1229 continue; // FIXME: should this be an error? probably... 1230 1231 if (const RecordType *Record = SpecType->getAs<RecordType>()) { 1232 ClassTemplateSpecializationDecl *SpecDecl 1233 = cast<ClassTemplateSpecializationDecl>(Record->getDecl()); 1234 // If the nested name specifier refers to an explicit specialization, 1235 // we don't need a template<> header. 1236 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) { 1237 ExplicitSpecializationsInSpecifier.push_back(SpecDecl); 1238 continue; 1239 } 1240 } 1241 1242 TemplateIdsInSpecifier.push_back(SpecType); 1243 } 1244 } 1245 1246 // Reverse the list of template-ids in the scope specifier, so that we can 1247 // more easily match up the template-ids and the template parameter lists. 1248 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end()); 1249 1250 SourceLocation FirstTemplateLoc = DeclStartLoc; 1251 if (NumParamLists) 1252 FirstTemplateLoc = ParamLists[0]->getTemplateLoc(); 1253 1254 // Match the template-ids found in the specifier to the template parameter 1255 // lists. 1256 unsigned Idx = 0; 1257 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size(); 1258 Idx != NumTemplateIds; ++Idx) { 1259 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0); 1260 bool DependentTemplateId = TemplateId->isDependentType(); 1261 if (Idx >= NumParamLists) { 1262 // We have a template-id without a corresponding template parameter 1263 // list. 1264 if (DependentTemplateId) { 1265 // FIXME: the location information here isn't great. 1266 Diag(SS.getRange().getBegin(), 1267 diag::err_template_spec_needs_template_parameters) 1268 << TemplateId 1269 << SS.getRange(); 1270 } else { 1271 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header) 1272 << SS.getRange() 1273 << CodeModificationHint::CreateInsertion(FirstTemplateLoc, 1274 "template<> "); 1275 IsExplicitSpecialization = true; 1276 } 1277 return 0; 1278 } 1279 1280 // Check the template parameter list against its corresponding template-id. 1281 if (DependentTemplateId) { 1282 TemplateDecl *Template 1283 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl(); 1284 1285 if (ClassTemplateDecl *ClassTemplate 1286 = dyn_cast<ClassTemplateDecl>(Template)) { 1287 TemplateParameterList *ExpectedTemplateParams = 0; 1288 // Is this template-id naming the primary template? 1289 if (Context.hasSameType(TemplateId, 1290 ClassTemplate->getInjectedClassNameType(Context))) 1291 ExpectedTemplateParams = ClassTemplate->getTemplateParameters(); 1292 // ... or a partial specialization? 1293 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 1294 = ClassTemplate->findPartialSpecialization(TemplateId)) 1295 ExpectedTemplateParams = PartialSpec->getTemplateParameters(); 1296 1297 if (ExpectedTemplateParams) 1298 TemplateParameterListsAreEqual(ParamLists[Idx], 1299 ExpectedTemplateParams, 1300 true, TPL_TemplateMatch); 1301 } 1302 } else if (ParamLists[Idx]->size() > 0) 1303 Diag(ParamLists[Idx]->getTemplateLoc(), 1304 diag::err_template_param_list_matches_nontemplate) 1305 << TemplateId 1306 << ParamLists[Idx]->getSourceRange(); 1307 else 1308 IsExplicitSpecialization = true; 1309 } 1310 1311 // If there were at least as many template-ids as there were template 1312 // parameter lists, then there are no template parameter lists remaining for 1313 // the declaration itself. 1314 if (Idx >= NumParamLists) 1315 return 0; 1316 1317 // If there were too many template parameter lists, complain about that now. 1318 if (Idx != NumParamLists - 1) { 1319 while (Idx < NumParamLists - 1) { 1320 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0; 1321 Diag(ParamLists[Idx]->getTemplateLoc(), 1322 isExplicitSpecHeader? diag::warn_template_spec_extra_headers 1323 : diag::err_template_spec_extra_headers) 1324 << SourceRange(ParamLists[Idx]->getTemplateLoc(), 1325 ParamLists[Idx]->getRAngleLoc()); 1326 1327 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) { 1328 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(), 1329 diag::note_explicit_template_spec_does_not_need_header) 1330 << ExplicitSpecializationsInSpecifier.back(); 1331 ExplicitSpecializationsInSpecifier.pop_back(); 1332 } 1333 1334 ++Idx; 1335 } 1336 } 1337 1338 // Return the last template parameter list, which corresponds to the 1339 // entity being declared. 1340 return ParamLists[NumParamLists - 1]; 1341} 1342 1343QualType Sema::CheckTemplateIdType(TemplateName Name, 1344 SourceLocation TemplateLoc, 1345 const TemplateArgumentListInfo &TemplateArgs) { 1346 TemplateDecl *Template = Name.getAsTemplateDecl(); 1347 if (!Template) { 1348 // The template name does not resolve to a template, so we just 1349 // build a dependent template-id type. 1350 return Context.getTemplateSpecializationType(Name, TemplateArgs); 1351 } 1352 1353 // Check that the template argument list is well-formed for this 1354 // template. 1355 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(), 1356 TemplateArgs.size()); 1357 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, 1358 false, Converted)) 1359 return QualType(); 1360 1361 assert((Converted.structuredSize() == 1362 Template->getTemplateParameters()->size()) && 1363 "Converted template argument list is too short!"); 1364 1365 QualType CanonType; 1366 1367 if (Name.isDependent() || 1368 TemplateSpecializationType::anyDependentTemplateArguments( 1369 TemplateArgs)) { 1370 // This class template specialization is a dependent 1371 // type. Therefore, its canonical type is another class template 1372 // specialization type that contains all of the converted 1373 // arguments in canonical form. This ensures that, e.g., A<T> and 1374 // A<T, T> have identical types when A is declared as: 1375 // 1376 // template<typename T, typename U = T> struct A; 1377 TemplateName CanonName = Context.getCanonicalTemplateName(Name); 1378 CanonType = Context.getTemplateSpecializationType(CanonName, 1379 Converted.getFlatArguments(), 1380 Converted.flatSize()); 1381 1382 // FIXME: CanonType is not actually the canonical type, and unfortunately 1383 // it is a TemplateSpecializationType that we will never use again. 1384 // In the future, we need to teach getTemplateSpecializationType to only 1385 // build the canonical type and return that to us. 1386 CanonType = Context.getCanonicalType(CanonType); 1387 } else if (ClassTemplateDecl *ClassTemplate 1388 = dyn_cast<ClassTemplateDecl>(Template)) { 1389 // Find the class template specialization declaration that 1390 // corresponds to these arguments. 1391 llvm::FoldingSetNodeID ID; 1392 ClassTemplateSpecializationDecl::Profile(ID, 1393 Converted.getFlatArguments(), 1394 Converted.flatSize(), 1395 Context); 1396 void *InsertPos = 0; 1397 ClassTemplateSpecializationDecl *Decl 1398 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 1399 if (!Decl) { 1400 // This is the first time we have referenced this class template 1401 // specialization. Create the canonical declaration and add it to 1402 // the set of specializations. 1403 Decl = ClassTemplateSpecializationDecl::Create(Context, 1404 ClassTemplate->getDeclContext(), 1405 ClassTemplate->getLocation(), 1406 ClassTemplate, 1407 Converted, 0); 1408 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos); 1409 Decl->setLexicalDeclContext(CurContext); 1410 } 1411 1412 CanonType = Context.getTypeDeclType(Decl); 1413 } 1414 1415 // Build the fully-sugared type for this class template 1416 // specialization, which refers back to the class template 1417 // specialization we created or found. 1418 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); 1419} 1420 1421Action::TypeResult 1422Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc, 1423 SourceLocation LAngleLoc, 1424 ASTTemplateArgsPtr TemplateArgsIn, 1425 SourceLocation RAngleLoc) { 1426 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 1427 1428 // Translate the parser's template argument list in our AST format. 1429 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 1430 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 1431 1432 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 1433 TemplateArgsIn.release(); 1434 1435 if (Result.isNull()) 1436 return true; 1437 1438 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result); 1439 TemplateSpecializationTypeLoc TL 1440 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 1441 TL.setTemplateNameLoc(TemplateLoc); 1442 TL.setLAngleLoc(LAngleLoc); 1443 TL.setRAngleLoc(RAngleLoc); 1444 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 1445 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 1446 1447 return CreateLocInfoType(Result, DI).getAsOpaquePtr(); 1448} 1449 1450Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult, 1451 TagUseKind TUK, 1452 DeclSpec::TST TagSpec, 1453 SourceLocation TagLoc) { 1454 if (TypeResult.isInvalid()) 1455 return Sema::TypeResult(); 1456 1457 // FIXME: preserve source info, ideally without copying the DI. 1458 DeclaratorInfo *DI; 1459 QualType Type = GetTypeFromParser(TypeResult.get(), &DI); 1460 1461 // Verify the tag specifier. 1462 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec); 1463 1464 if (const RecordType *RT = Type->getAs<RecordType>()) { 1465 RecordDecl *D = RT->getDecl(); 1466 1467 IdentifierInfo *Id = D->getIdentifier(); 1468 assert(Id && "templated class must have an identifier"); 1469 1470 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) { 1471 Diag(TagLoc, diag::err_use_with_wrong_tag) 1472 << Type 1473 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc), 1474 D->getKindName()); 1475 Diag(D->getLocation(), diag::note_previous_use); 1476 } 1477 } 1478 1479 QualType ElabType = Context.getElaboratedType(Type, TagKind); 1480 1481 return ElabType.getAsOpaquePtr(); 1482} 1483 1484Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, 1485 LookupResult &R, 1486 bool RequiresADL, 1487 const TemplateArgumentListInfo &TemplateArgs) { 1488 // FIXME: Can we do any checking at this point? I guess we could check the 1489 // template arguments that we have against the template name, if the template 1490 // name refers to a single template. That's not a terribly common case, 1491 // though. 1492 1493 // These should be filtered out by our callers. 1494 assert(!R.empty() && "empty lookup results when building templateid"); 1495 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid"); 1496 1497 NestedNameSpecifier *Qualifier = 0; 1498 SourceRange QualifierRange; 1499 if (SS.isSet()) { 1500 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1501 QualifierRange = SS.getRange(); 1502 } 1503 1504 bool Dependent 1505 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 1506 &TemplateArgs); 1507 UnresolvedLookupExpr *ULE 1508 = UnresolvedLookupExpr::Create(Context, Dependent, 1509 Qualifier, QualifierRange, 1510 R.getLookupName(), R.getNameLoc(), 1511 RequiresADL, TemplateArgs); 1512 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1513 ULE->addDecl(*I); 1514 1515 return Owned(ULE); 1516} 1517 1518// We actually only call this from template instantiation. 1519Sema::OwningExprResult 1520Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS, 1521 DeclarationName Name, 1522 SourceLocation NameLoc, 1523 const TemplateArgumentListInfo &TemplateArgs) { 1524 DeclContext *DC; 1525 if (!(DC = computeDeclContext(SS, false)) || 1526 DC->isDependentContext() || 1527 RequireCompleteDeclContext(SS)) 1528 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs); 1529 1530 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName); 1531 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false); 1532 1533 if (R.isAmbiguous()) 1534 return ExprError(); 1535 1536 if (R.empty()) { 1537 Diag(NameLoc, diag::err_template_kw_refers_to_non_template) 1538 << Name << SS.getRange(); 1539 return ExprError(); 1540 } 1541 1542 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) { 1543 Diag(NameLoc, diag::err_template_kw_refers_to_class_template) 1544 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange(); 1545 Diag(Temp->getLocation(), diag::note_referenced_class_template); 1546 return ExprError(); 1547 } 1548 1549 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs); 1550} 1551 1552/// \brief Form a dependent template name. 1553/// 1554/// This action forms a dependent template name given the template 1555/// name and its (presumably dependent) scope specifier. For 1556/// example, given "MetaFun::template apply", the scope specifier \p 1557/// SS will be "MetaFun::", \p TemplateKWLoc contains the location 1558/// of the "template" keyword, and "apply" is the \p Name. 1559Sema::TemplateTy 1560Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc, 1561 const CXXScopeSpec &SS, 1562 UnqualifiedId &Name, 1563 TypeTy *ObjectType, 1564 bool EnteringContext) { 1565 if ((ObjectType && 1566 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) || 1567 (SS.isSet() && computeDeclContext(SS, EnteringContext))) { 1568 // C++0x [temp.names]p5: 1569 // If a name prefixed by the keyword template is not the name of 1570 // a template, the program is ill-formed. [Note: the keyword 1571 // template may not be applied to non-template members of class 1572 // templates. -end note ] [ Note: as is the case with the 1573 // typename prefix, the template prefix is allowed in cases 1574 // where it is not strictly necessary; i.e., when the 1575 // nested-name-specifier or the expression on the left of the -> 1576 // or . is not dependent on a template-parameter, or the use 1577 // does not appear in the scope of a template. -end note] 1578 // 1579 // Note: C++03 was more strict here, because it banned the use of 1580 // the "template" keyword prior to a template-name that was not a 1581 // dependent name. C++ DR468 relaxed this requirement (the 1582 // "template" keyword is now permitted). We follow the C++0x 1583 // rules, even in C++03 mode, retroactively applying the DR. 1584 TemplateTy Template; 1585 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType, 1586 EnteringContext, Template); 1587 if (TNK == TNK_Non_template) { 1588 Diag(Name.getSourceRange().getBegin(), 1589 diag::err_template_kw_refers_to_non_template) 1590 << GetNameFromUnqualifiedId(Name) 1591 << Name.getSourceRange(); 1592 return TemplateTy(); 1593 } 1594 1595 return Template; 1596 } 1597 1598 NestedNameSpecifier *Qualifier 1599 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 1600 1601 switch (Name.getKind()) { 1602 case UnqualifiedId::IK_Identifier: 1603 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, 1604 Name.Identifier)); 1605 1606 case UnqualifiedId::IK_OperatorFunctionId: 1607 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, 1608 Name.OperatorFunctionId.Operator)); 1609 1610 default: 1611 break; 1612 } 1613 1614 Diag(Name.getSourceRange().getBegin(), 1615 diag::err_template_kw_refers_to_non_template) 1616 << GetNameFromUnqualifiedId(Name) 1617 << Name.getSourceRange(); 1618 return TemplateTy(); 1619} 1620 1621bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 1622 const TemplateArgumentLoc &AL, 1623 TemplateArgumentListBuilder &Converted) { 1624 const TemplateArgument &Arg = AL.getArgument(); 1625 1626 // Check template type parameter. 1627 if (Arg.getKind() != TemplateArgument::Type) { 1628 // C++ [temp.arg.type]p1: 1629 // A template-argument for a template-parameter which is a 1630 // type shall be a type-id. 1631 1632 // We have a template type parameter but the template argument 1633 // is not a type. 1634 SourceRange SR = AL.getSourceRange(); 1635 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; 1636 Diag(Param->getLocation(), diag::note_template_param_here); 1637 1638 return true; 1639 } 1640 1641 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo())) 1642 return true; 1643 1644 // Add the converted template type argument. 1645 Converted.Append( 1646 TemplateArgument(Context.getCanonicalType(Arg.getAsType()))); 1647 return false; 1648} 1649 1650/// \brief Substitute template arguments into the default template argument for 1651/// the given template type parameter. 1652/// 1653/// \param SemaRef the semantic analysis object for which we are performing 1654/// the substitution. 1655/// 1656/// \param Template the template that we are synthesizing template arguments 1657/// for. 1658/// 1659/// \param TemplateLoc the location of the template name that started the 1660/// template-id we are checking. 1661/// 1662/// \param RAngleLoc the location of the right angle bracket ('>') that 1663/// terminates the template-id. 1664/// 1665/// \param Param the template template parameter whose default we are 1666/// substituting into. 1667/// 1668/// \param Converted the list of template arguments provided for template 1669/// parameters that precede \p Param in the template parameter list. 1670/// 1671/// \returns the substituted template argument, or NULL if an error occurred. 1672static DeclaratorInfo * 1673SubstDefaultTemplateArgument(Sema &SemaRef, 1674 TemplateDecl *Template, 1675 SourceLocation TemplateLoc, 1676 SourceLocation RAngleLoc, 1677 TemplateTypeParmDecl *Param, 1678 TemplateArgumentListBuilder &Converted) { 1679 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo(); 1680 1681 // If the argument type is dependent, instantiate it now based 1682 // on the previously-computed template arguments. 1683 if (ArgType->getType()->isDependentType()) { 1684 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted, 1685 /*TakeArgs=*/false); 1686 1687 MultiLevelTemplateArgumentList AllTemplateArgs 1688 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 1689 1690 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 1691 Template, Converted.getFlatArguments(), 1692 Converted.flatSize(), 1693 SourceRange(TemplateLoc, RAngleLoc)); 1694 1695 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs, 1696 Param->getDefaultArgumentLoc(), 1697 Param->getDeclName()); 1698 } 1699 1700 return ArgType; 1701} 1702 1703/// \brief Substitute template arguments into the default template argument for 1704/// the given non-type template parameter. 1705/// 1706/// \param SemaRef the semantic analysis object for which we are performing 1707/// the substitution. 1708/// 1709/// \param Template the template that we are synthesizing template arguments 1710/// for. 1711/// 1712/// \param TemplateLoc the location of the template name that started the 1713/// template-id we are checking. 1714/// 1715/// \param RAngleLoc the location of the right angle bracket ('>') that 1716/// terminates the template-id. 1717/// 1718/// \param Param the non-type template parameter whose default we are 1719/// substituting into. 1720/// 1721/// \param Converted the list of template arguments provided for template 1722/// parameters that precede \p Param in the template parameter list. 1723/// 1724/// \returns the substituted template argument, or NULL if an error occurred. 1725static Sema::OwningExprResult 1726SubstDefaultTemplateArgument(Sema &SemaRef, 1727 TemplateDecl *Template, 1728 SourceLocation TemplateLoc, 1729 SourceLocation RAngleLoc, 1730 NonTypeTemplateParmDecl *Param, 1731 TemplateArgumentListBuilder &Converted) { 1732 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted, 1733 /*TakeArgs=*/false); 1734 1735 MultiLevelTemplateArgumentList AllTemplateArgs 1736 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 1737 1738 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 1739 Template, Converted.getFlatArguments(), 1740 Converted.flatSize(), 1741 SourceRange(TemplateLoc, RAngleLoc)); 1742 1743 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs); 1744} 1745 1746/// \brief Substitute template arguments into the default template argument for 1747/// the given template template parameter. 1748/// 1749/// \param SemaRef the semantic analysis object for which we are performing 1750/// the substitution. 1751/// 1752/// \param Template the template that we are synthesizing template arguments 1753/// for. 1754/// 1755/// \param TemplateLoc the location of the template name that started the 1756/// template-id we are checking. 1757/// 1758/// \param RAngleLoc the location of the right angle bracket ('>') that 1759/// terminates the template-id. 1760/// 1761/// \param Param the template template parameter whose default we are 1762/// substituting into. 1763/// 1764/// \param Converted the list of template arguments provided for template 1765/// parameters that precede \p Param in the template parameter list. 1766/// 1767/// \returns the substituted template argument, or NULL if an error occurred. 1768static TemplateName 1769SubstDefaultTemplateArgument(Sema &SemaRef, 1770 TemplateDecl *Template, 1771 SourceLocation TemplateLoc, 1772 SourceLocation RAngleLoc, 1773 TemplateTemplateParmDecl *Param, 1774 TemplateArgumentListBuilder &Converted) { 1775 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted, 1776 /*TakeArgs=*/false); 1777 1778 MultiLevelTemplateArgumentList AllTemplateArgs 1779 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 1780 1781 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 1782 Template, Converted.getFlatArguments(), 1783 Converted.flatSize(), 1784 SourceRange(TemplateLoc, RAngleLoc)); 1785 1786 return SemaRef.SubstTemplateName( 1787 Param->getDefaultArgument().getArgument().getAsTemplate(), 1788 Param->getDefaultArgument().getTemplateNameLoc(), 1789 AllTemplateArgs); 1790} 1791 1792/// \brief Check that the given template argument corresponds to the given 1793/// template parameter. 1794bool Sema::CheckTemplateArgument(NamedDecl *Param, 1795 const TemplateArgumentLoc &Arg, 1796 TemplateDecl *Template, 1797 SourceLocation TemplateLoc, 1798 SourceLocation RAngleLoc, 1799 TemplateArgumentListBuilder &Converted) { 1800 // Check template type parameters. 1801 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 1802 return CheckTemplateTypeArgument(TTP, Arg, Converted); 1803 1804 // Check non-type template parameters. 1805 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { 1806 // Do substitution on the type of the non-type template parameter 1807 // with the template arguments we've seen thus far. 1808 QualType NTTPType = NTTP->getType(); 1809 if (NTTPType->isDependentType()) { 1810 // Do substitution on the type of the non-type template parameter. 1811 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 1812 NTTP, Converted.getFlatArguments(), 1813 Converted.flatSize(), 1814 SourceRange(TemplateLoc, RAngleLoc)); 1815 1816 TemplateArgumentList TemplateArgs(Context, Converted, 1817 /*TakeArgs=*/false); 1818 NTTPType = SubstType(NTTPType, 1819 MultiLevelTemplateArgumentList(TemplateArgs), 1820 NTTP->getLocation(), 1821 NTTP->getDeclName()); 1822 // If that worked, check the non-type template parameter type 1823 // for validity. 1824 if (!NTTPType.isNull()) 1825 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 1826 NTTP->getLocation()); 1827 if (NTTPType.isNull()) 1828 return true; 1829 } 1830 1831 switch (Arg.getArgument().getKind()) { 1832 case TemplateArgument::Null: 1833 assert(false && "Should never see a NULL template argument here"); 1834 return true; 1835 1836 case TemplateArgument::Expression: { 1837 Expr *E = Arg.getArgument().getAsExpr(); 1838 TemplateArgument Result; 1839 if (CheckTemplateArgument(NTTP, NTTPType, E, Result)) 1840 return true; 1841 1842 Converted.Append(Result); 1843 break; 1844 } 1845 1846 case TemplateArgument::Declaration: 1847 case TemplateArgument::Integral: 1848 // We've already checked this template argument, so just copy 1849 // it to the list of converted arguments. 1850 Converted.Append(Arg.getArgument()); 1851 break; 1852 1853 case TemplateArgument::Template: 1854 // We were given a template template argument. It may not be ill-formed; 1855 // see below. 1856 if (DependentTemplateName *DTN 1857 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) { 1858 // We have a template argument such as \c T::template X, which we 1859 // parsed as a template template argument. However, since we now 1860 // know that we need a non-type template argument, convert this 1861 // template name into an expression. 1862 Expr *E = DependentScopeDeclRefExpr::Create(Context, 1863 DTN->getQualifier(), 1864 Arg.getTemplateQualifierRange(), 1865 DTN->getIdentifier(), 1866 Arg.getTemplateNameLoc()); 1867 1868 TemplateArgument Result; 1869 if (CheckTemplateArgument(NTTP, NTTPType, E, Result)) 1870 return true; 1871 1872 Converted.Append(Result); 1873 break; 1874 } 1875 1876 // We have a template argument that actually does refer to a class 1877 // template, template alias, or template template parameter, and 1878 // therefore cannot be a non-type template argument. 1879 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) 1880 << Arg.getSourceRange(); 1881 1882 Diag(Param->getLocation(), diag::note_template_param_here); 1883 return true; 1884 1885 case TemplateArgument::Type: { 1886 // We have a non-type template parameter but the template 1887 // argument is a type. 1888 1889 // C++ [temp.arg]p2: 1890 // In a template-argument, an ambiguity between a type-id and 1891 // an expression is resolved to a type-id, regardless of the 1892 // form of the corresponding template-parameter. 1893 // 1894 // We warn specifically about this case, since it can be rather 1895 // confusing for users. 1896 QualType T = Arg.getArgument().getAsType(); 1897 SourceRange SR = Arg.getSourceRange(); 1898 if (T->isFunctionType()) 1899 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; 1900 else 1901 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; 1902 Diag(Param->getLocation(), diag::note_template_param_here); 1903 return true; 1904 } 1905 1906 case TemplateArgument::Pack: 1907 llvm::llvm_unreachable("Caller must expand template argument packs"); 1908 break; 1909 } 1910 1911 return false; 1912 } 1913 1914 1915 // Check template template parameters. 1916 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); 1917 1918 // Substitute into the template parameter list of the template 1919 // template parameter, since previously-supplied template arguments 1920 // may appear within the template template parameter. 1921 { 1922 // Set up a template instantiation context. 1923 LocalInstantiationScope Scope(*this); 1924 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 1925 TempParm, Converted.getFlatArguments(), 1926 Converted.flatSize(), 1927 SourceRange(TemplateLoc, RAngleLoc)); 1928 1929 TemplateArgumentList TemplateArgs(Context, Converted, 1930 /*TakeArgs=*/false); 1931 TempParm = cast_or_null<TemplateTemplateParmDecl>( 1932 SubstDecl(TempParm, CurContext, 1933 MultiLevelTemplateArgumentList(TemplateArgs))); 1934 if (!TempParm) 1935 return true; 1936 1937 // FIXME: TempParam is leaked. 1938 } 1939 1940 switch (Arg.getArgument().getKind()) { 1941 case TemplateArgument::Null: 1942 assert(false && "Should never see a NULL template argument here"); 1943 return true; 1944 1945 case TemplateArgument::Template: 1946 if (CheckTemplateArgument(TempParm, Arg)) 1947 return true; 1948 1949 Converted.Append(Arg.getArgument()); 1950 break; 1951 1952 case TemplateArgument::Expression: 1953 case TemplateArgument::Type: 1954 // We have a template template parameter but the template 1955 // argument does not refer to a template. 1956 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template); 1957 return true; 1958 1959 case TemplateArgument::Declaration: 1960 llvm::llvm_unreachable( 1961 "Declaration argument with template template parameter"); 1962 break; 1963 case TemplateArgument::Integral: 1964 llvm::llvm_unreachable( 1965 "Integral argument with template template parameter"); 1966 break; 1967 1968 case TemplateArgument::Pack: 1969 llvm::llvm_unreachable("Caller must expand template argument packs"); 1970 break; 1971 } 1972 1973 return false; 1974} 1975 1976/// \brief Check that the given template argument list is well-formed 1977/// for specializing the given template. 1978bool Sema::CheckTemplateArgumentList(TemplateDecl *Template, 1979 SourceLocation TemplateLoc, 1980 const TemplateArgumentListInfo &TemplateArgs, 1981 bool PartialTemplateArgs, 1982 TemplateArgumentListBuilder &Converted) { 1983 TemplateParameterList *Params = Template->getTemplateParameters(); 1984 unsigned NumParams = Params->size(); 1985 unsigned NumArgs = TemplateArgs.size(); 1986 bool Invalid = false; 1987 1988 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc(); 1989 1990 bool HasParameterPack = 1991 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack(); 1992 1993 if ((NumArgs > NumParams && !HasParameterPack) || 1994 (NumArgs < Params->getMinRequiredArguments() && 1995 !PartialTemplateArgs)) { 1996 // FIXME: point at either the first arg beyond what we can handle, 1997 // or the '>', depending on whether we have too many or too few 1998 // arguments. 1999 SourceRange Range; 2000 if (NumArgs > NumParams) 2001 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc); 2002 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 2003 << (NumArgs > NumParams) 2004 << (isa<ClassTemplateDecl>(Template)? 0 : 2005 isa<FunctionTemplateDecl>(Template)? 1 : 2006 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 2007 << Template << Range; 2008 Diag(Template->getLocation(), diag::note_template_decl_here) 2009 << Params->getSourceRange(); 2010 Invalid = true; 2011 } 2012 2013 // C++ [temp.arg]p1: 2014 // [...] The type and form of each template-argument specified in 2015 // a template-id shall match the type and form specified for the 2016 // corresponding parameter declared by the template in its 2017 // template-parameter-list. 2018 unsigned ArgIdx = 0; 2019 for (TemplateParameterList::iterator Param = Params->begin(), 2020 ParamEnd = Params->end(); 2021 Param != ParamEnd; ++Param, ++ArgIdx) { 2022 if (ArgIdx > NumArgs && PartialTemplateArgs) 2023 break; 2024 2025 // If we have a template parameter pack, check every remaining template 2026 // argument against that template parameter pack. 2027 if ((*Param)->isTemplateParameterPack()) { 2028 Converted.BeginPack(); 2029 for (; ArgIdx < NumArgs; ++ArgIdx) { 2030 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 2031 TemplateLoc, RAngleLoc, Converted)) { 2032 Invalid = true; 2033 break; 2034 } 2035 } 2036 Converted.EndPack(); 2037 continue; 2038 } 2039 2040 if (ArgIdx < NumArgs) { 2041 // Check the template argument we were given. 2042 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 2043 TemplateLoc, RAngleLoc, Converted)) 2044 return true; 2045 2046 continue; 2047 } 2048 2049 // We have a default template argument that we will use. 2050 TemplateArgumentLoc Arg; 2051 2052 // Retrieve the default template argument from the template 2053 // parameter. For each kind of template parameter, we substitute the 2054 // template arguments provided thus far and any "outer" template arguments 2055 // (when the template parameter was part of a nested template) into 2056 // the default argument. 2057 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 2058 if (!TTP->hasDefaultArgument()) { 2059 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2060 break; 2061 } 2062 2063 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this, 2064 Template, 2065 TemplateLoc, 2066 RAngleLoc, 2067 TTP, 2068 Converted); 2069 if (!ArgType) 2070 return true; 2071 2072 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), 2073 ArgType); 2074 } else if (NonTypeTemplateParmDecl *NTTP 2075 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 2076 if (!NTTP->hasDefaultArgument()) { 2077 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2078 break; 2079 } 2080 2081 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template, 2082 TemplateLoc, 2083 RAngleLoc, 2084 NTTP, 2085 Converted); 2086 if (E.isInvalid()) 2087 return true; 2088 2089 Expr *Ex = E.takeAs<Expr>(); 2090 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); 2091 } else { 2092 TemplateTemplateParmDecl *TempParm 2093 = cast<TemplateTemplateParmDecl>(*Param); 2094 2095 if (!TempParm->hasDefaultArgument()) { 2096 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2097 break; 2098 } 2099 2100 TemplateName Name = SubstDefaultTemplateArgument(*this, Template, 2101 TemplateLoc, 2102 RAngleLoc, 2103 TempParm, 2104 Converted); 2105 if (Name.isNull()) 2106 return true; 2107 2108 Arg = TemplateArgumentLoc(TemplateArgument(Name), 2109 TempParm->getDefaultArgument().getTemplateQualifierRange(), 2110 TempParm->getDefaultArgument().getTemplateNameLoc()); 2111 } 2112 2113 // Introduce an instantiation record that describes where we are using 2114 // the default template argument. 2115 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param, 2116 Converted.getFlatArguments(), 2117 Converted.flatSize(), 2118 SourceRange(TemplateLoc, RAngleLoc)); 2119 2120 // Check the default template argument. 2121 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, 2122 RAngleLoc, Converted)) 2123 return true; 2124 } 2125 2126 return Invalid; 2127} 2128 2129/// \brief Check a template argument against its corresponding 2130/// template type parameter. 2131/// 2132/// This routine implements the semantics of C++ [temp.arg.type]. It 2133/// returns true if an error occurred, and false otherwise. 2134bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 2135 DeclaratorInfo *ArgInfo) { 2136 assert(ArgInfo && "invalid DeclaratorInfo"); 2137 QualType Arg = ArgInfo->getType(); 2138 2139 // C++ [temp.arg.type]p2: 2140 // A local type, a type with no linkage, an unnamed type or a type 2141 // compounded from any of these types shall not be used as a 2142 // template-argument for a template type-parameter. 2143 // 2144 // FIXME: Perform the recursive and no-linkage type checks. 2145 const TagType *Tag = 0; 2146 if (const EnumType *EnumT = Arg->getAs<EnumType>()) 2147 Tag = EnumT; 2148 else if (const RecordType *RecordT = Arg->getAs<RecordType>()) 2149 Tag = RecordT; 2150 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) { 2151 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange(); 2152 return Diag(SR.getBegin(), diag::err_template_arg_local_type) 2153 << QualType(Tag, 0) << SR; 2154 } else if (Tag && !Tag->getDecl()->getDeclName() && 2155 !Tag->getDecl()->getTypedefForAnonDecl()) { 2156 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange(); 2157 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR; 2158 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here); 2159 return true; 2160 } 2161 2162 return false; 2163} 2164 2165/// \brief Checks whether the given template argument is the address 2166/// of an object or function according to C++ [temp.arg.nontype]p1. 2167bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg, 2168 NamedDecl *&Entity) { 2169 bool Invalid = false; 2170 2171 // See through any implicit casts we added to fix the type. 2172 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 2173 Arg = Cast->getSubExpr(); 2174 2175 // C++0x allows nullptr, and there's no further checking to be done for that. 2176 if (Arg->getType()->isNullPtrType()) 2177 return false; 2178 2179 // C++ [temp.arg.nontype]p1: 2180 // 2181 // A template-argument for a non-type, non-template 2182 // template-parameter shall be one of: [...] 2183 // 2184 // -- the address of an object or function with external 2185 // linkage, including function templates and function 2186 // template-ids but excluding non-static class members, 2187 // expressed as & id-expression where the & is optional if 2188 // the name refers to a function or array, or if the 2189 // corresponding template-parameter is a reference; or 2190 DeclRefExpr *DRE = 0; 2191 2192 // Ignore (and complain about) any excess parentheses. 2193 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 2194 if (!Invalid) { 2195 Diag(Arg->getSourceRange().getBegin(), 2196 diag::err_template_arg_extra_parens) 2197 << Arg->getSourceRange(); 2198 Invalid = true; 2199 } 2200 2201 Arg = Parens->getSubExpr(); 2202 } 2203 2204 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 2205 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 2206 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 2207 } else 2208 DRE = dyn_cast<DeclRefExpr>(Arg); 2209 2210 if (!DRE || !isa<ValueDecl>(DRE->getDecl())) 2211 return Diag(Arg->getSourceRange().getBegin(), 2212 diag::err_template_arg_not_object_or_func_form) 2213 << Arg->getSourceRange(); 2214 2215 // Cannot refer to non-static data members 2216 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) 2217 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field) 2218 << Field << Arg->getSourceRange(); 2219 2220 // Cannot refer to non-static member functions 2221 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl())) 2222 if (!Method->isStatic()) 2223 return Diag(Arg->getSourceRange().getBegin(), 2224 diag::err_template_arg_method) 2225 << Method << Arg->getSourceRange(); 2226 2227 // Functions must have external linkage. 2228 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) { 2229 if (Func->getStorageClass() == FunctionDecl::Static) { 2230 Diag(Arg->getSourceRange().getBegin(), 2231 diag::err_template_arg_function_not_extern) 2232 << Func << Arg->getSourceRange(); 2233 Diag(Func->getLocation(), diag::note_template_arg_internal_object) 2234 << true; 2235 return true; 2236 } 2237 2238 // Okay: we've named a function with external linkage. 2239 Entity = Func; 2240 return Invalid; 2241 } 2242 2243 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 2244 if (!Var->hasGlobalStorage()) { 2245 Diag(Arg->getSourceRange().getBegin(), 2246 diag::err_template_arg_object_not_extern) 2247 << Var << Arg->getSourceRange(); 2248 Diag(Var->getLocation(), diag::note_template_arg_internal_object) 2249 << true; 2250 return true; 2251 } 2252 2253 // Okay: we've named an object with external linkage 2254 Entity = Var; 2255 return Invalid; 2256 } 2257 2258 // We found something else, but we don't know specifically what it is. 2259 Diag(Arg->getSourceRange().getBegin(), 2260 diag::err_template_arg_not_object_or_func) 2261 << Arg->getSourceRange(); 2262 Diag(DRE->getDecl()->getLocation(), 2263 diag::note_template_arg_refers_here); 2264 return true; 2265} 2266 2267/// \brief Checks whether the given template argument is a pointer to 2268/// member constant according to C++ [temp.arg.nontype]p1. 2269bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, 2270 TemplateArgument &Converted) { 2271 bool Invalid = false; 2272 2273 // See through any implicit casts we added to fix the type. 2274 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 2275 Arg = Cast->getSubExpr(); 2276 2277 // C++0x allows nullptr, and there's no further checking to be done for that. 2278 if (Arg->getType()->isNullPtrType()) 2279 return false; 2280 2281 // C++ [temp.arg.nontype]p1: 2282 // 2283 // A template-argument for a non-type, non-template 2284 // template-parameter shall be one of: [...] 2285 // 2286 // -- a pointer to member expressed as described in 5.3.1. 2287 DeclRefExpr *DRE = 0; 2288 2289 // Ignore (and complain about) any excess parentheses. 2290 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 2291 if (!Invalid) { 2292 Diag(Arg->getSourceRange().getBegin(), 2293 diag::err_template_arg_extra_parens) 2294 << Arg->getSourceRange(); 2295 Invalid = true; 2296 } 2297 2298 Arg = Parens->getSubExpr(); 2299 } 2300 2301 // A pointer-to-member constant written &Class::member. 2302 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 2303 if (UnOp->getOpcode() == UnaryOperator::AddrOf) { 2304 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 2305 if (DRE && !DRE->getQualifier()) 2306 DRE = 0; 2307 } 2308 } 2309 // A constant of pointer-to-member type. 2310 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { 2311 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) { 2312 if (VD->getType()->isMemberPointerType()) { 2313 if (isa<NonTypeTemplateParmDecl>(VD) || 2314 (isa<VarDecl>(VD) && 2315 Context.getCanonicalType(VD->getType()).isConstQualified())) { 2316 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2317 Converted = TemplateArgument(Arg->Retain()); 2318 else 2319 Converted = TemplateArgument(VD->getCanonicalDecl()); 2320 return Invalid; 2321 } 2322 } 2323 } 2324 2325 DRE = 0; 2326 } 2327 2328 if (!DRE) 2329 return Diag(Arg->getSourceRange().getBegin(), 2330 diag::err_template_arg_not_pointer_to_member_form) 2331 << Arg->getSourceRange(); 2332 2333 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) { 2334 assert((isa<FieldDecl>(DRE->getDecl()) || 2335 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && 2336 "Only non-static member pointers can make it here"); 2337 2338 // Okay: this is the address of a non-static member, and therefore 2339 // a member pointer constant. 2340 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2341 Converted = TemplateArgument(Arg->Retain()); 2342 else 2343 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl()); 2344 return Invalid; 2345 } 2346 2347 // We found something else, but we don't know specifically what it is. 2348 Diag(Arg->getSourceRange().getBegin(), 2349 diag::err_template_arg_not_pointer_to_member_form) 2350 << Arg->getSourceRange(); 2351 Diag(DRE->getDecl()->getLocation(), 2352 diag::note_template_arg_refers_here); 2353 return true; 2354} 2355 2356/// \brief Check a template argument against its corresponding 2357/// non-type template parameter. 2358/// 2359/// This routine implements the semantics of C++ [temp.arg.nontype]. 2360/// It returns true if an error occurred, and false otherwise. \p 2361/// InstantiatedParamType is the type of the non-type template 2362/// parameter after it has been instantiated. 2363/// 2364/// If no error was detected, Converted receives the converted template argument. 2365bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 2366 QualType InstantiatedParamType, Expr *&Arg, 2367 TemplateArgument &Converted) { 2368 SourceLocation StartLoc = Arg->getSourceRange().getBegin(); 2369 2370 // If either the parameter has a dependent type or the argument is 2371 // type-dependent, there's nothing we can check now. 2372 // FIXME: Add template argument to Converted! 2373 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) { 2374 // FIXME: Produce a cloned, canonical expression? 2375 Converted = TemplateArgument(Arg); 2376 return false; 2377 } 2378 2379 // C++ [temp.arg.nontype]p5: 2380 // The following conversions are performed on each expression used 2381 // as a non-type template-argument. If a non-type 2382 // template-argument cannot be converted to the type of the 2383 // corresponding template-parameter then the program is 2384 // ill-formed. 2385 // 2386 // -- for a non-type template-parameter of integral or 2387 // enumeration type, integral promotions (4.5) and integral 2388 // conversions (4.7) are applied. 2389 QualType ParamType = InstantiatedParamType; 2390 QualType ArgType = Arg->getType(); 2391 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) { 2392 // C++ [temp.arg.nontype]p1: 2393 // A template-argument for a non-type, non-template 2394 // template-parameter shall be one of: 2395 // 2396 // -- an integral constant-expression of integral or enumeration 2397 // type; or 2398 // -- the name of a non-type template-parameter; or 2399 SourceLocation NonConstantLoc; 2400 llvm::APSInt Value; 2401 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) { 2402 Diag(Arg->getSourceRange().getBegin(), 2403 diag::err_template_arg_not_integral_or_enumeral) 2404 << ArgType << Arg->getSourceRange(); 2405 Diag(Param->getLocation(), diag::note_template_param_here); 2406 return true; 2407 } else if (!Arg->isValueDependent() && 2408 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) { 2409 Diag(NonConstantLoc, diag::err_template_arg_not_ice) 2410 << ArgType << Arg->getSourceRange(); 2411 return true; 2412 } 2413 2414 // FIXME: We need some way to more easily get the unqualified form 2415 // of the types without going all the way to the 2416 // canonical type. 2417 if (Context.getCanonicalType(ParamType).getCVRQualifiers()) 2418 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType(); 2419 if (Context.getCanonicalType(ArgType).getCVRQualifiers()) 2420 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType(); 2421 2422 // Try to convert the argument to the parameter's type. 2423 if (Context.hasSameType(ParamType, ArgType)) { 2424 // Okay: no conversion necessary 2425 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 2426 !ParamType->isEnumeralType()) { 2427 // This is an integral promotion or conversion. 2428 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast); 2429 } else { 2430 // We can't perform this conversion. 2431 Diag(Arg->getSourceRange().getBegin(), 2432 diag::err_template_arg_not_convertible) 2433 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2434 Diag(Param->getLocation(), diag::note_template_param_here); 2435 return true; 2436 } 2437 2438 QualType IntegerType = Context.getCanonicalType(ParamType); 2439 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 2440 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); 2441 2442 if (!Arg->isValueDependent()) { 2443 // Check that an unsigned parameter does not receive a negative 2444 // value. 2445 if (IntegerType->isUnsignedIntegerType() 2446 && (Value.isSigned() && Value.isNegative())) { 2447 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative) 2448 << Value.toString(10) << Param->getType() 2449 << Arg->getSourceRange(); 2450 Diag(Param->getLocation(), diag::note_template_param_here); 2451 return true; 2452 } 2453 2454 // Check that we don't overflow the template parameter type. 2455 unsigned AllowedBits = Context.getTypeSize(IntegerType); 2456 if (Value.getActiveBits() > AllowedBits) { 2457 Diag(Arg->getSourceRange().getBegin(), 2458 diag::err_template_arg_too_large) 2459 << Value.toString(10) << Param->getType() 2460 << Arg->getSourceRange(); 2461 Diag(Param->getLocation(), diag::note_template_param_here); 2462 return true; 2463 } 2464 2465 if (Value.getBitWidth() != AllowedBits) 2466 Value.extOrTrunc(AllowedBits); 2467 Value.setIsSigned(IntegerType->isSignedIntegerType()); 2468 } 2469 2470 // Add the value of this argument to the list of converted 2471 // arguments. We use the bitwidth and signedness of the template 2472 // parameter. 2473 if (Arg->isValueDependent()) { 2474 // The argument is value-dependent. Create a new 2475 // TemplateArgument with the converted expression. 2476 Converted = TemplateArgument(Arg); 2477 return false; 2478 } 2479 2480 Converted = TemplateArgument(Value, 2481 ParamType->isEnumeralType() ? ParamType 2482 : IntegerType); 2483 return false; 2484 } 2485 2486 // Handle pointer-to-function, reference-to-function, and 2487 // pointer-to-member-function all in (roughly) the same way. 2488 if (// -- For a non-type template-parameter of type pointer to 2489 // function, only the function-to-pointer conversion (4.3) is 2490 // applied. If the template-argument represents a set of 2491 // overloaded functions (or a pointer to such), the matching 2492 // function is selected from the set (13.4). 2493 // In C++0x, any std::nullptr_t value can be converted. 2494 (ParamType->isPointerType() && 2495 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) || 2496 // -- For a non-type template-parameter of type reference to 2497 // function, no conversions apply. If the template-argument 2498 // represents a set of overloaded functions, the matching 2499 // function is selected from the set (13.4). 2500 (ParamType->isReferenceType() && 2501 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 2502 // -- For a non-type template-parameter of type pointer to 2503 // member function, no conversions apply. If the 2504 // template-argument represents a set of overloaded member 2505 // functions, the matching member function is selected from 2506 // the set (13.4). 2507 // Again, C++0x allows a std::nullptr_t value. 2508 (ParamType->isMemberPointerType() && 2509 ParamType->getAs<MemberPointerType>()->getPointeeType() 2510 ->isFunctionType())) { 2511 if (Context.hasSameUnqualifiedType(ArgType, 2512 ParamType.getNonReferenceType())) { 2513 // We don't have to do anything: the types already match. 2514 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() || 2515 ParamType->isMemberPointerType())) { 2516 ArgType = ParamType; 2517 if (ParamType->isMemberPointerType()) 2518 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer); 2519 else 2520 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast); 2521 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) { 2522 ArgType = Context.getPointerType(ArgType); 2523 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay); 2524 } else if (FunctionDecl *Fn 2525 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) { 2526 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 2527 return true; 2528 2529 Arg = FixOverloadedFunctionReference(Arg, Fn); 2530 ArgType = Arg->getType(); 2531 if (ArgType->isFunctionType() && ParamType->isPointerType()) { 2532 ArgType = Context.getPointerType(Arg->getType()); 2533 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay); 2534 } 2535 } 2536 2537 if (!Context.hasSameUnqualifiedType(ArgType, 2538 ParamType.getNonReferenceType())) { 2539 // We can't perform this conversion. 2540 Diag(Arg->getSourceRange().getBegin(), 2541 diag::err_template_arg_not_convertible) 2542 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2543 Diag(Param->getLocation(), diag::note_template_param_here); 2544 return true; 2545 } 2546 2547 if (ParamType->isMemberPointerType()) 2548 return CheckTemplateArgumentPointerToMember(Arg, Converted); 2549 2550 NamedDecl *Entity = 0; 2551 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 2552 return true; 2553 2554 if (Entity) 2555 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 2556 Converted = TemplateArgument(Entity); 2557 return false; 2558 } 2559 2560 if (ParamType->isPointerType()) { 2561 // -- for a non-type template-parameter of type pointer to 2562 // object, qualification conversions (4.4) and the 2563 // array-to-pointer conversion (4.2) are applied. 2564 // C++0x also allows a value of std::nullptr_t. 2565 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() && 2566 "Only object pointers allowed here"); 2567 2568 if (ArgType->isNullPtrType()) { 2569 ArgType = ParamType; 2570 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast); 2571 } else if (ArgType->isArrayType()) { 2572 ArgType = Context.getArrayDecayedType(ArgType); 2573 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay); 2574 } 2575 2576 if (IsQualificationConversion(ArgType, ParamType)) { 2577 ArgType = ParamType; 2578 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp); 2579 } 2580 2581 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) { 2582 // We can't perform this conversion. 2583 Diag(Arg->getSourceRange().getBegin(), 2584 diag::err_template_arg_not_convertible) 2585 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2586 Diag(Param->getLocation(), diag::note_template_param_here); 2587 return true; 2588 } 2589 2590 NamedDecl *Entity = 0; 2591 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 2592 return true; 2593 2594 if (Entity) 2595 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 2596 Converted = TemplateArgument(Entity); 2597 return false; 2598 } 2599 2600 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 2601 // -- For a non-type template-parameter of type reference to 2602 // object, no conversions apply. The type referred to by the 2603 // reference may be more cv-qualified than the (otherwise 2604 // identical) type of the template-argument. The 2605 // template-parameter is bound directly to the 2606 // template-argument, which must be an lvalue. 2607 assert(ParamRefType->getPointeeType()->isObjectType() && 2608 "Only object references allowed here"); 2609 2610 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) { 2611 Diag(Arg->getSourceRange().getBegin(), 2612 diag::err_template_arg_no_ref_bind) 2613 << InstantiatedParamType << Arg->getType() 2614 << Arg->getSourceRange(); 2615 Diag(Param->getLocation(), diag::note_template_param_here); 2616 return true; 2617 } 2618 2619 unsigned ParamQuals 2620 = Context.getCanonicalType(ParamType).getCVRQualifiers(); 2621 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers(); 2622 2623 if ((ParamQuals | ArgQuals) != ParamQuals) { 2624 Diag(Arg->getSourceRange().getBegin(), 2625 diag::err_template_arg_ref_bind_ignores_quals) 2626 << InstantiatedParamType << Arg->getType() 2627 << Arg->getSourceRange(); 2628 Diag(Param->getLocation(), diag::note_template_param_here); 2629 return true; 2630 } 2631 2632 NamedDecl *Entity = 0; 2633 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 2634 return true; 2635 2636 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 2637 Converted = TemplateArgument(Entity); 2638 return false; 2639 } 2640 2641 // -- For a non-type template-parameter of type pointer to data 2642 // member, qualification conversions (4.4) are applied. 2643 // C++0x allows std::nullptr_t values. 2644 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 2645 2646 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) { 2647 // Types match exactly: nothing more to do here. 2648 } else if (ArgType->isNullPtrType()) { 2649 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer); 2650 } else if (IsQualificationConversion(ArgType, ParamType)) { 2651 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp); 2652 } else { 2653 // We can't perform this conversion. 2654 Diag(Arg->getSourceRange().getBegin(), 2655 diag::err_template_arg_not_convertible) 2656 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2657 Diag(Param->getLocation(), diag::note_template_param_here); 2658 return true; 2659 } 2660 2661 return CheckTemplateArgumentPointerToMember(Arg, Converted); 2662} 2663 2664/// \brief Check a template argument against its corresponding 2665/// template template parameter. 2666/// 2667/// This routine implements the semantics of C++ [temp.arg.template]. 2668/// It returns true if an error occurred, and false otherwise. 2669bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, 2670 const TemplateArgumentLoc &Arg) { 2671 TemplateName Name = Arg.getArgument().getAsTemplate(); 2672 TemplateDecl *Template = Name.getAsTemplateDecl(); 2673 if (!Template) { 2674 // Any dependent template name is fine. 2675 assert(Name.isDependent() && "Non-dependent template isn't a declaration?"); 2676 return false; 2677 } 2678 2679 // C++ [temp.arg.template]p1: 2680 // A template-argument for a template template-parameter shall be 2681 // the name of a class template, expressed as id-expression. Only 2682 // primary class templates are considered when matching the 2683 // template template argument with the corresponding parameter; 2684 // partial specializations are not considered even if their 2685 // parameter lists match that of the template template parameter. 2686 // 2687 // Note that we also allow template template parameters here, which 2688 // will happen when we are dealing with, e.g., class template 2689 // partial specializations. 2690 if (!isa<ClassTemplateDecl>(Template) && 2691 !isa<TemplateTemplateParmDecl>(Template)) { 2692 assert(isa<FunctionTemplateDecl>(Template) && 2693 "Only function templates are possible here"); 2694 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template); 2695 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 2696 << Template; 2697 } 2698 2699 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 2700 Param->getTemplateParameters(), 2701 true, 2702 TPL_TemplateTemplateArgumentMatch, 2703 Arg.getLocation()); 2704} 2705 2706/// \brief Determine whether the given template parameter lists are 2707/// equivalent. 2708/// 2709/// \param New The new template parameter list, typically written in the 2710/// source code as part of a new template declaration. 2711/// 2712/// \param Old The old template parameter list, typically found via 2713/// name lookup of the template declared with this template parameter 2714/// list. 2715/// 2716/// \param Complain If true, this routine will produce a diagnostic if 2717/// the template parameter lists are not equivalent. 2718/// 2719/// \param Kind describes how we are to match the template parameter lists. 2720/// 2721/// \param TemplateArgLoc If this source location is valid, then we 2722/// are actually checking the template parameter list of a template 2723/// argument (New) against the template parameter list of its 2724/// corresponding template template parameter (Old). We produce 2725/// slightly different diagnostics in this scenario. 2726/// 2727/// \returns True if the template parameter lists are equal, false 2728/// otherwise. 2729bool 2730Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 2731 TemplateParameterList *Old, 2732 bool Complain, 2733 TemplateParameterListEqualKind Kind, 2734 SourceLocation TemplateArgLoc) { 2735 if (Old->size() != New->size()) { 2736 if (Complain) { 2737 unsigned NextDiag = diag::err_template_param_list_different_arity; 2738 if (TemplateArgLoc.isValid()) { 2739 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 2740 NextDiag = diag::note_template_param_list_different_arity; 2741 } 2742 Diag(New->getTemplateLoc(), NextDiag) 2743 << (New->size() > Old->size()) 2744 << (Kind != TPL_TemplateMatch) 2745 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 2746 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 2747 << (Kind != TPL_TemplateMatch) 2748 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 2749 } 2750 2751 return false; 2752 } 2753 2754 for (TemplateParameterList::iterator OldParm = Old->begin(), 2755 OldParmEnd = Old->end(), NewParm = New->begin(); 2756 OldParm != OldParmEnd; ++OldParm, ++NewParm) { 2757 if ((*OldParm)->getKind() != (*NewParm)->getKind()) { 2758 if (Complain) { 2759 unsigned NextDiag = diag::err_template_param_different_kind; 2760 if (TemplateArgLoc.isValid()) { 2761 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 2762 NextDiag = diag::note_template_param_different_kind; 2763 } 2764 Diag((*NewParm)->getLocation(), NextDiag) 2765 << (Kind != TPL_TemplateMatch); 2766 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration) 2767 << (Kind != TPL_TemplateMatch); 2768 } 2769 return false; 2770 } 2771 2772 if (isa<TemplateTypeParmDecl>(*OldParm)) { 2773 // Okay; all template type parameters are equivalent (since we 2774 // know we're at the same index). 2775 } else if (NonTypeTemplateParmDecl *OldNTTP 2776 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) { 2777 // The types of non-type template parameters must agree. 2778 NonTypeTemplateParmDecl *NewNTTP 2779 = cast<NonTypeTemplateParmDecl>(*NewParm); 2780 2781 // If we are matching a template template argument to a template 2782 // template parameter and one of the non-type template parameter types 2783 // is dependent, then we must wait until template instantiation time 2784 // to actually compare the arguments. 2785 if (Kind == TPL_TemplateTemplateArgumentMatch && 2786 (OldNTTP->getType()->isDependentType() || 2787 NewNTTP->getType()->isDependentType())) 2788 continue; 2789 2790 if (Context.getCanonicalType(OldNTTP->getType()) != 2791 Context.getCanonicalType(NewNTTP->getType())) { 2792 if (Complain) { 2793 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 2794 if (TemplateArgLoc.isValid()) { 2795 Diag(TemplateArgLoc, 2796 diag::err_template_arg_template_params_mismatch); 2797 NextDiag = diag::note_template_nontype_parm_different_type; 2798 } 2799 Diag(NewNTTP->getLocation(), NextDiag) 2800 << NewNTTP->getType() 2801 << (Kind != TPL_TemplateMatch); 2802 Diag(OldNTTP->getLocation(), 2803 diag::note_template_nontype_parm_prev_declaration) 2804 << OldNTTP->getType(); 2805 } 2806 return false; 2807 } 2808 } else { 2809 // The template parameter lists of template template 2810 // parameters must agree. 2811 assert(isa<TemplateTemplateParmDecl>(*OldParm) && 2812 "Only template template parameters handled here"); 2813 TemplateTemplateParmDecl *OldTTP 2814 = cast<TemplateTemplateParmDecl>(*OldParm); 2815 TemplateTemplateParmDecl *NewTTP 2816 = cast<TemplateTemplateParmDecl>(*NewParm); 2817 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 2818 OldTTP->getTemplateParameters(), 2819 Complain, 2820 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind), 2821 TemplateArgLoc)) 2822 return false; 2823 } 2824 } 2825 2826 return true; 2827} 2828 2829/// \brief Check whether a template can be declared within this scope. 2830/// 2831/// If the template declaration is valid in this scope, returns 2832/// false. Otherwise, issues a diagnostic and returns true. 2833bool 2834Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 2835 // Find the nearest enclosing declaration scope. 2836 while ((S->getFlags() & Scope::DeclScope) == 0 || 2837 (S->getFlags() & Scope::TemplateParamScope) != 0) 2838 S = S->getParent(); 2839 2840 // C++ [temp]p2: 2841 // A template-declaration can appear only as a namespace scope or 2842 // class scope declaration. 2843 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 2844 if (Ctx && isa<LinkageSpecDecl>(Ctx) && 2845 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx) 2846 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 2847 << TemplateParams->getSourceRange(); 2848 2849 while (Ctx && isa<LinkageSpecDecl>(Ctx)) 2850 Ctx = Ctx->getParent(); 2851 2852 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord())) 2853 return false; 2854 2855 return Diag(TemplateParams->getTemplateLoc(), 2856 diag::err_template_outside_namespace_or_class_scope) 2857 << TemplateParams->getSourceRange(); 2858} 2859 2860/// \brief Determine what kind of template specialization the given declaration 2861/// is. 2862static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) { 2863 if (!D) 2864 return TSK_Undeclared; 2865 2866 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 2867 return Record->getTemplateSpecializationKind(); 2868 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 2869 return Function->getTemplateSpecializationKind(); 2870 if (VarDecl *Var = dyn_cast<VarDecl>(D)) 2871 return Var->getTemplateSpecializationKind(); 2872 2873 return TSK_Undeclared; 2874} 2875 2876/// \brief Check whether a specialization is well-formed in the current 2877/// context. 2878/// 2879/// This routine determines whether a template specialization can be declared 2880/// in the current context (C++ [temp.expl.spec]p2). 2881/// 2882/// \param S the semantic analysis object for which this check is being 2883/// performed. 2884/// 2885/// \param Specialized the entity being specialized or instantiated, which 2886/// may be a kind of template (class template, function template, etc.) or 2887/// a member of a class template (member function, static data member, 2888/// member class). 2889/// 2890/// \param PrevDecl the previous declaration of this entity, if any. 2891/// 2892/// \param Loc the location of the explicit specialization or instantiation of 2893/// this entity. 2894/// 2895/// \param IsPartialSpecialization whether this is a partial specialization of 2896/// a class template. 2897/// 2898/// \returns true if there was an error that we cannot recover from, false 2899/// otherwise. 2900static bool CheckTemplateSpecializationScope(Sema &S, 2901 NamedDecl *Specialized, 2902 NamedDecl *PrevDecl, 2903 SourceLocation Loc, 2904 bool IsPartialSpecialization) { 2905 // Keep these "kind" numbers in sync with the %select statements in the 2906 // various diagnostics emitted by this routine. 2907 int EntityKind = 0; 2908 bool isTemplateSpecialization = false; 2909 if (isa<ClassTemplateDecl>(Specialized)) { 2910 EntityKind = IsPartialSpecialization? 1 : 0; 2911 isTemplateSpecialization = true; 2912 } else if (isa<FunctionTemplateDecl>(Specialized)) { 2913 EntityKind = 2; 2914 isTemplateSpecialization = true; 2915 } else if (isa<CXXMethodDecl>(Specialized)) 2916 EntityKind = 3; 2917 else if (isa<VarDecl>(Specialized)) 2918 EntityKind = 4; 2919 else if (isa<RecordDecl>(Specialized)) 2920 EntityKind = 5; 2921 else { 2922 S.Diag(Loc, diag::err_template_spec_unknown_kind); 2923 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 2924 return true; 2925 } 2926 2927 // C++ [temp.expl.spec]p2: 2928 // An explicit specialization shall be declared in the namespace 2929 // of which the template is a member, or, for member templates, in 2930 // the namespace of which the enclosing class or enclosing class 2931 // template is a member. An explicit specialization of a member 2932 // function, member class or static data member of a class 2933 // template shall be declared in the namespace of which the class 2934 // template is a member. Such a declaration may also be a 2935 // definition. If the declaration is not a definition, the 2936 // specialization may be defined later in the name- space in which 2937 // the explicit specialization was declared, or in a namespace 2938 // that encloses the one in which the explicit specialization was 2939 // declared. 2940 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) { 2941 S.Diag(Loc, diag::err_template_spec_decl_function_scope) 2942 << Specialized; 2943 return true; 2944 } 2945 2946 if (S.CurContext->isRecord() && !IsPartialSpecialization) { 2947 S.Diag(Loc, diag::err_template_spec_decl_class_scope) 2948 << Specialized; 2949 return true; 2950 } 2951 2952 // C++ [temp.class.spec]p6: 2953 // A class template partial specialization may be declared or redeclared 2954 // in any namespace scope in which its definition may be defined (14.5.1 2955 // and 14.5.2). 2956 bool ComplainedAboutScope = false; 2957 DeclContext *SpecializedContext 2958 = Specialized->getDeclContext()->getEnclosingNamespaceContext(); 2959 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext(); 2960 if ((!PrevDecl || 2961 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared || 2962 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){ 2963 // There is no prior declaration of this entity, so this 2964 // specialization must be in the same context as the template 2965 // itself. 2966 if (!DC->Equals(SpecializedContext)) { 2967 if (isa<TranslationUnitDecl>(SpecializedContext)) 2968 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global) 2969 << EntityKind << Specialized; 2970 else if (isa<NamespaceDecl>(SpecializedContext)) 2971 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope) 2972 << EntityKind << Specialized 2973 << cast<NamedDecl>(SpecializedContext); 2974 2975 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 2976 ComplainedAboutScope = true; 2977 } 2978 } 2979 2980 // Make sure that this redeclaration (or definition) occurs in an enclosing 2981 // namespace. 2982 // Note that HandleDeclarator() performs this check for explicit 2983 // specializations of function templates, static data members, and member 2984 // functions, so we skip the check here for those kinds of entities. 2985 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though. 2986 // Should we refactor that check, so that it occurs later? 2987 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) && 2988 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) || 2989 isa<FunctionDecl>(Specialized))) { 2990 if (isa<TranslationUnitDecl>(SpecializedContext)) 2991 S.Diag(Loc, diag::err_template_spec_redecl_global_scope) 2992 << EntityKind << Specialized; 2993 else if (isa<NamespaceDecl>(SpecializedContext)) 2994 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope) 2995 << EntityKind << Specialized 2996 << cast<NamedDecl>(SpecializedContext); 2997 2998 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 2999 } 3000 3001 // FIXME: check for specialization-after-instantiation errors and such. 3002 3003 return false; 3004} 3005 3006/// \brief Check the non-type template arguments of a class template 3007/// partial specialization according to C++ [temp.class.spec]p9. 3008/// 3009/// \param TemplateParams the template parameters of the primary class 3010/// template. 3011/// 3012/// \param TemplateArg the template arguments of the class template 3013/// partial specialization. 3014/// 3015/// \param MirrorsPrimaryTemplate will be set true if the class 3016/// template partial specialization arguments are identical to the 3017/// implicit template arguments of the primary template. This is not 3018/// necessarily an error (C++0x), and it is left to the caller to diagnose 3019/// this condition when it is an error. 3020/// 3021/// \returns true if there was an error, false otherwise. 3022bool Sema::CheckClassTemplatePartialSpecializationArgs( 3023 TemplateParameterList *TemplateParams, 3024 const TemplateArgumentListBuilder &TemplateArgs, 3025 bool &MirrorsPrimaryTemplate) { 3026 // FIXME: the interface to this function will have to change to 3027 // accommodate variadic templates. 3028 MirrorsPrimaryTemplate = true; 3029 3030 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments(); 3031 3032 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 3033 // Determine whether the template argument list of the partial 3034 // specialization is identical to the implicit argument list of 3035 // the primary template. The caller may need to diagnostic this as 3036 // an error per C++ [temp.class.spec]p9b3. 3037 if (MirrorsPrimaryTemplate) { 3038 if (TemplateTypeParmDecl *TTP 3039 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) { 3040 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) != 3041 Context.getCanonicalType(ArgList[I].getAsType())) 3042 MirrorsPrimaryTemplate = false; 3043 } else if (TemplateTemplateParmDecl *TTP 3044 = dyn_cast<TemplateTemplateParmDecl>( 3045 TemplateParams->getParam(I))) { 3046 TemplateName Name = ArgList[I].getAsTemplate(); 3047 TemplateTemplateParmDecl *ArgDecl 3048 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()); 3049 if (!ArgDecl || 3050 ArgDecl->getIndex() != TTP->getIndex() || 3051 ArgDecl->getDepth() != TTP->getDepth()) 3052 MirrorsPrimaryTemplate = false; 3053 } 3054 } 3055 3056 NonTypeTemplateParmDecl *Param 3057 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 3058 if (!Param) { 3059 continue; 3060 } 3061 3062 Expr *ArgExpr = ArgList[I].getAsExpr(); 3063 if (!ArgExpr) { 3064 MirrorsPrimaryTemplate = false; 3065 continue; 3066 } 3067 3068 // C++ [temp.class.spec]p8: 3069 // A non-type argument is non-specialized if it is the name of a 3070 // non-type parameter. All other non-type arguments are 3071 // specialized. 3072 // 3073 // Below, we check the two conditions that only apply to 3074 // specialized non-type arguments, so skip any non-specialized 3075 // arguments. 3076 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 3077 if (NonTypeTemplateParmDecl *NTTP 3078 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) { 3079 if (MirrorsPrimaryTemplate && 3080 (Param->getIndex() != NTTP->getIndex() || 3081 Param->getDepth() != NTTP->getDepth())) 3082 MirrorsPrimaryTemplate = false; 3083 3084 continue; 3085 } 3086 3087 // C++ [temp.class.spec]p9: 3088 // Within the argument list of a class template partial 3089 // specialization, the following restrictions apply: 3090 // -- A partially specialized non-type argument expression 3091 // shall not involve a template parameter of the partial 3092 // specialization except when the argument expression is a 3093 // simple identifier. 3094 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) { 3095 Diag(ArgExpr->getLocStart(), 3096 diag::err_dependent_non_type_arg_in_partial_spec) 3097 << ArgExpr->getSourceRange(); 3098 return true; 3099 } 3100 3101 // -- The type of a template parameter corresponding to a 3102 // specialized non-type argument shall not be dependent on a 3103 // parameter of the specialization. 3104 if (Param->getType()->isDependentType()) { 3105 Diag(ArgExpr->getLocStart(), 3106 diag::err_dependent_typed_non_type_arg_in_partial_spec) 3107 << Param->getType() 3108 << ArgExpr->getSourceRange(); 3109 Diag(Param->getLocation(), diag::note_template_param_here); 3110 return true; 3111 } 3112 3113 MirrorsPrimaryTemplate = false; 3114 } 3115 3116 return false; 3117} 3118 3119Sema::DeclResult 3120Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, 3121 TagUseKind TUK, 3122 SourceLocation KWLoc, 3123 const CXXScopeSpec &SS, 3124 TemplateTy TemplateD, 3125 SourceLocation TemplateNameLoc, 3126 SourceLocation LAngleLoc, 3127 ASTTemplateArgsPtr TemplateArgsIn, 3128 SourceLocation RAngleLoc, 3129 AttributeList *Attr, 3130 MultiTemplateParamsArg TemplateParameterLists) { 3131 assert(TUK != TUK_Reference && "References are not specializations"); 3132 3133 // Find the class template we're specializing 3134 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 3135 ClassTemplateDecl *ClassTemplate 3136 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl()); 3137 3138 if (!ClassTemplate) { 3139 Diag(TemplateNameLoc, diag::err_not_class_template_specialization) 3140 << (Name.getAsTemplateDecl() && 3141 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); 3142 return true; 3143 } 3144 3145 bool isExplicitSpecialization = false; 3146 bool isPartialSpecialization = false; 3147 3148 // Check the validity of the template headers that introduce this 3149 // template. 3150 // FIXME: We probably shouldn't complain about these headers for 3151 // friend declarations. 3152 TemplateParameterList *TemplateParams 3153 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS, 3154 (TemplateParameterList**)TemplateParameterLists.get(), 3155 TemplateParameterLists.size(), 3156 isExplicitSpecialization); 3157 if (TemplateParams && TemplateParams->size() > 0) { 3158 isPartialSpecialization = true; 3159 3160 // C++ [temp.class.spec]p10: 3161 // The template parameter list of a specialization shall not 3162 // contain default template argument values. 3163 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 3164 Decl *Param = TemplateParams->getParam(I); 3165 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 3166 if (TTP->hasDefaultArgument()) { 3167 Diag(TTP->getDefaultArgumentLoc(), 3168 diag::err_default_arg_in_partial_spec); 3169 TTP->removeDefaultArgument(); 3170 } 3171 } else if (NonTypeTemplateParmDecl *NTTP 3172 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 3173 if (Expr *DefArg = NTTP->getDefaultArgument()) { 3174 Diag(NTTP->getDefaultArgumentLoc(), 3175 diag::err_default_arg_in_partial_spec) 3176 << DefArg->getSourceRange(); 3177 NTTP->setDefaultArgument(0); 3178 DefArg->Destroy(Context); 3179 } 3180 } else { 3181 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 3182 if (TTP->hasDefaultArgument()) { 3183 Diag(TTP->getDefaultArgument().getLocation(), 3184 diag::err_default_arg_in_partial_spec) 3185 << TTP->getDefaultArgument().getSourceRange(); 3186 TTP->setDefaultArgument(TemplateArgumentLoc()); 3187 } 3188 } 3189 } 3190 } else if (TemplateParams) { 3191 if (TUK == TUK_Friend) 3192 Diag(KWLoc, diag::err_template_spec_friend) 3193 << CodeModificationHint::CreateRemoval( 3194 SourceRange(TemplateParams->getTemplateLoc(), 3195 TemplateParams->getRAngleLoc())) 3196 << SourceRange(LAngleLoc, RAngleLoc); 3197 else 3198 isExplicitSpecialization = true; 3199 } else if (TUK != TUK_Friend) { 3200 Diag(KWLoc, diag::err_template_spec_needs_header) 3201 << CodeModificationHint::CreateInsertion(KWLoc, "template<> "); 3202 isExplicitSpecialization = true; 3203 } 3204 3205 // Check that the specialization uses the same tag kind as the 3206 // original template. 3207 TagDecl::TagKind Kind; 3208 switch (TagSpec) { 3209 default: assert(0 && "Unknown tag type!"); 3210 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 3211 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 3212 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 3213 } 3214 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 3215 Kind, KWLoc, 3216 *ClassTemplate->getIdentifier())) { 3217 Diag(KWLoc, diag::err_use_with_wrong_tag) 3218 << ClassTemplate 3219 << CodeModificationHint::CreateReplacement(KWLoc, 3220 ClassTemplate->getTemplatedDecl()->getKindName()); 3221 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 3222 diag::note_previous_use); 3223 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 3224 } 3225 3226 // Translate the parser's template argument list in our AST format. 3227 TemplateArgumentListInfo TemplateArgs; 3228 TemplateArgs.setLAngleLoc(LAngleLoc); 3229 TemplateArgs.setRAngleLoc(RAngleLoc); 3230 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 3231 3232 // Check that the template argument list is well-formed for this 3233 // template. 3234 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 3235 TemplateArgs.size()); 3236 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 3237 TemplateArgs, false, Converted)) 3238 return true; 3239 3240 assert((Converted.structuredSize() == 3241 ClassTemplate->getTemplateParameters()->size()) && 3242 "Converted template argument list is too short!"); 3243 3244 // Find the class template (partial) specialization declaration that 3245 // corresponds to these arguments. 3246 llvm::FoldingSetNodeID ID; 3247 if (isPartialSpecialization) { 3248 bool MirrorsPrimaryTemplate; 3249 if (CheckClassTemplatePartialSpecializationArgs( 3250 ClassTemplate->getTemplateParameters(), 3251 Converted, MirrorsPrimaryTemplate)) 3252 return true; 3253 3254 if (MirrorsPrimaryTemplate) { 3255 // C++ [temp.class.spec]p9b3: 3256 // 3257 // -- The argument list of the specialization shall not be identical 3258 // to the implicit argument list of the primary template. 3259 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 3260 << (TUK == TUK_Definition) 3261 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc, 3262 RAngleLoc)); 3263 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, 3264 ClassTemplate->getIdentifier(), 3265 TemplateNameLoc, 3266 Attr, 3267 TemplateParams, 3268 AS_none); 3269 } 3270 3271 // FIXME: Diagnose friend partial specializations 3272 3273 // FIXME: Template parameter list matters, too 3274 ClassTemplatePartialSpecializationDecl::Profile(ID, 3275 Converted.getFlatArguments(), 3276 Converted.flatSize(), 3277 Context); 3278 } else 3279 ClassTemplateSpecializationDecl::Profile(ID, 3280 Converted.getFlatArguments(), 3281 Converted.flatSize(), 3282 Context); 3283 void *InsertPos = 0; 3284 ClassTemplateSpecializationDecl *PrevDecl = 0; 3285 3286 if (isPartialSpecialization) 3287 PrevDecl 3288 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 3289 InsertPos); 3290 else 3291 PrevDecl 3292 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 3293 3294 ClassTemplateSpecializationDecl *Specialization = 0; 3295 3296 // Check whether we can declare a class template specialization in 3297 // the current scope. 3298 if (TUK != TUK_Friend && 3299 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 3300 TemplateNameLoc, 3301 isPartialSpecialization)) 3302 return true; 3303 3304 // The canonical type 3305 QualType CanonType; 3306 if (PrevDecl && 3307 (PrevDecl->getSpecializationKind() == TSK_Undeclared || 3308 TUK == TUK_Friend)) { 3309 // Since the only prior class template specialization with these 3310 // arguments was referenced but not declared, or we're only 3311 // referencing this specialization as a friend, reuse that 3312 // declaration node as our own, updating its source location to 3313 // reflect our new declaration. 3314 Specialization = PrevDecl; 3315 Specialization->setLocation(TemplateNameLoc); 3316 PrevDecl = 0; 3317 CanonType = Context.getTypeDeclType(Specialization); 3318 } else if (isPartialSpecialization) { 3319 // Build the canonical type that describes the converted template 3320 // arguments of the class template partial specialization. 3321 CanonType = Context.getTemplateSpecializationType( 3322 TemplateName(ClassTemplate), 3323 Converted.getFlatArguments(), 3324 Converted.flatSize()); 3325 3326 // Create a new class template partial specialization declaration node. 3327 ClassTemplatePartialSpecializationDecl *PrevPartial 3328 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 3329 ClassTemplatePartialSpecializationDecl *Partial 3330 = ClassTemplatePartialSpecializationDecl::Create(Context, 3331 ClassTemplate->getDeclContext(), 3332 TemplateNameLoc, 3333 TemplateParams, 3334 ClassTemplate, 3335 Converted, 3336 TemplateArgs, 3337 PrevPartial); 3338 3339 if (PrevPartial) { 3340 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial); 3341 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial); 3342 } else { 3343 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos); 3344 } 3345 Specialization = Partial; 3346 3347 // If we are providing an explicit specialization of a member class 3348 // template specialization, make a note of that. 3349 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 3350 PrevPartial->setMemberSpecialization(); 3351 3352 // Check that all of the template parameters of the class template 3353 // partial specialization are deducible from the template 3354 // arguments. If not, this class template partial specialization 3355 // will never be used. 3356 llvm::SmallVector<bool, 8> DeducibleParams; 3357 DeducibleParams.resize(TemplateParams->size()); 3358 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 3359 TemplateParams->getDepth(), 3360 DeducibleParams); 3361 unsigned NumNonDeducible = 0; 3362 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) 3363 if (!DeducibleParams[I]) 3364 ++NumNonDeducible; 3365 3366 if (NumNonDeducible) { 3367 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible) 3368 << (NumNonDeducible > 1) 3369 << SourceRange(TemplateNameLoc, RAngleLoc); 3370 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 3371 if (!DeducibleParams[I]) { 3372 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I)); 3373 if (Param->getDeclName()) 3374 Diag(Param->getLocation(), 3375 diag::note_partial_spec_unused_parameter) 3376 << Param->getDeclName(); 3377 else 3378 Diag(Param->getLocation(), 3379 diag::note_partial_spec_unused_parameter) 3380 << std::string("<anonymous>"); 3381 } 3382 } 3383 } 3384 } else { 3385 // Create a new class template specialization declaration node for 3386 // this explicit specialization or friend declaration. 3387 Specialization 3388 = ClassTemplateSpecializationDecl::Create(Context, 3389 ClassTemplate->getDeclContext(), 3390 TemplateNameLoc, 3391 ClassTemplate, 3392 Converted, 3393 PrevDecl); 3394 3395 if (PrevDecl) { 3396 ClassTemplate->getSpecializations().RemoveNode(PrevDecl); 3397 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization); 3398 } else { 3399 ClassTemplate->getSpecializations().InsertNode(Specialization, 3400 InsertPos); 3401 } 3402 3403 CanonType = Context.getTypeDeclType(Specialization); 3404 } 3405 3406 // C++ [temp.expl.spec]p6: 3407 // If a template, a member template or the member of a class template is 3408 // explicitly specialized then that specialization shall be declared 3409 // before the first use of that specialization that would cause an implicit 3410 // instantiation to take place, in every translation unit in which such a 3411 // use occurs; no diagnostic is required. 3412 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 3413 SourceRange Range(TemplateNameLoc, RAngleLoc); 3414 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 3415 << Context.getTypeDeclType(Specialization) << Range; 3416 3417 Diag(PrevDecl->getPointOfInstantiation(), 3418 diag::note_instantiation_required_here) 3419 << (PrevDecl->getTemplateSpecializationKind() 3420 != TSK_ImplicitInstantiation); 3421 return true; 3422 } 3423 3424 // If this is not a friend, note that this is an explicit specialization. 3425 if (TUK != TUK_Friend) 3426 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 3427 3428 // Check that this isn't a redefinition of this specialization. 3429 if (TUK == TUK_Definition) { 3430 if (RecordDecl *Def = Specialization->getDefinition(Context)) { 3431 SourceRange Range(TemplateNameLoc, RAngleLoc); 3432 Diag(TemplateNameLoc, diag::err_redefinition) 3433 << Context.getTypeDeclType(Specialization) << Range; 3434 Diag(Def->getLocation(), diag::note_previous_definition); 3435 Specialization->setInvalidDecl(); 3436 return true; 3437 } 3438 } 3439 3440 // Build the fully-sugared type for this class template 3441 // specialization as the user wrote in the specialization 3442 // itself. This means that we'll pretty-print the type retrieved 3443 // from the specialization's declaration the way that the user 3444 // actually wrote the specialization, rather than formatting the 3445 // name based on the "canonical" representation used to store the 3446 // template arguments in the specialization. 3447 QualType WrittenTy 3448 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); 3449 if (TUK != TUK_Friend) 3450 Specialization->setTypeAsWritten(WrittenTy); 3451 TemplateArgsIn.release(); 3452 3453 // C++ [temp.expl.spec]p9: 3454 // A template explicit specialization is in the scope of the 3455 // namespace in which the template was defined. 3456 // 3457 // We actually implement this paragraph where we set the semantic 3458 // context (in the creation of the ClassTemplateSpecializationDecl), 3459 // but we also maintain the lexical context where the actual 3460 // definition occurs. 3461 Specialization->setLexicalDeclContext(CurContext); 3462 3463 // We may be starting the definition of this specialization. 3464 if (TUK == TUK_Definition) 3465 Specialization->startDefinition(); 3466 3467 if (TUK == TUK_Friend) { 3468 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 3469 TemplateNameLoc, 3470 WrittenTy.getTypePtr(), 3471 /*FIXME:*/KWLoc); 3472 Friend->setAccess(AS_public); 3473 CurContext->addDecl(Friend); 3474 } else { 3475 // Add the specialization into its lexical context, so that it can 3476 // be seen when iterating through the list of declarations in that 3477 // context. However, specializations are not found by name lookup. 3478 CurContext->addDecl(Specialization); 3479 } 3480 return DeclPtrTy::make(Specialization); 3481} 3482 3483Sema::DeclPtrTy 3484Sema::ActOnTemplateDeclarator(Scope *S, 3485 MultiTemplateParamsArg TemplateParameterLists, 3486 Declarator &D) { 3487 return HandleDeclarator(S, D, move(TemplateParameterLists), false); 3488} 3489 3490Sema::DeclPtrTy 3491Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 3492 MultiTemplateParamsArg TemplateParameterLists, 3493 Declarator &D) { 3494 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 3495 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 3496 "Not a function declarator!"); 3497 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3498 3499 if (FTI.hasPrototype) { 3500 // FIXME: Diagnose arguments without names in C. 3501 } 3502 3503 Scope *ParentScope = FnBodyScope->getParent(); 3504 3505 DeclPtrTy DP = HandleDeclarator(ParentScope, D, 3506 move(TemplateParameterLists), 3507 /*IsFunctionDefinition=*/true); 3508 if (FunctionTemplateDecl *FunctionTemplate 3509 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>())) 3510 return ActOnStartOfFunctionDef(FnBodyScope, 3511 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl())); 3512 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>())) 3513 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function)); 3514 return DeclPtrTy(); 3515} 3516 3517/// \brief Diagnose cases where we have an explicit template specialization 3518/// before/after an explicit template instantiation, producing diagnostics 3519/// for those cases where they are required and determining whether the 3520/// new specialization/instantiation will have any effect. 3521/// 3522/// \param NewLoc the location of the new explicit specialization or 3523/// instantiation. 3524/// 3525/// \param NewTSK the kind of the new explicit specialization or instantiation. 3526/// 3527/// \param PrevDecl the previous declaration of the entity. 3528/// 3529/// \param PrevTSK the kind of the old explicit specialization or instantiatin. 3530/// 3531/// \param PrevPointOfInstantiation if valid, indicates where the previus 3532/// declaration was instantiated (either implicitly or explicitly). 3533/// 3534/// \param SuppressNew will be set to true to indicate that the new 3535/// specialization or instantiation has no effect and should be ignored. 3536/// 3537/// \returns true if there was an error that should prevent the introduction of 3538/// the new declaration into the AST, false otherwise. 3539bool 3540Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 3541 TemplateSpecializationKind NewTSK, 3542 NamedDecl *PrevDecl, 3543 TemplateSpecializationKind PrevTSK, 3544 SourceLocation PrevPointOfInstantiation, 3545 bool &SuppressNew) { 3546 SuppressNew = false; 3547 3548 switch (NewTSK) { 3549 case TSK_Undeclared: 3550 case TSK_ImplicitInstantiation: 3551 assert(false && "Don't check implicit instantiations here"); 3552 return false; 3553 3554 case TSK_ExplicitSpecialization: 3555 switch (PrevTSK) { 3556 case TSK_Undeclared: 3557 case TSK_ExplicitSpecialization: 3558 // Okay, we're just specializing something that is either already 3559 // explicitly specialized or has merely been mentioned without any 3560 // instantiation. 3561 return false; 3562 3563 case TSK_ImplicitInstantiation: 3564 if (PrevPointOfInstantiation.isInvalid()) { 3565 // The declaration itself has not actually been instantiated, so it is 3566 // still okay to specialize it. 3567 return false; 3568 } 3569 // Fall through 3570 3571 case TSK_ExplicitInstantiationDeclaration: 3572 case TSK_ExplicitInstantiationDefinition: 3573 assert((PrevTSK == TSK_ImplicitInstantiation || 3574 PrevPointOfInstantiation.isValid()) && 3575 "Explicit instantiation without point of instantiation?"); 3576 3577 // C++ [temp.expl.spec]p6: 3578 // If a template, a member template or the member of a class template 3579 // is explicitly specialized then that specialization shall be declared 3580 // before the first use of that specialization that would cause an 3581 // implicit instantiation to take place, in every translation unit in 3582 // which such a use occurs; no diagnostic is required. 3583 Diag(NewLoc, diag::err_specialization_after_instantiation) 3584 << PrevDecl; 3585 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) 3586 << (PrevTSK != TSK_ImplicitInstantiation); 3587 3588 return true; 3589 } 3590 break; 3591 3592 case TSK_ExplicitInstantiationDeclaration: 3593 switch (PrevTSK) { 3594 case TSK_ExplicitInstantiationDeclaration: 3595 // This explicit instantiation declaration is redundant (that's okay). 3596 SuppressNew = true; 3597 return false; 3598 3599 case TSK_Undeclared: 3600 case TSK_ImplicitInstantiation: 3601 // We're explicitly instantiating something that may have already been 3602 // implicitly instantiated; that's fine. 3603 return false; 3604 3605 case TSK_ExplicitSpecialization: 3606 // C++0x [temp.explicit]p4: 3607 // For a given set of template parameters, if an explicit instantiation 3608 // of a template appears after a declaration of an explicit 3609 // specialization for that template, the explicit instantiation has no 3610 // effect. 3611 return false; 3612 3613 case TSK_ExplicitInstantiationDefinition: 3614 // C++0x [temp.explicit]p10: 3615 // If an entity is the subject of both an explicit instantiation 3616 // declaration and an explicit instantiation definition in the same 3617 // translation unit, the definition shall follow the declaration. 3618 Diag(NewLoc, 3619 diag::err_explicit_instantiation_declaration_after_definition); 3620 Diag(PrevPointOfInstantiation, 3621 diag::note_explicit_instantiation_definition_here); 3622 assert(PrevPointOfInstantiation.isValid() && 3623 "Explicit instantiation without point of instantiation?"); 3624 SuppressNew = true; 3625 return false; 3626 } 3627 break; 3628 3629 case TSK_ExplicitInstantiationDefinition: 3630 switch (PrevTSK) { 3631 case TSK_Undeclared: 3632 case TSK_ImplicitInstantiation: 3633 // We're explicitly instantiating something that may have already been 3634 // implicitly instantiated; that's fine. 3635 return false; 3636 3637 case TSK_ExplicitSpecialization: 3638 // C++ DR 259, C++0x [temp.explicit]p4: 3639 // For a given set of template parameters, if an explicit 3640 // instantiation of a template appears after a declaration of 3641 // an explicit specialization for that template, the explicit 3642 // instantiation has no effect. 3643 // 3644 // In C++98/03 mode, we only give an extension warning here, because it 3645 // is not not harmful to try to explicitly instantiate something that 3646 // has been explicitly specialized. 3647 if (!getLangOptions().CPlusPlus0x) { 3648 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization) 3649 << PrevDecl; 3650 Diag(PrevDecl->getLocation(), 3651 diag::note_previous_template_specialization); 3652 } 3653 SuppressNew = true; 3654 return false; 3655 3656 case TSK_ExplicitInstantiationDeclaration: 3657 // We're explicity instantiating a definition for something for which we 3658 // were previously asked to suppress instantiations. That's fine. 3659 return false; 3660 3661 case TSK_ExplicitInstantiationDefinition: 3662 // C++0x [temp.spec]p5: 3663 // For a given template and a given set of template-arguments, 3664 // - an explicit instantiation definition shall appear at most once 3665 // in a program, 3666 Diag(NewLoc, diag::err_explicit_instantiation_duplicate) 3667 << PrevDecl; 3668 Diag(PrevPointOfInstantiation, 3669 diag::note_previous_explicit_instantiation); 3670 SuppressNew = true; 3671 return false; 3672 } 3673 break; 3674 } 3675 3676 assert(false && "Missing specialization/instantiation case?"); 3677 3678 return false; 3679} 3680 3681/// \brief Perform semantic analysis for the given function template 3682/// specialization. 3683/// 3684/// This routine performs all of the semantic analysis required for an 3685/// explicit function template specialization. On successful completion, 3686/// the function declaration \p FD will become a function template 3687/// specialization. 3688/// 3689/// \param FD the function declaration, which will be updated to become a 3690/// function template specialization. 3691/// 3692/// \param HasExplicitTemplateArgs whether any template arguments were 3693/// explicitly provided. 3694/// 3695/// \param LAngleLoc the location of the left angle bracket ('<'), if 3696/// template arguments were explicitly provided. 3697/// 3698/// \param ExplicitTemplateArgs the explicitly-provided template arguments, 3699/// if any. 3700/// 3701/// \param NumExplicitTemplateArgs the number of explicitly-provided template 3702/// arguments. This number may be zero even when HasExplicitTemplateArgs is 3703/// true as in, e.g., \c void sort<>(char*, char*); 3704/// 3705/// \param RAngleLoc the location of the right angle bracket ('>'), if 3706/// template arguments were explicitly provided. 3707/// 3708/// \param PrevDecl the set of declarations that 3709bool 3710Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD, 3711 const TemplateArgumentListInfo *ExplicitTemplateArgs, 3712 LookupResult &Previous) { 3713 // The set of function template specializations that could match this 3714 // explicit function template specialization. 3715 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet; 3716 CandidateSet Candidates; 3717 3718 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext(); 3719 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 3720 I != E; ++I) { 3721 NamedDecl *Ovl = (*I)->getUnderlyingDecl(); 3722 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) { 3723 // Only consider templates found within the same semantic lookup scope as 3724 // FD. 3725 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext())) 3726 continue; 3727 3728 // C++ [temp.expl.spec]p11: 3729 // A trailing template-argument can be left unspecified in the 3730 // template-id naming an explicit function template specialization 3731 // provided it can be deduced from the function argument type. 3732 // Perform template argument deduction to determine whether we may be 3733 // specializing this template. 3734 // FIXME: It is somewhat wasteful to build 3735 TemplateDeductionInfo Info(Context); 3736 FunctionDecl *Specialization = 0; 3737 if (TemplateDeductionResult TDK 3738 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs, 3739 FD->getType(), 3740 Specialization, 3741 Info)) { 3742 // FIXME: Template argument deduction failed; record why it failed, so 3743 // that we can provide nifty diagnostics. 3744 (void)TDK; 3745 continue; 3746 } 3747 3748 // Record this candidate. 3749 Candidates.push_back(Specialization); 3750 } 3751 } 3752 3753 // Find the most specialized function template. 3754 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(), 3755 Candidates.size(), 3756 TPOC_Other, 3757 FD->getLocation(), 3758 PartialDiagnostic(diag::err_function_template_spec_no_match) 3759 << FD->getDeclName(), 3760 PartialDiagnostic(diag::err_function_template_spec_ambiguous) 3761 << FD->getDeclName() << (ExplicitTemplateArgs != 0), 3762 PartialDiagnostic(diag::note_function_template_spec_matched)); 3763 if (!Specialization) 3764 return true; 3765 3766 // FIXME: Check if the prior specialization has a point of instantiation. 3767 // If so, we have run afoul of . 3768 3769 // Check the scope of this explicit specialization. 3770 if (CheckTemplateSpecializationScope(*this, 3771 Specialization->getPrimaryTemplate(), 3772 Specialization, FD->getLocation(), 3773 false)) 3774 return true; 3775 3776 // C++ [temp.expl.spec]p6: 3777 // If a template, a member template or the member of a class template is 3778 // explicitly specialized then that specialization shall be declared 3779 // before the first use of that specialization that would cause an implicit 3780 // instantiation to take place, in every translation unit in which such a 3781 // use occurs; no diagnostic is required. 3782 FunctionTemplateSpecializationInfo *SpecInfo 3783 = Specialization->getTemplateSpecializationInfo(); 3784 assert(SpecInfo && "Function template specialization info missing?"); 3785 if (SpecInfo->getPointOfInstantiation().isValid()) { 3786 Diag(FD->getLocation(), diag::err_specialization_after_instantiation) 3787 << FD; 3788 Diag(SpecInfo->getPointOfInstantiation(), 3789 diag::note_instantiation_required_here) 3790 << (Specialization->getTemplateSpecializationKind() 3791 != TSK_ImplicitInstantiation); 3792 return true; 3793 } 3794 3795 // Mark the prior declaration as an explicit specialization, so that later 3796 // clients know that this is an explicit specialization. 3797 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 3798 3799 // Turn the given function declaration into a function template 3800 // specialization, with the template arguments from the previous 3801 // specialization. 3802 FD->setFunctionTemplateSpecialization(Context, 3803 Specialization->getPrimaryTemplate(), 3804 new (Context) TemplateArgumentList( 3805 *Specialization->getTemplateSpecializationArgs()), 3806 /*InsertPos=*/0, 3807 TSK_ExplicitSpecialization); 3808 3809 // The "previous declaration" for this function template specialization is 3810 // the prior function template specialization. 3811 Previous.clear(); 3812 Previous.addDecl(Specialization); 3813 return false; 3814} 3815 3816/// \brief Perform semantic analysis for the given non-template member 3817/// specialization. 3818/// 3819/// This routine performs all of the semantic analysis required for an 3820/// explicit member function specialization. On successful completion, 3821/// the function declaration \p FD will become a member function 3822/// specialization. 3823/// 3824/// \param Member the member declaration, which will be updated to become a 3825/// specialization. 3826/// 3827/// \param Previous the set of declarations, one of which may be specialized 3828/// by this function specialization; the set will be modified to contain the 3829/// redeclared member. 3830bool 3831Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { 3832 assert(!isa<TemplateDecl>(Member) && "Only for non-template members"); 3833 3834 // Try to find the member we are instantiating. 3835 NamedDecl *Instantiation = 0; 3836 NamedDecl *InstantiatedFrom = 0; 3837 MemberSpecializationInfo *MSInfo = 0; 3838 3839 if (Previous.empty()) { 3840 // Nowhere to look anyway. 3841 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) { 3842 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 3843 I != E; ++I) { 3844 NamedDecl *D = (*I)->getUnderlyingDecl(); 3845 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 3846 if (Context.hasSameType(Function->getType(), Method->getType())) { 3847 Instantiation = Method; 3848 InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); 3849 MSInfo = Method->getMemberSpecializationInfo(); 3850 break; 3851 } 3852 } 3853 } 3854 } else if (isa<VarDecl>(Member)) { 3855 VarDecl *PrevVar; 3856 if (Previous.isSingleResult() && 3857 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl()))) 3858 if (PrevVar->isStaticDataMember()) { 3859 Instantiation = PrevVar; 3860 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); 3861 MSInfo = PrevVar->getMemberSpecializationInfo(); 3862 } 3863 } else if (isa<RecordDecl>(Member)) { 3864 CXXRecordDecl *PrevRecord; 3865 if (Previous.isSingleResult() && 3866 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) { 3867 Instantiation = PrevRecord; 3868 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); 3869 MSInfo = PrevRecord->getMemberSpecializationInfo(); 3870 } 3871 } 3872 3873 if (!Instantiation) { 3874 // There is no previous declaration that matches. Since member 3875 // specializations are always out-of-line, the caller will complain about 3876 // this mismatch later. 3877 return false; 3878 } 3879 3880 // Make sure that this is a specialization of a member. 3881 if (!InstantiatedFrom) { 3882 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) 3883 << Member; 3884 Diag(Instantiation->getLocation(), diag::note_specialized_decl); 3885 return true; 3886 } 3887 3888 // C++ [temp.expl.spec]p6: 3889 // If a template, a member template or the member of a class template is 3890 // explicitly specialized then that spe- cialization shall be declared 3891 // before the first use of that specialization that would cause an implicit 3892 // instantiation to take place, in every translation unit in which such a 3893 // use occurs; no diagnostic is required. 3894 assert(MSInfo && "Member specialization info missing?"); 3895 if (MSInfo->getPointOfInstantiation().isValid()) { 3896 Diag(Member->getLocation(), diag::err_specialization_after_instantiation) 3897 << Member; 3898 Diag(MSInfo->getPointOfInstantiation(), 3899 diag::note_instantiation_required_here) 3900 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation); 3901 return true; 3902 } 3903 3904 // Check the scope of this explicit specialization. 3905 if (CheckTemplateSpecializationScope(*this, 3906 InstantiatedFrom, 3907 Instantiation, Member->getLocation(), 3908 false)) 3909 return true; 3910 3911 // Note that this is an explicit instantiation of a member. 3912 // the original declaration to note that it is an explicit specialization 3913 // (if it was previously an implicit instantiation). This latter step 3914 // makes bookkeeping easier. 3915 if (isa<FunctionDecl>(Member)) { 3916 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); 3917 if (InstantiationFunction->getTemplateSpecializationKind() == 3918 TSK_ImplicitInstantiation) { 3919 InstantiationFunction->setTemplateSpecializationKind( 3920 TSK_ExplicitSpecialization); 3921 InstantiationFunction->setLocation(Member->getLocation()); 3922 } 3923 3924 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction( 3925 cast<CXXMethodDecl>(InstantiatedFrom), 3926 TSK_ExplicitSpecialization); 3927 } else if (isa<VarDecl>(Member)) { 3928 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation); 3929 if (InstantiationVar->getTemplateSpecializationKind() == 3930 TSK_ImplicitInstantiation) { 3931 InstantiationVar->setTemplateSpecializationKind( 3932 TSK_ExplicitSpecialization); 3933 InstantiationVar->setLocation(Member->getLocation()); 3934 } 3935 3936 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member), 3937 cast<VarDecl>(InstantiatedFrom), 3938 TSK_ExplicitSpecialization); 3939 } else { 3940 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain"); 3941 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation); 3942 if (InstantiationClass->getTemplateSpecializationKind() == 3943 TSK_ImplicitInstantiation) { 3944 InstantiationClass->setTemplateSpecializationKind( 3945 TSK_ExplicitSpecialization); 3946 InstantiationClass->setLocation(Member->getLocation()); 3947 } 3948 3949 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 3950 cast<CXXRecordDecl>(InstantiatedFrom), 3951 TSK_ExplicitSpecialization); 3952 } 3953 3954 // Save the caller the trouble of having to figure out which declaration 3955 // this specialization matches. 3956 Previous.clear(); 3957 Previous.addDecl(Instantiation); 3958 return false; 3959} 3960 3961/// \brief Check the scope of an explicit instantiation. 3962static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, 3963 SourceLocation InstLoc, 3964 bool WasQualifiedName) { 3965 DeclContext *ExpectedContext 3966 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext(); 3967 DeclContext *CurContext = S.CurContext->getLookupContext(); 3968 3969 // C++0x [temp.explicit]p2: 3970 // An explicit instantiation shall appear in an enclosing namespace of its 3971 // template. 3972 // 3973 // This is DR275, which we do not retroactively apply to C++98/03. 3974 if (S.getLangOptions().CPlusPlus0x && 3975 !CurContext->Encloses(ExpectedContext)) { 3976 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext)) 3977 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope) 3978 << D << NS; 3979 else 3980 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global) 3981 << D; 3982 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 3983 return; 3984 } 3985 3986 // C++0x [temp.explicit]p2: 3987 // If the name declared in the explicit instantiation is an unqualified 3988 // name, the explicit instantiation shall appear in the namespace where 3989 // its template is declared or, if that namespace is inline (7.3.1), any 3990 // namespace from its enclosing namespace set. 3991 if (WasQualifiedName) 3992 return; 3993 3994 if (CurContext->Equals(ExpectedContext)) 3995 return; 3996 3997 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace) 3998 << D << ExpectedContext; 3999 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 4000} 4001 4002/// \brief Determine whether the given scope specifier has a template-id in it. 4003static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { 4004 if (!SS.isSet()) 4005 return false; 4006 4007 // C++0x [temp.explicit]p2: 4008 // If the explicit instantiation is for a member function, a member class 4009 // or a static data member of a class template specialization, the name of 4010 // the class template specialization in the qualified-id for the member 4011 // name shall be a simple-template-id. 4012 // 4013 // C++98 has the same restriction, just worded differently. 4014 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 4015 NNS; NNS = NNS->getPrefix()) 4016 if (Type *T = NNS->getAsType()) 4017 if (isa<TemplateSpecializationType>(T)) 4018 return true; 4019 4020 return false; 4021} 4022 4023// Explicit instantiation of a class template specialization 4024// FIXME: Implement extern template semantics 4025Sema::DeclResult 4026Sema::ActOnExplicitInstantiation(Scope *S, 4027 SourceLocation ExternLoc, 4028 SourceLocation TemplateLoc, 4029 unsigned TagSpec, 4030 SourceLocation KWLoc, 4031 const CXXScopeSpec &SS, 4032 TemplateTy TemplateD, 4033 SourceLocation TemplateNameLoc, 4034 SourceLocation LAngleLoc, 4035 ASTTemplateArgsPtr TemplateArgsIn, 4036 SourceLocation RAngleLoc, 4037 AttributeList *Attr) { 4038 // Find the class template we're specializing 4039 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 4040 ClassTemplateDecl *ClassTemplate 4041 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); 4042 4043 // Check that the specialization uses the same tag kind as the 4044 // original template. 4045 TagDecl::TagKind Kind; 4046 switch (TagSpec) { 4047 default: assert(0 && "Unknown tag type!"); 4048 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 4049 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 4050 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 4051 } 4052 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 4053 Kind, KWLoc, 4054 *ClassTemplate->getIdentifier())) { 4055 Diag(KWLoc, diag::err_use_with_wrong_tag) 4056 << ClassTemplate 4057 << CodeModificationHint::CreateReplacement(KWLoc, 4058 ClassTemplate->getTemplatedDecl()->getKindName()); 4059 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 4060 diag::note_previous_use); 4061 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 4062 } 4063 4064 // C++0x [temp.explicit]p2: 4065 // There are two forms of explicit instantiation: an explicit instantiation 4066 // definition and an explicit instantiation declaration. An explicit 4067 // instantiation declaration begins with the extern keyword. [...] 4068 TemplateSpecializationKind TSK 4069 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 4070 : TSK_ExplicitInstantiationDeclaration; 4071 4072 // Translate the parser's template argument list in our AST format. 4073 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 4074 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 4075 4076 // Check that the template argument list is well-formed for this 4077 // template. 4078 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 4079 TemplateArgs.size()); 4080 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 4081 TemplateArgs, false, Converted)) 4082 return true; 4083 4084 assert((Converted.structuredSize() == 4085 ClassTemplate->getTemplateParameters()->size()) && 4086 "Converted template argument list is too short!"); 4087 4088 // Find the class template specialization declaration that 4089 // corresponds to these arguments. 4090 llvm::FoldingSetNodeID ID; 4091 ClassTemplateSpecializationDecl::Profile(ID, 4092 Converted.getFlatArguments(), 4093 Converted.flatSize(), 4094 Context); 4095 void *InsertPos = 0; 4096 ClassTemplateSpecializationDecl *PrevDecl 4097 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 4098 4099 // C++0x [temp.explicit]p2: 4100 // [...] An explicit instantiation shall appear in an enclosing 4101 // namespace of its template. [...] 4102 // 4103 // This is C++ DR 275. 4104 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc, 4105 SS.isSet()); 4106 4107 ClassTemplateSpecializationDecl *Specialization = 0; 4108 4109 if (PrevDecl) { 4110 bool SuppressNew = false; 4111 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, 4112 PrevDecl, 4113 PrevDecl->getSpecializationKind(), 4114 PrevDecl->getPointOfInstantiation(), 4115 SuppressNew)) 4116 return DeclPtrTy::make(PrevDecl); 4117 4118 if (SuppressNew) 4119 return DeclPtrTy::make(PrevDecl); 4120 4121 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation || 4122 PrevDecl->getSpecializationKind() == TSK_Undeclared) { 4123 // Since the only prior class template specialization with these 4124 // arguments was referenced but not declared, reuse that 4125 // declaration node as our own, updating its source location to 4126 // reflect our new declaration. 4127 Specialization = PrevDecl; 4128 Specialization->setLocation(TemplateNameLoc); 4129 PrevDecl = 0; 4130 } 4131 } 4132 4133 if (!Specialization) { 4134 // Create a new class template specialization declaration node for 4135 // this explicit specialization. 4136 Specialization 4137 = ClassTemplateSpecializationDecl::Create(Context, 4138 ClassTemplate->getDeclContext(), 4139 TemplateNameLoc, 4140 ClassTemplate, 4141 Converted, PrevDecl); 4142 4143 if (PrevDecl) { 4144 // Remove the previous declaration from the folding set, since we want 4145 // to introduce a new declaration. 4146 ClassTemplate->getSpecializations().RemoveNode(PrevDecl); 4147 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 4148 } 4149 4150 // Insert the new specialization. 4151 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos); 4152 } 4153 4154 // Build the fully-sugared type for this explicit instantiation as 4155 // the user wrote in the explicit instantiation itself. This means 4156 // that we'll pretty-print the type retrieved from the 4157 // specialization's declaration the way that the user actually wrote 4158 // the explicit instantiation, rather than formatting the name based 4159 // on the "canonical" representation used to store the template 4160 // arguments in the specialization. 4161 QualType WrittenTy 4162 = Context.getTemplateSpecializationType(Name, TemplateArgs, 4163 Context.getTypeDeclType(Specialization)); 4164 Specialization->setTypeAsWritten(WrittenTy); 4165 TemplateArgsIn.release(); 4166 4167 // Add the explicit instantiation into its lexical context. However, 4168 // since explicit instantiations are never found by name lookup, we 4169 // just put it into the declaration context directly. 4170 Specialization->setLexicalDeclContext(CurContext); 4171 CurContext->addDecl(Specialization); 4172 4173 // C++ [temp.explicit]p3: 4174 // A definition of a class template or class member template 4175 // shall be in scope at the point of the explicit instantiation of 4176 // the class template or class member template. 4177 // 4178 // This check comes when we actually try to perform the 4179 // instantiation. 4180 ClassTemplateSpecializationDecl *Def 4181 = cast_or_null<ClassTemplateSpecializationDecl>( 4182 Specialization->getDefinition(Context)); 4183 if (!Def) 4184 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK); 4185 4186 // Instantiate the members of this class template specialization. 4187 Def = cast_or_null<ClassTemplateSpecializationDecl>( 4188 Specialization->getDefinition(Context)); 4189 if (Def) 4190 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK); 4191 4192 return DeclPtrTy::make(Specialization); 4193} 4194 4195// Explicit instantiation of a member class of a class template. 4196Sema::DeclResult 4197Sema::ActOnExplicitInstantiation(Scope *S, 4198 SourceLocation ExternLoc, 4199 SourceLocation TemplateLoc, 4200 unsigned TagSpec, 4201 SourceLocation KWLoc, 4202 const CXXScopeSpec &SS, 4203 IdentifierInfo *Name, 4204 SourceLocation NameLoc, 4205 AttributeList *Attr) { 4206 4207 bool Owned = false; 4208 bool IsDependent = false; 4209 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference, 4210 KWLoc, SS, Name, NameLoc, Attr, AS_none, 4211 MultiTemplateParamsArg(*this, 0, 0), 4212 Owned, IsDependent); 4213 assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); 4214 4215 if (!TagD) 4216 return true; 4217 4218 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 4219 if (Tag->isEnum()) { 4220 Diag(TemplateLoc, diag::err_explicit_instantiation_enum) 4221 << Context.getTypeDeclType(Tag); 4222 return true; 4223 } 4224 4225 if (Tag->isInvalidDecl()) 4226 return true; 4227 4228 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 4229 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 4230 if (!Pattern) { 4231 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 4232 << Context.getTypeDeclType(Record); 4233 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 4234 return true; 4235 } 4236 4237 // C++0x [temp.explicit]p2: 4238 // If the explicit instantiation is for a class or member class, the 4239 // elaborated-type-specifier in the declaration shall include a 4240 // simple-template-id. 4241 // 4242 // C++98 has the same restriction, just worded differently. 4243 if (!ScopeSpecifierHasTemplateId(SS)) 4244 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id) 4245 << Record << SS.getRange(); 4246 4247 // C++0x [temp.explicit]p2: 4248 // There are two forms of explicit instantiation: an explicit instantiation 4249 // definition and an explicit instantiation declaration. An explicit 4250 // instantiation declaration begins with the extern keyword. [...] 4251 TemplateSpecializationKind TSK 4252 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 4253 : TSK_ExplicitInstantiationDeclaration; 4254 4255 // C++0x [temp.explicit]p2: 4256 // [...] An explicit instantiation shall appear in an enclosing 4257 // namespace of its template. [...] 4258 // 4259 // This is C++ DR 275. 4260 CheckExplicitInstantiationScope(*this, Record, NameLoc, true); 4261 4262 // Verify that it is okay to explicitly instantiate here. 4263 CXXRecordDecl *PrevDecl 4264 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration()); 4265 if (!PrevDecl && Record->getDefinition(Context)) 4266 PrevDecl = Record; 4267 if (PrevDecl) { 4268 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); 4269 bool SuppressNew = false; 4270 assert(MSInfo && "No member specialization information?"); 4271 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, 4272 PrevDecl, 4273 MSInfo->getTemplateSpecializationKind(), 4274 MSInfo->getPointOfInstantiation(), 4275 SuppressNew)) 4276 return true; 4277 if (SuppressNew) 4278 return TagD; 4279 } 4280 4281 CXXRecordDecl *RecordDef 4282 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context)); 4283 if (!RecordDef) { 4284 // C++ [temp.explicit]p3: 4285 // A definition of a member class of a class template shall be in scope 4286 // at the point of an explicit instantiation of the member class. 4287 CXXRecordDecl *Def 4288 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context)); 4289 if (!Def) { 4290 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) 4291 << 0 << Record->getDeclName() << Record->getDeclContext(); 4292 Diag(Pattern->getLocation(), diag::note_forward_declaration) 4293 << Pattern; 4294 return true; 4295 } else { 4296 if (InstantiateClass(NameLoc, Record, Def, 4297 getTemplateInstantiationArgs(Record), 4298 TSK)) 4299 return true; 4300 4301 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context)); 4302 if (!RecordDef) 4303 return true; 4304 } 4305 } 4306 4307 // Instantiate all of the members of the class. 4308 InstantiateClassMembers(NameLoc, RecordDef, 4309 getTemplateInstantiationArgs(Record), TSK); 4310 4311 // FIXME: We don't have any representation for explicit instantiations of 4312 // member classes. Such a representation is not needed for compilation, but it 4313 // should be available for clients that want to see all of the declarations in 4314 // the source code. 4315 return TagD; 4316} 4317 4318Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S, 4319 SourceLocation ExternLoc, 4320 SourceLocation TemplateLoc, 4321 Declarator &D) { 4322 // Explicit instantiations always require a name. 4323 DeclarationName Name = GetNameForDeclarator(D); 4324 if (!Name) { 4325 if (!D.isInvalidType()) 4326 Diag(D.getDeclSpec().getSourceRange().getBegin(), 4327 diag::err_explicit_instantiation_requires_name) 4328 << D.getDeclSpec().getSourceRange() 4329 << D.getSourceRange(); 4330 4331 return true; 4332 } 4333 4334 // The scope passed in may not be a decl scope. Zip up the scope tree until 4335 // we find one that is. 4336 while ((S->getFlags() & Scope::DeclScope) == 0 || 4337 (S->getFlags() & Scope::TemplateParamScope) != 0) 4338 S = S->getParent(); 4339 4340 // Determine the type of the declaration. 4341 QualType R = GetTypeForDeclarator(D, S, 0); 4342 if (R.isNull()) 4343 return true; 4344 4345 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4346 // Cannot explicitly instantiate a typedef. 4347 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) 4348 << Name; 4349 return true; 4350 } 4351 4352 // C++0x [temp.explicit]p1: 4353 // [...] An explicit instantiation of a function template shall not use the 4354 // inline or constexpr specifiers. 4355 // Presumably, this also applies to member functions of class templates as 4356 // well. 4357 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x) 4358 Diag(D.getDeclSpec().getInlineSpecLoc(), 4359 diag::err_explicit_instantiation_inline) 4360 << CodeModificationHint::CreateRemoval( 4361 SourceRange(D.getDeclSpec().getInlineSpecLoc())); 4362 4363 // FIXME: check for constexpr specifier. 4364 4365 // C++0x [temp.explicit]p2: 4366 // There are two forms of explicit instantiation: an explicit instantiation 4367 // definition and an explicit instantiation declaration. An explicit 4368 // instantiation declaration begins with the extern keyword. [...] 4369 TemplateSpecializationKind TSK 4370 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 4371 : TSK_ExplicitInstantiationDeclaration; 4372 4373 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName); 4374 LookupParsedName(Previous, S, &D.getCXXScopeSpec()); 4375 4376 if (!R->isFunctionType()) { 4377 // C++ [temp.explicit]p1: 4378 // A [...] static data member of a class template can be explicitly 4379 // instantiated from the member definition associated with its class 4380 // template. 4381 if (Previous.isAmbiguous()) 4382 return true; 4383 4384 VarDecl *Prev = dyn_cast_or_null<VarDecl>( 4385 Previous.getAsSingleDecl(Context)); 4386 if (!Prev || !Prev->isStaticDataMember()) { 4387 // We expect to see a data data member here. 4388 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) 4389 << Name; 4390 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 4391 P != PEnd; ++P) 4392 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); 4393 return true; 4394 } 4395 4396 if (!Prev->getInstantiatedFromStaticDataMember()) { 4397 // FIXME: Check for explicit specialization? 4398 Diag(D.getIdentifierLoc(), 4399 diag::err_explicit_instantiation_data_member_not_instantiated) 4400 << Prev; 4401 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); 4402 // FIXME: Can we provide a note showing where this was declared? 4403 return true; 4404 } 4405 4406 // C++0x [temp.explicit]p2: 4407 // If the explicit instantiation is for a member function, a member class 4408 // or a static data member of a class template specialization, the name of 4409 // the class template specialization in the qualified-id for the member 4410 // name shall be a simple-template-id. 4411 // 4412 // C++98 has the same restriction, just worded differently. 4413 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 4414 Diag(D.getIdentifierLoc(), 4415 diag::err_explicit_instantiation_without_qualified_id) 4416 << Prev << D.getCXXScopeSpec().getRange(); 4417 4418 // Check the scope of this explicit instantiation. 4419 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true); 4420 4421 // Verify that it is okay to explicitly instantiate here. 4422 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo(); 4423 assert(MSInfo && "Missing static data member specialization info?"); 4424 bool SuppressNew = false; 4425 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, 4426 MSInfo->getTemplateSpecializationKind(), 4427 MSInfo->getPointOfInstantiation(), 4428 SuppressNew)) 4429 return true; 4430 if (SuppressNew) 4431 return DeclPtrTy(); 4432 4433 // Instantiate static data member. 4434 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 4435 if (TSK == TSK_ExplicitInstantiationDefinition) 4436 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false, 4437 /*DefinitionRequired=*/true); 4438 4439 // FIXME: Create an ExplicitInstantiation node? 4440 return DeclPtrTy(); 4441 } 4442 4443 // If the declarator is a template-id, translate the parser's template 4444 // argument list into our AST format. 4445 bool HasExplicitTemplateArgs = false; 4446 TemplateArgumentListInfo TemplateArgs; 4447 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 4448 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 4449 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 4450 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 4451 ASTTemplateArgsPtr TemplateArgsPtr(*this, 4452 TemplateId->getTemplateArgs(), 4453 TemplateId->NumArgs); 4454 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 4455 HasExplicitTemplateArgs = true; 4456 TemplateArgsPtr.release(); 4457 } 4458 4459 // C++ [temp.explicit]p1: 4460 // A [...] function [...] can be explicitly instantiated from its template. 4461 // A member function [...] of a class template can be explicitly 4462 // instantiated from the member definition associated with its class 4463 // template. 4464 llvm::SmallVector<FunctionDecl *, 8> Matches; 4465 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 4466 P != PEnd; ++P) { 4467 NamedDecl *Prev = *P; 4468 if (!HasExplicitTemplateArgs) { 4469 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { 4470 if (Context.hasSameUnqualifiedType(Method->getType(), R)) { 4471 Matches.clear(); 4472 Matches.push_back(Method); 4473 break; 4474 } 4475 } 4476 } 4477 4478 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); 4479 if (!FunTmpl) 4480 continue; 4481 4482 TemplateDeductionInfo Info(Context); 4483 FunctionDecl *Specialization = 0; 4484 if (TemplateDeductionResult TDK 4485 = DeduceTemplateArguments(FunTmpl, 4486 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 4487 R, Specialization, Info)) { 4488 // FIXME: Keep track of almost-matches? 4489 (void)TDK; 4490 continue; 4491 } 4492 4493 Matches.push_back(Specialization); 4494 } 4495 4496 // Find the most specialized function template specialization. 4497 FunctionDecl *Specialization 4498 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other, 4499 D.getIdentifierLoc(), 4500 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name, 4501 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name, 4502 PartialDiagnostic(diag::note_explicit_instantiation_candidate)); 4503 4504 if (!Specialization) 4505 return true; 4506 4507 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { 4508 Diag(D.getIdentifierLoc(), 4509 diag::err_explicit_instantiation_member_function_not_instantiated) 4510 << Specialization 4511 << (Specialization->getTemplateSpecializationKind() == 4512 TSK_ExplicitSpecialization); 4513 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); 4514 return true; 4515 } 4516 4517 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration(); 4518 if (!PrevDecl && Specialization->isThisDeclarationADefinition()) 4519 PrevDecl = Specialization; 4520 4521 if (PrevDecl) { 4522 bool SuppressNew = false; 4523 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, 4524 PrevDecl, 4525 PrevDecl->getTemplateSpecializationKind(), 4526 PrevDecl->getPointOfInstantiation(), 4527 SuppressNew)) 4528 return true; 4529 4530 // FIXME: We may still want to build some representation of this 4531 // explicit specialization. 4532 if (SuppressNew) 4533 return DeclPtrTy(); 4534 } 4535 4536 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 4537 4538 if (TSK == TSK_ExplicitInstantiationDefinition) 4539 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization, 4540 false, /*DefinitionRequired=*/true); 4541 4542 // C++0x [temp.explicit]p2: 4543 // If the explicit instantiation is for a member function, a member class 4544 // or a static data member of a class template specialization, the name of 4545 // the class template specialization in the qualified-id for the member 4546 // name shall be a simple-template-id. 4547 // 4548 // C++98 has the same restriction, just worded differently. 4549 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); 4550 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl && 4551 D.getCXXScopeSpec().isSet() && 4552 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 4553 Diag(D.getIdentifierLoc(), 4554 diag::err_explicit_instantiation_without_qualified_id) 4555 << Specialization << D.getCXXScopeSpec().getRange(); 4556 4557 CheckExplicitInstantiationScope(*this, 4558 FunTmpl? (NamedDecl *)FunTmpl 4559 : Specialization->getInstantiatedFromMemberFunction(), 4560 D.getIdentifierLoc(), 4561 D.getCXXScopeSpec().isSet()); 4562 4563 // FIXME: Create some kind of ExplicitInstantiationDecl here. 4564 return DeclPtrTy(); 4565} 4566 4567Sema::TypeResult 4568Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 4569 const CXXScopeSpec &SS, IdentifierInfo *Name, 4570 SourceLocation TagLoc, SourceLocation NameLoc) { 4571 // This has to hold, because SS is expected to be defined. 4572 assert(Name && "Expected a name in a dependent tag"); 4573 4574 NestedNameSpecifier *NNS 4575 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4576 if (!NNS) 4577 return true; 4578 4579 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc)); 4580 if (T.isNull()) 4581 return true; 4582 4583 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec); 4584 QualType ElabType = Context.getElaboratedType(T, TagKind); 4585 4586 return ElabType.getAsOpaquePtr(); 4587} 4588 4589Sema::TypeResult 4590Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, 4591 const IdentifierInfo &II, SourceLocation IdLoc) { 4592 NestedNameSpecifier *NNS 4593 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4594 if (!NNS) 4595 return true; 4596 4597 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc)); 4598 if (T.isNull()) 4599 return true; 4600 return T.getAsOpaquePtr(); 4601} 4602 4603Sema::TypeResult 4604Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, 4605 SourceLocation TemplateLoc, TypeTy *Ty) { 4606 QualType T = GetTypeFromParser(Ty); 4607 NestedNameSpecifier *NNS 4608 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4609 const TemplateSpecializationType *TemplateId 4610 = T->getAs<TemplateSpecializationType>(); 4611 assert(TemplateId && "Expected a template specialization type"); 4612 4613 if (computeDeclContext(SS, false)) { 4614 // If we can compute a declaration context, then the "typename" 4615 // keyword was superfluous. Just build a QualifiedNameType to keep 4616 // track of the nested-name-specifier. 4617 4618 // FIXME: Note that the QualifiedNameType had the "typename" keyword! 4619 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr(); 4620 } 4621 4622 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr(); 4623} 4624 4625/// \brief Build the type that describes a C++ typename specifier, 4626/// e.g., "typename T::type". 4627QualType 4628Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II, 4629 SourceRange Range) { 4630 CXXRecordDecl *CurrentInstantiation = 0; 4631 if (NNS->isDependent()) { 4632 CurrentInstantiation = getCurrentInstantiationOf(NNS); 4633 4634 // If the nested-name-specifier does not refer to the current 4635 // instantiation, then build a typename type. 4636 if (!CurrentInstantiation) 4637 return Context.getTypenameType(NNS, &II); 4638 4639 // The nested-name-specifier refers to the current instantiation, so the 4640 // "typename" keyword itself is superfluous. In C++03, the program is 4641 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such 4642 // extraneous "typename" keywords, and we retroactively apply this DR to 4643 // C++03 code. 4644 } 4645 4646 DeclContext *Ctx = 0; 4647 4648 if (CurrentInstantiation) 4649 Ctx = CurrentInstantiation; 4650 else { 4651 CXXScopeSpec SS; 4652 SS.setScopeRep(NNS); 4653 SS.setRange(Range); 4654 if (RequireCompleteDeclContext(SS)) 4655 return QualType(); 4656 4657 Ctx = computeDeclContext(SS); 4658 } 4659 assert(Ctx && "No declaration context?"); 4660 4661 DeclarationName Name(&II); 4662 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName); 4663 LookupQualifiedName(Result, Ctx); 4664 unsigned DiagID = 0; 4665 Decl *Referenced = 0; 4666 switch (Result.getResultKind()) { 4667 case LookupResult::NotFound: 4668 DiagID = diag::err_typename_nested_not_found; 4669 break; 4670 4671 case LookupResult::Found: 4672 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) { 4673 // We found a type. Build a QualifiedNameType, since the 4674 // typename-specifier was just sugar. FIXME: Tell 4675 // QualifiedNameType that it has a "typename" prefix. 4676 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type)); 4677 } 4678 4679 DiagID = diag::err_typename_nested_not_type; 4680 Referenced = Result.getFoundDecl(); 4681 break; 4682 4683 case LookupResult::FoundUnresolvedValue: 4684 llvm::llvm_unreachable("unresolved using decl in non-dependent context"); 4685 return QualType(); 4686 4687 case LookupResult::FoundOverloaded: 4688 DiagID = diag::err_typename_nested_not_type; 4689 Referenced = *Result.begin(); 4690 break; 4691 4692 case LookupResult::Ambiguous: 4693 return QualType(); 4694 } 4695 4696 // If we get here, it's because name lookup did not find a 4697 // type. Emit an appropriate diagnostic and return an error. 4698 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx; 4699 if (Referenced) 4700 Diag(Referenced->getLocation(), diag::note_typename_refers_here) 4701 << Name; 4702 return QualType(); 4703} 4704 4705namespace { 4706 // See Sema::RebuildTypeInCurrentInstantiation 4707 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder 4708 : public TreeTransform<CurrentInstantiationRebuilder> { 4709 SourceLocation Loc; 4710 DeclarationName Entity; 4711 4712 public: 4713 CurrentInstantiationRebuilder(Sema &SemaRef, 4714 SourceLocation Loc, 4715 DeclarationName Entity) 4716 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), 4717 Loc(Loc), Entity(Entity) { } 4718 4719 /// \brief Determine whether the given type \p T has already been 4720 /// transformed. 4721 /// 4722 /// For the purposes of type reconstruction, a type has already been 4723 /// transformed if it is NULL or if it is not dependent. 4724 bool AlreadyTransformed(QualType T) { 4725 return T.isNull() || !T->isDependentType(); 4726 } 4727 4728 /// \brief Returns the location of the entity whose type is being 4729 /// rebuilt. 4730 SourceLocation getBaseLocation() { return Loc; } 4731 4732 /// \brief Returns the name of the entity whose type is being rebuilt. 4733 DeclarationName getBaseEntity() { return Entity; } 4734 4735 /// \brief Sets the "base" location and entity when that 4736 /// information is known based on another transformation. 4737 void setBase(SourceLocation Loc, DeclarationName Entity) { 4738 this->Loc = Loc; 4739 this->Entity = Entity; 4740 } 4741 4742 /// \brief Transforms an expression by returning the expression itself 4743 /// (an identity function). 4744 /// 4745 /// FIXME: This is completely unsafe; we will need to actually clone the 4746 /// expressions. 4747 Sema::OwningExprResult TransformExpr(Expr *E) { 4748 return getSema().Owned(E); 4749 } 4750 4751 /// \brief Transforms a typename type by determining whether the type now 4752 /// refers to a member of the current instantiation, and then 4753 /// type-checking and building a QualifiedNameType (when possible). 4754 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL); 4755 }; 4756} 4757 4758QualType 4759CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB, 4760 TypenameTypeLoc TL) { 4761 TypenameType *T = TL.getTypePtr(); 4762 4763 NestedNameSpecifier *NNS 4764 = TransformNestedNameSpecifier(T->getQualifier(), 4765 /*FIXME:*/SourceRange(getBaseLocation())); 4766 if (!NNS) 4767 return QualType(); 4768 4769 // If the nested-name-specifier did not change, and we cannot compute the 4770 // context corresponding to the nested-name-specifier, then this 4771 // typename type will not change; exit early. 4772 CXXScopeSpec SS; 4773 SS.setRange(SourceRange(getBaseLocation())); 4774 SS.setScopeRep(NNS); 4775 4776 QualType Result; 4777 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0) 4778 Result = QualType(T, 0); 4779 4780 // Rebuild the typename type, which will probably turn into a 4781 // QualifiedNameType. 4782 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) { 4783 QualType NewTemplateId 4784 = TransformType(QualType(TemplateId, 0)); 4785 if (NewTemplateId.isNull()) 4786 return QualType(); 4787 4788 if (NNS == T->getQualifier() && 4789 NewTemplateId == QualType(TemplateId, 0)) 4790 Result = QualType(T, 0); 4791 else 4792 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId); 4793 } else 4794 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(), 4795 SourceRange(TL.getNameLoc())); 4796 4797 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result); 4798 NewTL.setNameLoc(TL.getNameLoc()); 4799 return Result; 4800} 4801 4802/// \brief Rebuilds a type within the context of the current instantiation. 4803/// 4804/// The type \p T is part of the type of an out-of-line member definition of 4805/// a class template (or class template partial specialization) that was parsed 4806/// and constructed before we entered the scope of the class template (or 4807/// partial specialization thereof). This routine will rebuild that type now 4808/// that we have entered the declarator's scope, which may produce different 4809/// canonical types, e.g., 4810/// 4811/// \code 4812/// template<typename T> 4813/// struct X { 4814/// typedef T* pointer; 4815/// pointer data(); 4816/// }; 4817/// 4818/// template<typename T> 4819/// typename X<T>::pointer X<T>::data() { ... } 4820/// \endcode 4821/// 4822/// Here, the type "typename X<T>::pointer" will be created as a TypenameType, 4823/// since we do not know that we can look into X<T> when we parsed the type. 4824/// This function will rebuild the type, performing the lookup of "pointer" 4825/// in X<T> and returning a QualifiedNameType whose canonical type is the same 4826/// as the canonical type of T*, allowing the return types of the out-of-line 4827/// definition and the declaration to match. 4828QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc, 4829 DeclarationName Name) { 4830 if (T.isNull() || !T->isDependentType()) 4831 return T; 4832 4833 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); 4834 return Rebuilder.TransformType(T); 4835} 4836 4837/// \brief Produces a formatted string that describes the binding of 4838/// template parameters to template arguments. 4839std::string 4840Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4841 const TemplateArgumentList &Args) { 4842 // FIXME: For variadic templates, we'll need to get the structured list. 4843 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(), 4844 Args.flat_size()); 4845} 4846 4847std::string 4848Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4849 const TemplateArgument *Args, 4850 unsigned NumArgs) { 4851 std::string Result; 4852 4853 if (!Params || Params->size() == 0 || NumArgs == 0) 4854 return Result; 4855 4856 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 4857 if (I >= NumArgs) 4858 break; 4859 4860 if (I == 0) 4861 Result += "[with "; 4862 else 4863 Result += ", "; 4864 4865 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { 4866 Result += Id->getName(); 4867 } else { 4868 Result += '$'; 4869 Result += llvm::utostr(I); 4870 } 4871 4872 Result += " = "; 4873 4874 switch (Args[I].getKind()) { 4875 case TemplateArgument::Null: 4876 Result += "<no value>"; 4877 break; 4878 4879 case TemplateArgument::Type: { 4880 std::string TypeStr; 4881 Args[I].getAsType().getAsStringInternal(TypeStr, 4882 Context.PrintingPolicy); 4883 Result += TypeStr; 4884 break; 4885 } 4886 4887 case TemplateArgument::Declaration: { 4888 bool Unnamed = true; 4889 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) { 4890 if (ND->getDeclName()) { 4891 Unnamed = false; 4892 Result += ND->getNameAsString(); 4893 } 4894 } 4895 4896 if (Unnamed) { 4897 Result += "<anonymous>"; 4898 } 4899 break; 4900 } 4901 4902 case TemplateArgument::Template: { 4903 std::string Str; 4904 llvm::raw_string_ostream OS(Str); 4905 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy); 4906 Result += OS.str(); 4907 break; 4908 } 4909 4910 case TemplateArgument::Integral: { 4911 Result += Args[I].getAsIntegral()->toString(10); 4912 break; 4913 } 4914 4915 case TemplateArgument::Expression: { 4916 assert(false && "No expressions in deduced template arguments!"); 4917 Result += "<expression>"; 4918 break; 4919 } 4920 4921 case TemplateArgument::Pack: 4922 // FIXME: Format template argument packs 4923 Result += "<template argument pack>"; 4924 break; 4925 } 4926 } 4927 4928 Result += ']'; 4929 return Result; 4930} 4931