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