SemaTemplate.cpp revision d5cb8765ad3841ead8eaacb0360ac385f2f0e080
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/// \returns the template parameter list, if any, that corresponds to the 937/// name that is preceded by the scope specifier @p SS. This template 938/// parameter list may be have template parameters (if we're declaring a 939/// template) or may have no template parameters (if we're declaring a 940/// template specialization), or may be NULL (if we were's declaring isn't 941/// itself a template). 942TemplateParameterList * 943Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 944 const CXXScopeSpec &SS, 945 TemplateParameterList **ParamLists, 946 unsigned NumParamLists) { 947 // Find the template-ids that occur within the nested-name-specifier. These 948 // template-ids will match up with the template parameter lists. 949 llvm::SmallVector<const TemplateSpecializationType *, 4> 950 TemplateIdsInSpecifier; 951 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 952 NNS; NNS = NNS->getPrefix()) { 953 if (const TemplateSpecializationType *SpecType 954 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) { 955 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl(); 956 if (!Template) 957 continue; // FIXME: should this be an error? probably... 958 959 if (const RecordType *Record = SpecType->getAs<RecordType>()) { 960 ClassTemplateSpecializationDecl *SpecDecl 961 = cast<ClassTemplateSpecializationDecl>(Record->getDecl()); 962 // If the nested name specifier refers to an explicit specialization, 963 // we don't need a template<> header. 964 // FIXME: revisit this approach once we cope with specializations 965 // properly. 966 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) 967 continue; 968 } 969 970 TemplateIdsInSpecifier.push_back(SpecType); 971 } 972 } 973 974 // Reverse the list of template-ids in the scope specifier, so that we can 975 // more easily match up the template-ids and the template parameter lists. 976 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end()); 977 978 SourceLocation FirstTemplateLoc = DeclStartLoc; 979 if (NumParamLists) 980 FirstTemplateLoc = ParamLists[0]->getTemplateLoc(); 981 982 // Match the template-ids found in the specifier to the template parameter 983 // lists. 984 unsigned Idx = 0; 985 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size(); 986 Idx != NumTemplateIds; ++Idx) { 987 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0); 988 bool DependentTemplateId = TemplateId->isDependentType(); 989 if (Idx >= NumParamLists) { 990 // We have a template-id without a corresponding template parameter 991 // list. 992 if (DependentTemplateId) { 993 // FIXME: the location information here isn't great. 994 Diag(SS.getRange().getBegin(), 995 diag::err_template_spec_needs_template_parameters) 996 << TemplateId 997 << SS.getRange(); 998 } else { 999 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header) 1000 << SS.getRange() 1001 << CodeModificationHint::CreateInsertion(FirstTemplateLoc, 1002 "template<> "); 1003 } 1004 return 0; 1005 } 1006 1007 // Check the template parameter list against its corresponding template-id. 1008 if (DependentTemplateId) { 1009 TemplateDecl *Template 1010 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl(); 1011 1012 if (ClassTemplateDecl *ClassTemplate 1013 = dyn_cast<ClassTemplateDecl>(Template)) { 1014 TemplateParameterList *ExpectedTemplateParams = 0; 1015 // Is this template-id naming the primary template? 1016 if (Context.hasSameType(TemplateId, 1017 ClassTemplate->getInjectedClassNameType(Context))) 1018 ExpectedTemplateParams = ClassTemplate->getTemplateParameters(); 1019 // ... or a partial specialization? 1020 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 1021 = ClassTemplate->findPartialSpecialization(TemplateId)) 1022 ExpectedTemplateParams = PartialSpec->getTemplateParameters(); 1023 1024 if (ExpectedTemplateParams) 1025 TemplateParameterListsAreEqual(ParamLists[Idx], 1026 ExpectedTemplateParams, 1027 true); 1028 } 1029 } else if (ParamLists[Idx]->size() > 0) 1030 Diag(ParamLists[Idx]->getTemplateLoc(), 1031 diag::err_template_param_list_matches_nontemplate) 1032 << TemplateId 1033 << ParamLists[Idx]->getSourceRange(); 1034 } 1035 1036 // If there were at least as many template-ids as there were template 1037 // parameter lists, then there are no template parameter lists remaining for 1038 // the declaration itself. 1039 if (Idx >= NumParamLists) 1040 return 0; 1041 1042 // If there were too many template parameter lists, complain about that now. 1043 if (Idx != NumParamLists - 1) { 1044 while (Idx < NumParamLists - 1) { 1045 Diag(ParamLists[Idx]->getTemplateLoc(), 1046 diag::err_template_spec_extra_headers) 1047 << SourceRange(ParamLists[Idx]->getTemplateLoc(), 1048 ParamLists[Idx]->getRAngleLoc()); 1049 ++Idx; 1050 } 1051 } 1052 1053 // Return the last template parameter list, which corresponds to the 1054 // entity being declared. 1055 return ParamLists[NumParamLists - 1]; 1056} 1057 1058/// \brief Translates template arguments as provided by the parser 1059/// into template arguments used by semantic analysis. 1060void Sema::translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn, 1061 SourceLocation *TemplateArgLocs, 1062 llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) { 1063 TemplateArgs.reserve(TemplateArgsIn.size()); 1064 1065 void **Args = TemplateArgsIn.getArgs(); 1066 bool *ArgIsType = TemplateArgsIn.getArgIsType(); 1067 for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) { 1068 TemplateArgs.push_back( 1069 ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg], 1070 //FIXME: Preserve type source info. 1071 Sema::GetTypeFromParser(Args[Arg])) 1072 : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg]))); 1073 } 1074} 1075 1076QualType Sema::CheckTemplateIdType(TemplateName Name, 1077 SourceLocation TemplateLoc, 1078 SourceLocation LAngleLoc, 1079 const TemplateArgument *TemplateArgs, 1080 unsigned NumTemplateArgs, 1081 SourceLocation RAngleLoc) { 1082 TemplateDecl *Template = Name.getAsTemplateDecl(); 1083 if (!Template) { 1084 // The template name does not resolve to a template, so we just 1085 // build a dependent template-id type. 1086 return Context.getTemplateSpecializationType(Name, TemplateArgs, 1087 NumTemplateArgs); 1088 } 1089 1090 // Check that the template argument list is well-formed for this 1091 // template. 1092 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(), 1093 NumTemplateArgs); 1094 if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc, 1095 TemplateArgs, NumTemplateArgs, RAngleLoc, 1096 false, Converted)) 1097 return QualType(); 1098 1099 assert((Converted.structuredSize() == 1100 Template->getTemplateParameters()->size()) && 1101 "Converted template argument list is too short!"); 1102 1103 QualType CanonType; 1104 1105 if (TemplateSpecializationType::anyDependentTemplateArguments( 1106 TemplateArgs, 1107 NumTemplateArgs)) { 1108 // This class template specialization is a dependent 1109 // type. Therefore, its canonical type is another class template 1110 // specialization type that contains all of the converted 1111 // arguments in canonical form. This ensures that, e.g., A<T> and 1112 // A<T, T> have identical types when A is declared as: 1113 // 1114 // template<typename T, typename U = T> struct A; 1115 TemplateName CanonName = Context.getCanonicalTemplateName(Name); 1116 CanonType = Context.getTemplateSpecializationType(CanonName, 1117 Converted.getFlatArguments(), 1118 Converted.flatSize()); 1119 1120 // FIXME: CanonType is not actually the canonical type, and unfortunately 1121 // it is a TemplateTypeSpecializationType that we will never use again. 1122 // In the future, we need to teach getTemplateSpecializationType to only 1123 // build the canonical type and return that to us. 1124 CanonType = Context.getCanonicalType(CanonType); 1125 } else if (ClassTemplateDecl *ClassTemplate 1126 = dyn_cast<ClassTemplateDecl>(Template)) { 1127 // Find the class template specialization declaration that 1128 // corresponds to these arguments. 1129 llvm::FoldingSetNodeID ID; 1130 ClassTemplateSpecializationDecl::Profile(ID, 1131 Converted.getFlatArguments(), 1132 Converted.flatSize(), 1133 Context); 1134 void *InsertPos = 0; 1135 ClassTemplateSpecializationDecl *Decl 1136 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 1137 if (!Decl) { 1138 // This is the first time we have referenced this class template 1139 // specialization. Create the canonical declaration and add it to 1140 // the set of specializations. 1141 Decl = ClassTemplateSpecializationDecl::Create(Context, 1142 ClassTemplate->getDeclContext(), 1143 ClassTemplate->getLocation(), 1144 ClassTemplate, 1145 Converted, 0); 1146 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos); 1147 Decl->setLexicalDeclContext(CurContext); 1148 } 1149 1150 CanonType = Context.getTypeDeclType(Decl); 1151 } 1152 1153 // Build the fully-sugared type for this class template 1154 // specialization, which refers back to the class template 1155 // specialization we created or found. 1156 //FIXME: Preserve type source info. 1157 return Context.getTemplateSpecializationType(Name, TemplateArgs, 1158 NumTemplateArgs, CanonType); 1159} 1160 1161Action::TypeResult 1162Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc, 1163 SourceLocation LAngleLoc, 1164 ASTTemplateArgsPtr TemplateArgsIn, 1165 SourceLocation *TemplateArgLocs, 1166 SourceLocation RAngleLoc) { 1167 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 1168 1169 // Translate the parser's template argument list in our AST format. 1170 llvm::SmallVector<TemplateArgument, 16> TemplateArgs; 1171 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs); 1172 1173 QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc, 1174 TemplateArgs.data(), 1175 TemplateArgs.size(), 1176 RAngleLoc); 1177 TemplateArgsIn.release(); 1178 1179 if (Result.isNull()) 1180 return true; 1181 1182 return Result.getAsOpaquePtr(); 1183} 1184 1185Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult, 1186 TagUseKind TUK, 1187 DeclSpec::TST TagSpec, 1188 SourceLocation TagLoc) { 1189 if (TypeResult.isInvalid()) 1190 return Sema::TypeResult(); 1191 1192 QualType Type = QualType::getFromOpaquePtr(TypeResult.get()); 1193 1194 // Verify the tag specifier. 1195 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec); 1196 1197 if (const RecordType *RT = Type->getAs<RecordType>()) { 1198 RecordDecl *D = RT->getDecl(); 1199 1200 IdentifierInfo *Id = D->getIdentifier(); 1201 assert(Id && "templated class must have an identifier"); 1202 1203 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) { 1204 Diag(TagLoc, diag::err_use_with_wrong_tag) 1205 << Type 1206 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc), 1207 D->getKindName()); 1208 Diag(D->getLocation(), diag::note_previous_use); 1209 } 1210 } 1211 1212 QualType ElabType = Context.getElaboratedType(Type, TagKind); 1213 1214 return ElabType.getAsOpaquePtr(); 1215} 1216 1217Sema::OwningExprResult Sema::BuildTemplateIdExpr(TemplateName Template, 1218 SourceLocation TemplateNameLoc, 1219 SourceLocation LAngleLoc, 1220 const TemplateArgument *TemplateArgs, 1221 unsigned NumTemplateArgs, 1222 SourceLocation RAngleLoc) { 1223 // FIXME: Can we do any checking at this point? I guess we could check the 1224 // template arguments that we have against the template name, if the template 1225 // name refers to a single template. That's not a terribly common case, 1226 // though. 1227 return Owned(TemplateIdRefExpr::Create(Context, 1228 /*FIXME: New type?*/Context.OverloadTy, 1229 /*FIXME: Necessary?*/0, 1230 /*FIXME: Necessary?*/SourceRange(), 1231 Template, TemplateNameLoc, LAngleLoc, 1232 TemplateArgs, 1233 NumTemplateArgs, RAngleLoc)); 1234} 1235 1236Sema::OwningExprResult Sema::ActOnTemplateIdExpr(TemplateTy TemplateD, 1237 SourceLocation TemplateNameLoc, 1238 SourceLocation LAngleLoc, 1239 ASTTemplateArgsPtr TemplateArgsIn, 1240 SourceLocation *TemplateArgLocs, 1241 SourceLocation RAngleLoc) { 1242 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 1243 1244 // Translate the parser's template argument list in our AST format. 1245 llvm::SmallVector<TemplateArgument, 16> TemplateArgs; 1246 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs); 1247 TemplateArgsIn.release(); 1248 1249 return BuildTemplateIdExpr(Template, TemplateNameLoc, LAngleLoc, 1250 TemplateArgs.data(), TemplateArgs.size(), 1251 RAngleLoc); 1252} 1253 1254Sema::OwningExprResult 1255Sema::ActOnMemberTemplateIdReferenceExpr(Scope *S, ExprArg Base, 1256 SourceLocation OpLoc, 1257 tok::TokenKind OpKind, 1258 const CXXScopeSpec &SS, 1259 TemplateTy TemplateD, 1260 SourceLocation TemplateNameLoc, 1261 SourceLocation LAngleLoc, 1262 ASTTemplateArgsPtr TemplateArgsIn, 1263 SourceLocation *TemplateArgLocs, 1264 SourceLocation RAngleLoc) { 1265 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 1266 1267 // FIXME: We're going to end up looking up the template based on its name, 1268 // twice! 1269 DeclarationName Name; 1270 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl()) 1271 Name = ActualTemplate->getDeclName(); 1272 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl()) 1273 Name = Ovl->getDeclName(); 1274 else 1275 Name = Template.getAsDependentTemplateName()->getName(); 1276 1277 // Translate the parser's template argument list in our AST format. 1278 llvm::SmallVector<TemplateArgument, 16> TemplateArgs; 1279 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs); 1280 TemplateArgsIn.release(); 1281 1282 // Do we have the save the actual template name? We might need it... 1283 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, TemplateNameLoc, 1284 Name, true, LAngleLoc, 1285 TemplateArgs.data(), TemplateArgs.size(), 1286 RAngleLoc, DeclPtrTy(), &SS); 1287} 1288 1289/// \brief Form a dependent template name. 1290/// 1291/// This action forms a dependent template name given the template 1292/// name and its (presumably dependent) scope specifier. For 1293/// example, given "MetaFun::template apply", the scope specifier \p 1294/// SS will be "MetaFun::", \p TemplateKWLoc contains the location 1295/// of the "template" keyword, and "apply" is the \p Name. 1296Sema::TemplateTy 1297Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc, 1298 const IdentifierInfo &Name, 1299 SourceLocation NameLoc, 1300 const CXXScopeSpec &SS, 1301 TypeTy *ObjectType) { 1302 if ((ObjectType && 1303 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) || 1304 (SS.isSet() && computeDeclContext(SS, false))) { 1305 // C++0x [temp.names]p5: 1306 // If a name prefixed by the keyword template is not the name of 1307 // a template, the program is ill-formed. [Note: the keyword 1308 // template may not be applied to non-template members of class 1309 // templates. -end note ] [ Note: as is the case with the 1310 // typename prefix, the template prefix is allowed in cases 1311 // where it is not strictly necessary; i.e., when the 1312 // nested-name-specifier or the expression on the left of the -> 1313 // or . is not dependent on a template-parameter, or the use 1314 // does not appear in the scope of a template. -end note] 1315 // 1316 // Note: C++03 was more strict here, because it banned the use of 1317 // the "template" keyword prior to a template-name that was not a 1318 // dependent name. C++ DR468 relaxed this requirement (the 1319 // "template" keyword is now permitted). We follow the C++0x 1320 // rules, even in C++03 mode, retroactively applying the DR. 1321 TemplateTy Template; 1322 TemplateNameKind TNK = isTemplateName(0, Name, NameLoc, &SS, ObjectType, 1323 false, Template); 1324 if (TNK == TNK_Non_template) { 1325 Diag(NameLoc, diag::err_template_kw_refers_to_non_template) 1326 << &Name; 1327 return TemplateTy(); 1328 } 1329 1330 return Template; 1331 } 1332 1333 NestedNameSpecifier *Qualifier 1334 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 1335 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name)); 1336} 1337 1338bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 1339 const TemplateArgument &Arg, 1340 TemplateArgumentListBuilder &Converted) { 1341 // Check template type parameter. 1342 if (Arg.getKind() != TemplateArgument::Type) { 1343 // C++ [temp.arg.type]p1: 1344 // A template-argument for a template-parameter which is a 1345 // type shall be a type-id. 1346 1347 // We have a template type parameter but the template argument 1348 // is not a type. 1349 Diag(Arg.getLocation(), diag::err_template_arg_must_be_type); 1350 Diag(Param->getLocation(), diag::note_template_param_here); 1351 1352 return true; 1353 } 1354 1355 if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation())) 1356 return true; 1357 1358 // Add the converted template type argument. 1359 Converted.Append( 1360 TemplateArgument(Arg.getLocation(), 1361 Context.getCanonicalType(Arg.getAsType()))); 1362 return false; 1363} 1364 1365/// \brief Check that the given template argument list is well-formed 1366/// for specializing the given template. 1367bool Sema::CheckTemplateArgumentList(TemplateDecl *Template, 1368 SourceLocation TemplateLoc, 1369 SourceLocation LAngleLoc, 1370 const TemplateArgument *TemplateArgs, 1371 unsigned NumTemplateArgs, 1372 SourceLocation RAngleLoc, 1373 bool PartialTemplateArgs, 1374 TemplateArgumentListBuilder &Converted) { 1375 TemplateParameterList *Params = Template->getTemplateParameters(); 1376 unsigned NumParams = Params->size(); 1377 unsigned NumArgs = NumTemplateArgs; 1378 bool Invalid = false; 1379 1380 bool HasParameterPack = 1381 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack(); 1382 1383 if ((NumArgs > NumParams && !HasParameterPack) || 1384 (NumArgs < Params->getMinRequiredArguments() && 1385 !PartialTemplateArgs)) { 1386 // FIXME: point at either the first arg beyond what we can handle, 1387 // or the '>', depending on whether we have too many or too few 1388 // arguments. 1389 SourceRange Range; 1390 if (NumArgs > NumParams) 1391 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc); 1392 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 1393 << (NumArgs > NumParams) 1394 << (isa<ClassTemplateDecl>(Template)? 0 : 1395 isa<FunctionTemplateDecl>(Template)? 1 : 1396 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 1397 << Template << Range; 1398 Diag(Template->getLocation(), diag::note_template_decl_here) 1399 << Params->getSourceRange(); 1400 Invalid = true; 1401 } 1402 1403 // C++ [temp.arg]p1: 1404 // [...] The type and form of each template-argument specified in 1405 // a template-id shall match the type and form specified for the 1406 // corresponding parameter declared by the template in its 1407 // template-parameter-list. 1408 unsigned ArgIdx = 0; 1409 for (TemplateParameterList::iterator Param = Params->begin(), 1410 ParamEnd = Params->end(); 1411 Param != ParamEnd; ++Param, ++ArgIdx) { 1412 if (ArgIdx > NumArgs && PartialTemplateArgs) 1413 break; 1414 1415 // Decode the template argument 1416 TemplateArgument Arg; 1417 if (ArgIdx >= NumArgs) { 1418 // Retrieve the default template argument from the template 1419 // parameter. 1420 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 1421 if (TTP->isParameterPack()) { 1422 // We have an empty argument pack. 1423 Converted.BeginPack(); 1424 Converted.EndPack(); 1425 break; 1426 } 1427 1428 if (!TTP->hasDefaultArgument()) 1429 break; 1430 1431 QualType ArgType = TTP->getDefaultArgument(); 1432 1433 // If the argument type is dependent, instantiate it now based 1434 // on the previously-computed template arguments. 1435 if (ArgType->isDependentType()) { 1436 InstantiatingTemplate Inst(*this, TemplateLoc, 1437 Template, Converted.getFlatArguments(), 1438 Converted.flatSize(), 1439 SourceRange(TemplateLoc, RAngleLoc)); 1440 1441 TemplateArgumentList TemplateArgs(Context, Converted, 1442 /*TakeArgs=*/false); 1443 ArgType = SubstType(ArgType, 1444 MultiLevelTemplateArgumentList(TemplateArgs), 1445 TTP->getDefaultArgumentLoc(), 1446 TTP->getDeclName()); 1447 } 1448 1449 if (ArgType.isNull()) 1450 return true; 1451 1452 Arg = TemplateArgument(TTP->getLocation(), ArgType); 1453 } else if (NonTypeTemplateParmDecl *NTTP 1454 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 1455 if (!NTTP->hasDefaultArgument()) 1456 break; 1457 1458 InstantiatingTemplate Inst(*this, TemplateLoc, 1459 Template, Converted.getFlatArguments(), 1460 Converted.flatSize(), 1461 SourceRange(TemplateLoc, RAngleLoc)); 1462 1463 TemplateArgumentList TemplateArgs(Context, Converted, 1464 /*TakeArgs=*/false); 1465 1466 Sema::OwningExprResult E 1467 = SubstExpr(NTTP->getDefaultArgument(), 1468 MultiLevelTemplateArgumentList(TemplateArgs)); 1469 if (E.isInvalid()) 1470 return true; 1471 1472 Arg = TemplateArgument(E.takeAs<Expr>()); 1473 } else { 1474 TemplateTemplateParmDecl *TempParm 1475 = cast<TemplateTemplateParmDecl>(*Param); 1476 1477 if (!TempParm->hasDefaultArgument()) 1478 break; 1479 1480 // FIXME: Subst default argument 1481 Arg = TemplateArgument(TempParm->getDefaultArgument()); 1482 } 1483 } else { 1484 // Retrieve the template argument produced by the user. 1485 Arg = TemplateArgs[ArgIdx]; 1486 } 1487 1488 1489 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 1490 if (TTP->isParameterPack()) { 1491 Converted.BeginPack(); 1492 // Check all the remaining arguments (if any). 1493 for (; ArgIdx < NumArgs; ++ArgIdx) { 1494 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted)) 1495 Invalid = true; 1496 } 1497 1498 Converted.EndPack(); 1499 } else { 1500 if (CheckTemplateTypeArgument(TTP, Arg, Converted)) 1501 Invalid = true; 1502 } 1503 } else if (NonTypeTemplateParmDecl *NTTP 1504 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 1505 // Check non-type template parameters. 1506 1507 // Do substitution on the type of the non-type template parameter 1508 // with the template arguments we've seen thus far. 1509 QualType NTTPType = NTTP->getType(); 1510 if (NTTPType->isDependentType()) { 1511 // Do substitution on the type of the non-type template parameter. 1512 InstantiatingTemplate Inst(*this, TemplateLoc, 1513 Template, Converted.getFlatArguments(), 1514 Converted.flatSize(), 1515 SourceRange(TemplateLoc, RAngleLoc)); 1516 1517 TemplateArgumentList TemplateArgs(Context, Converted, 1518 /*TakeArgs=*/false); 1519 NTTPType = SubstType(NTTPType, 1520 MultiLevelTemplateArgumentList(TemplateArgs), 1521 NTTP->getLocation(), 1522 NTTP->getDeclName()); 1523 // If that worked, check the non-type template parameter type 1524 // for validity. 1525 if (!NTTPType.isNull()) 1526 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 1527 NTTP->getLocation()); 1528 if (NTTPType.isNull()) { 1529 Invalid = true; 1530 break; 1531 } 1532 } 1533 1534 switch (Arg.getKind()) { 1535 case TemplateArgument::Null: 1536 assert(false && "Should never see a NULL template argument here"); 1537 break; 1538 1539 case TemplateArgument::Expression: { 1540 Expr *E = Arg.getAsExpr(); 1541 TemplateArgument Result; 1542 if (CheckTemplateArgument(NTTP, NTTPType, E, Result)) 1543 Invalid = true; 1544 else 1545 Converted.Append(Result); 1546 break; 1547 } 1548 1549 case TemplateArgument::Declaration: 1550 case TemplateArgument::Integral: 1551 // We've already checked this template argument, so just copy 1552 // it to the list of converted arguments. 1553 Converted.Append(Arg); 1554 break; 1555 1556 case TemplateArgument::Type: 1557 // We have a non-type template parameter but the template 1558 // argument is a type. 1559 1560 // C++ [temp.arg]p2: 1561 // In a template-argument, an ambiguity between a type-id and 1562 // an expression is resolved to a type-id, regardless of the 1563 // form of the corresponding template-parameter. 1564 // 1565 // We warn specifically about this case, since it can be rather 1566 // confusing for users. 1567 if (Arg.getAsType()->isFunctionType()) 1568 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig) 1569 << Arg.getAsType(); 1570 else 1571 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr); 1572 Diag((*Param)->getLocation(), diag::note_template_param_here); 1573 Invalid = true; 1574 break; 1575 1576 case TemplateArgument::Pack: 1577 assert(0 && "FIXME: Implement!"); 1578 break; 1579 } 1580 } else { 1581 // Check template template parameters. 1582 TemplateTemplateParmDecl *TempParm 1583 = cast<TemplateTemplateParmDecl>(*Param); 1584 1585 switch (Arg.getKind()) { 1586 case TemplateArgument::Null: 1587 assert(false && "Should never see a NULL template argument here"); 1588 break; 1589 1590 case TemplateArgument::Expression: { 1591 Expr *ArgExpr = Arg.getAsExpr(); 1592 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) && 1593 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) { 1594 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr))) 1595 Invalid = true; 1596 1597 // Add the converted template argument. 1598 Decl *D 1599 = cast<DeclRefExpr>(ArgExpr)->getDecl()->getCanonicalDecl(); 1600 Converted.Append(TemplateArgument(Arg.getLocation(), D)); 1601 continue; 1602 } 1603 } 1604 // fall through 1605 1606 case TemplateArgument::Type: { 1607 // We have a template template parameter but the template 1608 // argument does not refer to a template. 1609 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template); 1610 Invalid = true; 1611 break; 1612 } 1613 1614 case TemplateArgument::Declaration: 1615 // We've already checked this template argument, so just copy 1616 // it to the list of converted arguments. 1617 Converted.Append(Arg); 1618 break; 1619 1620 case TemplateArgument::Integral: 1621 assert(false && "Integral argument with template template parameter"); 1622 break; 1623 1624 case TemplateArgument::Pack: 1625 assert(0 && "FIXME: Implement!"); 1626 break; 1627 } 1628 } 1629 } 1630 1631 return Invalid; 1632} 1633 1634/// \brief Check a template argument against its corresponding 1635/// template type parameter. 1636/// 1637/// This routine implements the semantics of C++ [temp.arg.type]. It 1638/// returns true if an error occurred, and false otherwise. 1639bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 1640 QualType Arg, SourceLocation ArgLoc) { 1641 // C++ [temp.arg.type]p2: 1642 // A local type, a type with no linkage, an unnamed type or a type 1643 // compounded from any of these types shall not be used as a 1644 // template-argument for a template type-parameter. 1645 // 1646 // FIXME: Perform the recursive and no-linkage type checks. 1647 const TagType *Tag = 0; 1648 if (const EnumType *EnumT = Arg->getAs<EnumType>()) 1649 Tag = EnumT; 1650 else if (const RecordType *RecordT = Arg->getAs<RecordType>()) 1651 Tag = RecordT; 1652 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) 1653 return Diag(ArgLoc, diag::err_template_arg_local_type) 1654 << QualType(Tag, 0); 1655 else if (Tag && !Tag->getDecl()->getDeclName() && 1656 !Tag->getDecl()->getTypedefForAnonDecl()) { 1657 Diag(ArgLoc, diag::err_template_arg_unnamed_type); 1658 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here); 1659 return true; 1660 } 1661 1662 return false; 1663} 1664 1665/// \brief Checks whether the given template argument is the address 1666/// of an object or function according to C++ [temp.arg.nontype]p1. 1667bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg, 1668 NamedDecl *&Entity) { 1669 bool Invalid = false; 1670 1671 // See through any implicit casts we added to fix the type. 1672 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 1673 Arg = Cast->getSubExpr(); 1674 1675 // C++0x allows nullptr, and there's no further checking to be done for that. 1676 if (Arg->getType()->isNullPtrType()) 1677 return false; 1678 1679 // C++ [temp.arg.nontype]p1: 1680 // 1681 // A template-argument for a non-type, non-template 1682 // template-parameter shall be one of: [...] 1683 // 1684 // -- the address of an object or function with external 1685 // linkage, including function templates and function 1686 // template-ids but excluding non-static class members, 1687 // expressed as & id-expression where the & is optional if 1688 // the name refers to a function or array, or if the 1689 // corresponding template-parameter is a reference; or 1690 DeclRefExpr *DRE = 0; 1691 1692 // Ignore (and complain about) any excess parentheses. 1693 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 1694 if (!Invalid) { 1695 Diag(Arg->getSourceRange().getBegin(), 1696 diag::err_template_arg_extra_parens) 1697 << Arg->getSourceRange(); 1698 Invalid = true; 1699 } 1700 1701 Arg = Parens->getSubExpr(); 1702 } 1703 1704 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 1705 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 1706 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 1707 } else 1708 DRE = dyn_cast<DeclRefExpr>(Arg); 1709 1710 if (!DRE || !isa<ValueDecl>(DRE->getDecl())) 1711 return Diag(Arg->getSourceRange().getBegin(), 1712 diag::err_template_arg_not_object_or_func_form) 1713 << Arg->getSourceRange(); 1714 1715 // Cannot refer to non-static data members 1716 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) 1717 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field) 1718 << Field << Arg->getSourceRange(); 1719 1720 // Cannot refer to non-static member functions 1721 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl())) 1722 if (!Method->isStatic()) 1723 return Diag(Arg->getSourceRange().getBegin(), 1724 diag::err_template_arg_method) 1725 << Method << Arg->getSourceRange(); 1726 1727 // Functions must have external linkage. 1728 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) { 1729 if (Func->getStorageClass() == FunctionDecl::Static) { 1730 Diag(Arg->getSourceRange().getBegin(), 1731 diag::err_template_arg_function_not_extern) 1732 << Func << Arg->getSourceRange(); 1733 Diag(Func->getLocation(), diag::note_template_arg_internal_object) 1734 << true; 1735 return true; 1736 } 1737 1738 // Okay: we've named a function with external linkage. 1739 Entity = Func; 1740 return Invalid; 1741 } 1742 1743 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 1744 if (!Var->hasGlobalStorage()) { 1745 Diag(Arg->getSourceRange().getBegin(), 1746 diag::err_template_arg_object_not_extern) 1747 << Var << Arg->getSourceRange(); 1748 Diag(Var->getLocation(), diag::note_template_arg_internal_object) 1749 << true; 1750 return true; 1751 } 1752 1753 // Okay: we've named an object with external linkage 1754 Entity = Var; 1755 return Invalid; 1756 } 1757 1758 // We found something else, but we don't know specifically what it is. 1759 Diag(Arg->getSourceRange().getBegin(), 1760 diag::err_template_arg_not_object_or_func) 1761 << Arg->getSourceRange(); 1762 Diag(DRE->getDecl()->getLocation(), 1763 diag::note_template_arg_refers_here); 1764 return true; 1765} 1766 1767/// \brief Checks whether the given template argument is a pointer to 1768/// member constant according to C++ [temp.arg.nontype]p1. 1769bool 1770Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) { 1771 bool Invalid = false; 1772 1773 // See through any implicit casts we added to fix the type. 1774 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 1775 Arg = Cast->getSubExpr(); 1776 1777 // C++0x allows nullptr, and there's no further checking to be done for that. 1778 if (Arg->getType()->isNullPtrType()) 1779 return false; 1780 1781 // C++ [temp.arg.nontype]p1: 1782 // 1783 // A template-argument for a non-type, non-template 1784 // template-parameter shall be one of: [...] 1785 // 1786 // -- a pointer to member expressed as described in 5.3.1. 1787 QualifiedDeclRefExpr *DRE = 0; 1788 1789 // Ignore (and complain about) any excess parentheses. 1790 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 1791 if (!Invalid) { 1792 Diag(Arg->getSourceRange().getBegin(), 1793 diag::err_template_arg_extra_parens) 1794 << Arg->getSourceRange(); 1795 Invalid = true; 1796 } 1797 1798 Arg = Parens->getSubExpr(); 1799 } 1800 1801 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) 1802 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 1803 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr()); 1804 1805 if (!DRE) 1806 return Diag(Arg->getSourceRange().getBegin(), 1807 diag::err_template_arg_not_pointer_to_member_form) 1808 << Arg->getSourceRange(); 1809 1810 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) { 1811 assert((isa<FieldDecl>(DRE->getDecl()) || 1812 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && 1813 "Only non-static member pointers can make it here"); 1814 1815 // Okay: this is the address of a non-static member, and therefore 1816 // a member pointer constant. 1817 Member = DRE->getDecl(); 1818 return Invalid; 1819 } 1820 1821 // We found something else, but we don't know specifically what it is. 1822 Diag(Arg->getSourceRange().getBegin(), 1823 diag::err_template_arg_not_pointer_to_member_form) 1824 << Arg->getSourceRange(); 1825 Diag(DRE->getDecl()->getLocation(), 1826 diag::note_template_arg_refers_here); 1827 return true; 1828} 1829 1830/// \brief Check a template argument against its corresponding 1831/// non-type template parameter. 1832/// 1833/// This routine implements the semantics of C++ [temp.arg.nontype]. 1834/// It returns true if an error occurred, and false otherwise. \p 1835/// InstantiatedParamType is the type of the non-type template 1836/// parameter after it has been instantiated. 1837/// 1838/// If no error was detected, Converted receives the converted template argument. 1839bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 1840 QualType InstantiatedParamType, Expr *&Arg, 1841 TemplateArgument &Converted) { 1842 SourceLocation StartLoc = Arg->getSourceRange().getBegin(); 1843 1844 // If either the parameter has a dependent type or the argument is 1845 // type-dependent, there's nothing we can check now. 1846 // FIXME: Add template argument to Converted! 1847 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) { 1848 // FIXME: Produce a cloned, canonical expression? 1849 Converted = TemplateArgument(Arg); 1850 return false; 1851 } 1852 1853 // C++ [temp.arg.nontype]p5: 1854 // The following conversions are performed on each expression used 1855 // as a non-type template-argument. If a non-type 1856 // template-argument cannot be converted to the type of the 1857 // corresponding template-parameter then the program is 1858 // ill-formed. 1859 // 1860 // -- for a non-type template-parameter of integral or 1861 // enumeration type, integral promotions (4.5) and integral 1862 // conversions (4.7) are applied. 1863 QualType ParamType = InstantiatedParamType; 1864 QualType ArgType = Arg->getType(); 1865 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) { 1866 // C++ [temp.arg.nontype]p1: 1867 // A template-argument for a non-type, non-template 1868 // template-parameter shall be one of: 1869 // 1870 // -- an integral constant-expression of integral or enumeration 1871 // type; or 1872 // -- the name of a non-type template-parameter; or 1873 SourceLocation NonConstantLoc; 1874 llvm::APSInt Value; 1875 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) { 1876 Diag(Arg->getSourceRange().getBegin(), 1877 diag::err_template_arg_not_integral_or_enumeral) 1878 << ArgType << Arg->getSourceRange(); 1879 Diag(Param->getLocation(), diag::note_template_param_here); 1880 return true; 1881 } else if (!Arg->isValueDependent() && 1882 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) { 1883 Diag(NonConstantLoc, diag::err_template_arg_not_ice) 1884 << ArgType << Arg->getSourceRange(); 1885 return true; 1886 } 1887 1888 // FIXME: We need some way to more easily get the unqualified form 1889 // of the types without going all the way to the 1890 // canonical type. 1891 if (Context.getCanonicalType(ParamType).getCVRQualifiers()) 1892 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType(); 1893 if (Context.getCanonicalType(ArgType).getCVRQualifiers()) 1894 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType(); 1895 1896 // Try to convert the argument to the parameter's type. 1897 if (ParamType == ArgType) { 1898 // Okay: no conversion necessary 1899 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 1900 !ParamType->isEnumeralType()) { 1901 // This is an integral promotion or conversion. 1902 ImpCastExprToType(Arg, ParamType); 1903 } else { 1904 // We can't perform this conversion. 1905 Diag(Arg->getSourceRange().getBegin(), 1906 diag::err_template_arg_not_convertible) 1907 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 1908 Diag(Param->getLocation(), diag::note_template_param_here); 1909 return true; 1910 } 1911 1912 QualType IntegerType = Context.getCanonicalType(ParamType); 1913 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 1914 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); 1915 1916 if (!Arg->isValueDependent()) { 1917 // Check that an unsigned parameter does not receive a negative 1918 // value. 1919 if (IntegerType->isUnsignedIntegerType() 1920 && (Value.isSigned() && Value.isNegative())) { 1921 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative) 1922 << Value.toString(10) << Param->getType() 1923 << Arg->getSourceRange(); 1924 Diag(Param->getLocation(), diag::note_template_param_here); 1925 return true; 1926 } 1927 1928 // Check that we don't overflow the template parameter type. 1929 unsigned AllowedBits = Context.getTypeSize(IntegerType); 1930 if (Value.getActiveBits() > AllowedBits) { 1931 Diag(Arg->getSourceRange().getBegin(), 1932 diag::err_template_arg_too_large) 1933 << Value.toString(10) << Param->getType() 1934 << Arg->getSourceRange(); 1935 Diag(Param->getLocation(), diag::note_template_param_here); 1936 return true; 1937 } 1938 1939 if (Value.getBitWidth() != AllowedBits) 1940 Value.extOrTrunc(AllowedBits); 1941 Value.setIsSigned(IntegerType->isSignedIntegerType()); 1942 } 1943 1944 // Add the value of this argument to the list of converted 1945 // arguments. We use the bitwidth and signedness of the template 1946 // parameter. 1947 if (Arg->isValueDependent()) { 1948 // The argument is value-dependent. Create a new 1949 // TemplateArgument with the converted expression. 1950 Converted = TemplateArgument(Arg); 1951 return false; 1952 } 1953 1954 Converted = TemplateArgument(StartLoc, Value, 1955 ParamType->isEnumeralType() ? ParamType 1956 : IntegerType); 1957 return false; 1958 } 1959 1960 // Handle pointer-to-function, reference-to-function, and 1961 // pointer-to-member-function all in (roughly) the same way. 1962 if (// -- For a non-type template-parameter of type pointer to 1963 // function, only the function-to-pointer conversion (4.3) is 1964 // applied. If the template-argument represents a set of 1965 // overloaded functions (or a pointer to such), the matching 1966 // function is selected from the set (13.4). 1967 // In C++0x, any std::nullptr_t value can be converted. 1968 (ParamType->isPointerType() && 1969 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) || 1970 // -- For a non-type template-parameter of type reference to 1971 // function, no conversions apply. If the template-argument 1972 // represents a set of overloaded functions, the matching 1973 // function is selected from the set (13.4). 1974 (ParamType->isReferenceType() && 1975 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 1976 // -- For a non-type template-parameter of type pointer to 1977 // member function, no conversions apply. If the 1978 // template-argument represents a set of overloaded member 1979 // functions, the matching member function is selected from 1980 // the set (13.4). 1981 // Again, C++0x allows a std::nullptr_t value. 1982 (ParamType->isMemberPointerType() && 1983 ParamType->getAs<MemberPointerType>()->getPointeeType() 1984 ->isFunctionType())) { 1985 if (Context.hasSameUnqualifiedType(ArgType, 1986 ParamType.getNonReferenceType())) { 1987 // We don't have to do anything: the types already match. 1988 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() || 1989 ParamType->isMemberPointerType())) { 1990 ArgType = ParamType; 1991 ImpCastExprToType(Arg, ParamType); 1992 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) { 1993 ArgType = Context.getPointerType(ArgType); 1994 ImpCastExprToType(Arg, ArgType); 1995 } else if (FunctionDecl *Fn 1996 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) { 1997 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 1998 return true; 1999 2000 FixOverloadedFunctionReference(Arg, Fn); 2001 ArgType = Arg->getType(); 2002 if (ArgType->isFunctionType() && ParamType->isPointerType()) { 2003 ArgType = Context.getPointerType(Arg->getType()); 2004 ImpCastExprToType(Arg, ArgType); 2005 } 2006 } 2007 2008 if (!Context.hasSameUnqualifiedType(ArgType, 2009 ParamType.getNonReferenceType())) { 2010 // We can't perform this conversion. 2011 Diag(Arg->getSourceRange().getBegin(), 2012 diag::err_template_arg_not_convertible) 2013 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2014 Diag(Param->getLocation(), diag::note_template_param_here); 2015 return true; 2016 } 2017 2018 if (ParamType->isMemberPointerType()) { 2019 NamedDecl *Member = 0; 2020 if (CheckTemplateArgumentPointerToMember(Arg, Member)) 2021 return true; 2022 2023 if (Member) 2024 Member = cast<NamedDecl>(Member->getCanonicalDecl()); 2025 Converted = TemplateArgument(StartLoc, Member); 2026 return false; 2027 } 2028 2029 NamedDecl *Entity = 0; 2030 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 2031 return true; 2032 2033 if (Entity) 2034 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 2035 Converted = TemplateArgument(StartLoc, Entity); 2036 return false; 2037 } 2038 2039 if (ParamType->isPointerType()) { 2040 // -- for a non-type template-parameter of type pointer to 2041 // object, qualification conversions (4.4) and the 2042 // array-to-pointer conversion (4.2) are applied. 2043 // C++0x also allows a value of std::nullptr_t. 2044 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() && 2045 "Only object pointers allowed here"); 2046 2047 if (ArgType->isNullPtrType()) { 2048 ArgType = ParamType; 2049 ImpCastExprToType(Arg, ParamType); 2050 } else if (ArgType->isArrayType()) { 2051 ArgType = Context.getArrayDecayedType(ArgType); 2052 ImpCastExprToType(Arg, ArgType); 2053 } 2054 2055 if (IsQualificationConversion(ArgType, ParamType)) { 2056 ArgType = ParamType; 2057 ImpCastExprToType(Arg, ParamType); 2058 } 2059 2060 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) { 2061 // We can't perform this conversion. 2062 Diag(Arg->getSourceRange().getBegin(), 2063 diag::err_template_arg_not_convertible) 2064 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2065 Diag(Param->getLocation(), diag::note_template_param_here); 2066 return true; 2067 } 2068 2069 NamedDecl *Entity = 0; 2070 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 2071 return true; 2072 2073 if (Entity) 2074 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 2075 Converted = TemplateArgument(StartLoc, Entity); 2076 return false; 2077 } 2078 2079 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 2080 // -- For a non-type template-parameter of type reference to 2081 // object, no conversions apply. The type referred to by the 2082 // reference may be more cv-qualified than the (otherwise 2083 // identical) type of the template-argument. The 2084 // template-parameter is bound directly to the 2085 // template-argument, which must be an lvalue. 2086 assert(ParamRefType->getPointeeType()->isObjectType() && 2087 "Only object references allowed here"); 2088 2089 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) { 2090 Diag(Arg->getSourceRange().getBegin(), 2091 diag::err_template_arg_no_ref_bind) 2092 << InstantiatedParamType << Arg->getType() 2093 << Arg->getSourceRange(); 2094 Diag(Param->getLocation(), diag::note_template_param_here); 2095 return true; 2096 } 2097 2098 unsigned ParamQuals 2099 = Context.getCanonicalType(ParamType).getCVRQualifiers(); 2100 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers(); 2101 2102 if ((ParamQuals | ArgQuals) != ParamQuals) { 2103 Diag(Arg->getSourceRange().getBegin(), 2104 diag::err_template_arg_ref_bind_ignores_quals) 2105 << InstantiatedParamType << Arg->getType() 2106 << Arg->getSourceRange(); 2107 Diag(Param->getLocation(), diag::note_template_param_here); 2108 return true; 2109 } 2110 2111 NamedDecl *Entity = 0; 2112 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 2113 return true; 2114 2115 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 2116 Converted = TemplateArgument(StartLoc, Entity); 2117 return false; 2118 } 2119 2120 // -- For a non-type template-parameter of type pointer to data 2121 // member, qualification conversions (4.4) are applied. 2122 // C++0x allows std::nullptr_t values. 2123 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 2124 2125 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) { 2126 // Types match exactly: nothing more to do here. 2127 } else if (ArgType->isNullPtrType()) { 2128 ImpCastExprToType(Arg, ParamType); 2129 } else if (IsQualificationConversion(ArgType, ParamType)) { 2130 ImpCastExprToType(Arg, ParamType); 2131 } else { 2132 // We can't perform this conversion. 2133 Diag(Arg->getSourceRange().getBegin(), 2134 diag::err_template_arg_not_convertible) 2135 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2136 Diag(Param->getLocation(), diag::note_template_param_here); 2137 return true; 2138 } 2139 2140 NamedDecl *Member = 0; 2141 if (CheckTemplateArgumentPointerToMember(Arg, Member)) 2142 return true; 2143 2144 if (Member) 2145 Member = cast<NamedDecl>(Member->getCanonicalDecl()); 2146 Converted = TemplateArgument(StartLoc, Member); 2147 return false; 2148} 2149 2150/// \brief Check a template argument against its corresponding 2151/// template template parameter. 2152/// 2153/// This routine implements the semantics of C++ [temp.arg.template]. 2154/// It returns true if an error occurred, and false otherwise. 2155bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, 2156 DeclRefExpr *Arg) { 2157 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed"); 2158 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl()); 2159 2160 // C++ [temp.arg.template]p1: 2161 // A template-argument for a template template-parameter shall be 2162 // the name of a class template, expressed as id-expression. Only 2163 // primary class templates are considered when matching the 2164 // template template argument with the corresponding parameter; 2165 // partial specializations are not considered even if their 2166 // parameter lists match that of the template template parameter. 2167 // 2168 // Note that we also allow template template parameters here, which 2169 // will happen when we are dealing with, e.g., class template 2170 // partial specializations. 2171 if (!isa<ClassTemplateDecl>(Template) && 2172 !isa<TemplateTemplateParmDecl>(Template)) { 2173 assert(isa<FunctionTemplateDecl>(Template) && 2174 "Only function templates are possible here"); 2175 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template); 2176 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 2177 << Template; 2178 } 2179 2180 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 2181 Param->getTemplateParameters(), 2182 true, true, 2183 Arg->getSourceRange().getBegin()); 2184} 2185 2186/// \brief Determine whether the given template parameter lists are 2187/// equivalent. 2188/// 2189/// \param New The new template parameter list, typically written in the 2190/// source code as part of a new template declaration. 2191/// 2192/// \param Old The old template parameter list, typically found via 2193/// name lookup of the template declared with this template parameter 2194/// list. 2195/// 2196/// \param Complain If true, this routine will produce a diagnostic if 2197/// the template parameter lists are not equivalent. 2198/// 2199/// \param IsTemplateTemplateParm If true, this routine is being 2200/// called to compare the template parameter lists of a template 2201/// template parameter. 2202/// 2203/// \param TemplateArgLoc If this source location is valid, then we 2204/// are actually checking the template parameter list of a template 2205/// argument (New) against the template parameter list of its 2206/// corresponding template template parameter (Old). We produce 2207/// slightly different diagnostics in this scenario. 2208/// 2209/// \returns True if the template parameter lists are equal, false 2210/// otherwise. 2211bool 2212Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 2213 TemplateParameterList *Old, 2214 bool Complain, 2215 bool IsTemplateTemplateParm, 2216 SourceLocation TemplateArgLoc) { 2217 if (Old->size() != New->size()) { 2218 if (Complain) { 2219 unsigned NextDiag = diag::err_template_param_list_different_arity; 2220 if (TemplateArgLoc.isValid()) { 2221 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 2222 NextDiag = diag::note_template_param_list_different_arity; 2223 } 2224 Diag(New->getTemplateLoc(), NextDiag) 2225 << (New->size() > Old->size()) 2226 << IsTemplateTemplateParm 2227 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 2228 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 2229 << IsTemplateTemplateParm 2230 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 2231 } 2232 2233 return false; 2234 } 2235 2236 for (TemplateParameterList::iterator OldParm = Old->begin(), 2237 OldParmEnd = Old->end(), NewParm = New->begin(); 2238 OldParm != OldParmEnd; ++OldParm, ++NewParm) { 2239 if ((*OldParm)->getKind() != (*NewParm)->getKind()) { 2240 if (Complain) { 2241 unsigned NextDiag = diag::err_template_param_different_kind; 2242 if (TemplateArgLoc.isValid()) { 2243 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 2244 NextDiag = diag::note_template_param_different_kind; 2245 } 2246 Diag((*NewParm)->getLocation(), NextDiag) 2247 << IsTemplateTemplateParm; 2248 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration) 2249 << IsTemplateTemplateParm; 2250 } 2251 return false; 2252 } 2253 2254 if (isa<TemplateTypeParmDecl>(*OldParm)) { 2255 // Okay; all template type parameters are equivalent (since we 2256 // know we're at the same index). 2257#if 0 2258 // FIXME: Enable this code in debug mode *after* we properly go through 2259 // and "instantiate" the template parameter lists of template template 2260 // parameters. It's only after this instantiation that (1) any dependent 2261 // types within the template parameter list of the template template 2262 // parameter can be checked, and (2) the template type parameter depths 2263 // will match up. 2264 QualType OldParmType 2265 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm)); 2266 QualType NewParmType 2267 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm)); 2268 assert(Context.getCanonicalType(OldParmType) == 2269 Context.getCanonicalType(NewParmType) && 2270 "type parameter mismatch?"); 2271#endif 2272 } else if (NonTypeTemplateParmDecl *OldNTTP 2273 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) { 2274 // The types of non-type template parameters must agree. 2275 NonTypeTemplateParmDecl *NewNTTP 2276 = cast<NonTypeTemplateParmDecl>(*NewParm); 2277 if (Context.getCanonicalType(OldNTTP->getType()) != 2278 Context.getCanonicalType(NewNTTP->getType())) { 2279 if (Complain) { 2280 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 2281 if (TemplateArgLoc.isValid()) { 2282 Diag(TemplateArgLoc, 2283 diag::err_template_arg_template_params_mismatch); 2284 NextDiag = diag::note_template_nontype_parm_different_type; 2285 } 2286 Diag(NewNTTP->getLocation(), NextDiag) 2287 << NewNTTP->getType() 2288 << IsTemplateTemplateParm; 2289 Diag(OldNTTP->getLocation(), 2290 diag::note_template_nontype_parm_prev_declaration) 2291 << OldNTTP->getType(); 2292 } 2293 return false; 2294 } 2295 } else { 2296 // The template parameter lists of template template 2297 // parameters must agree. 2298 // FIXME: Could we perform a faster "type" comparison here? 2299 assert(isa<TemplateTemplateParmDecl>(*OldParm) && 2300 "Only template template parameters handled here"); 2301 TemplateTemplateParmDecl *OldTTP 2302 = cast<TemplateTemplateParmDecl>(*OldParm); 2303 TemplateTemplateParmDecl *NewTTP 2304 = cast<TemplateTemplateParmDecl>(*NewParm); 2305 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 2306 OldTTP->getTemplateParameters(), 2307 Complain, 2308 /*IsTemplateTemplateParm=*/true, 2309 TemplateArgLoc)) 2310 return false; 2311 } 2312 } 2313 2314 return true; 2315} 2316 2317/// \brief Check whether a template can be declared within this scope. 2318/// 2319/// If the template declaration is valid in this scope, returns 2320/// false. Otherwise, issues a diagnostic and returns true. 2321bool 2322Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 2323 // Find the nearest enclosing declaration scope. 2324 while ((S->getFlags() & Scope::DeclScope) == 0 || 2325 (S->getFlags() & Scope::TemplateParamScope) != 0) 2326 S = S->getParent(); 2327 2328 // C++ [temp]p2: 2329 // A template-declaration can appear only as a namespace scope or 2330 // class scope declaration. 2331 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 2332 if (Ctx && isa<LinkageSpecDecl>(Ctx) && 2333 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx) 2334 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 2335 << TemplateParams->getSourceRange(); 2336 2337 while (Ctx && isa<LinkageSpecDecl>(Ctx)) 2338 Ctx = Ctx->getParent(); 2339 2340 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord())) 2341 return false; 2342 2343 return Diag(TemplateParams->getTemplateLoc(), 2344 diag::err_template_outside_namespace_or_class_scope) 2345 << TemplateParams->getSourceRange(); 2346} 2347 2348/// \brief Determine what kind of template specialization the given declaration 2349/// is. 2350static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) { 2351 if (!D) 2352 return TSK_Undeclared; 2353 2354 if (ClassTemplateSpecializationDecl *CTS 2355 = dyn_cast<ClassTemplateSpecializationDecl>(D)) 2356 return CTS->getSpecializationKind(); 2357 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 2358 return Function->getTemplateSpecializationKind(); 2359 2360 // FIXME: static data members! 2361 // FIXME: member classes of class templates! 2362 return TSK_Undeclared; 2363} 2364 2365/// \brief Check whether a specialization or explicit instantiation is 2366/// well-formed in the current context. 2367/// 2368/// This routine determines whether a template specialization or 2369/// explicit instantiation can be declared in the current context 2370/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2). 2371/// 2372/// \param S the semantic analysis object for which this check is being 2373/// performed. 2374/// 2375/// \param Specialized the entity being specialized or instantiated, which 2376/// may be a kind of template (class template, function template, etc.) or 2377/// a member of a class template (member function, static data member, 2378/// member class). 2379/// 2380/// \param PrevDecl the previous declaration of this entity, if any. 2381/// 2382/// \param Loc the location of the explicit specialization or instantiation of 2383/// this entity. 2384/// 2385/// \param IsPartialSpecialization whether this is a partial specialization of 2386/// a class template. 2387/// 2388/// \param TSK the kind of specialization or implicit instantiation being 2389/// performed. 2390/// 2391/// \returns true if there was an error that we cannot recover from, false 2392/// otherwise. 2393static bool CheckTemplateSpecializationScope(Sema &S, 2394 NamedDecl *Specialized, 2395 NamedDecl *PrevDecl, 2396 SourceLocation Loc, 2397 bool IsPartialSpecialization, 2398 TemplateSpecializationKind TSK) { 2399 // Keep these "kind" numbers in sync with the %select statements in the 2400 // various diagnostics emitted by this routine. 2401 int EntityKind = 0; 2402 if (isa<ClassTemplateDecl>(Specialized)) 2403 EntityKind = IsPartialSpecialization? 1 : 0; 2404 else if (isa<FunctionTemplateDecl>(Specialized)) 2405 EntityKind = 2; 2406 else if (isa<CXXMethodDecl>(Specialized)) 2407 EntityKind = 3; 2408 else if (isa<VarDecl>(Specialized)) 2409 EntityKind = 4; 2410 else if (isa<RecordDecl>(Specialized)) 2411 EntityKind = 5; 2412 else { 2413 S.Diag(Loc, diag::err_template_spec_unknown_kind) << TSK; 2414 S.Diag(Specialized->getLocation(), diag::note_specialized_entity) << TSK; 2415 return true; 2416 } 2417 2418 // C++ [temp.expl.spec]p2: 2419 // An explicit specialization shall be declared in the namespace 2420 // of which the template is a member, or, for member templates, in 2421 // the namespace of which the enclosing class or enclosing class 2422 // template is a member. An explicit specialization of a member 2423 // function, member class or static data member of a class 2424 // template shall be declared in the namespace of which the class 2425 // template is a member. Such a declaration may also be a 2426 // definition. If the declaration is not a definition, the 2427 // specialization may be defined later in the name- space in which 2428 // the explicit specialization was declared, or in a namespace 2429 // that encloses the one in which the explicit specialization was 2430 // declared. 2431 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) { 2432 S.Diag(Loc, diag::err_template_spec_decl_function_scope) 2433 << TSK << Specialized; 2434 return true; 2435 } 2436 2437 bool ComplainedAboutScope = false; 2438 DeclContext *SpecializedContext 2439 = Specialized->getDeclContext()->getEnclosingNamespaceContext(); 2440 if (TSK == TSK_ExplicitSpecialization) { 2441 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext(); 2442 if ((!PrevDecl || 2443 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared || 2444 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){ 2445 // There is no prior declaration of this entity, so this 2446 // specialization must be in the same context as the template 2447 // itself. 2448 if (!DC->Equals(SpecializedContext)) { 2449 if (isa<TranslationUnitDecl>(SpecializedContext)) 2450 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global) 2451 << EntityKind << Specialized; 2452 else if (isa<NamespaceDecl>(SpecializedContext)) 2453 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope) 2454 << EntityKind << Specialized 2455 << cast<NamedDecl>(SpecializedContext); 2456 2457 S.Diag(Specialized->getLocation(), diag::note_template_decl_here); 2458 ComplainedAboutScope = true; 2459 } 2460 } 2461 } 2462 2463 // Make sure that this redeclaration (or definition) occurs in an enclosing 2464 // namespace. We perform this check for explicit specializations and, in 2465 // C++0x, for explicit instantiations as well (per DR275). 2466 // FIXME: -Wc++0x should make these warnings. 2467 // Note that HandleDeclarator() performs this check for explicit 2468 // specializations of function templates, static data members, and member 2469 // functions, so we skip the check here for those kinds of entities. 2470 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though. 2471 // Should we refactor the check, so that it occurs later? 2472 if (!ComplainedAboutScope && !S.CurContext->Encloses(SpecializedContext) && 2473 ((TSK == TSK_ExplicitSpecialization && 2474 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) || 2475 isa<FunctionDecl>(Specialized))) || 2476 S.getLangOptions().CPlusPlus0x)) { 2477 if (isa<TranslationUnitDecl>(SpecializedContext)) 2478 S.Diag(Loc, diag::err_template_spec_redecl_global_scope) 2479 << EntityKind << Specialized; 2480 else if (isa<NamespaceDecl>(SpecializedContext)) 2481 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope) 2482 << EntityKind << Specialized 2483 << cast<NamedDecl>(SpecializedContext); 2484 2485 S.Diag(Specialized->getLocation(), diag::note_template_decl_here); 2486 } 2487 2488 // FIXME: check for specialization-after-instantiation errors and such. 2489 2490 return false; 2491} 2492 2493/// \brief Check the non-type template arguments of a class template 2494/// partial specialization according to C++ [temp.class.spec]p9. 2495/// 2496/// \param TemplateParams the template parameters of the primary class 2497/// template. 2498/// 2499/// \param TemplateArg the template arguments of the class template 2500/// partial specialization. 2501/// 2502/// \param MirrorsPrimaryTemplate will be set true if the class 2503/// template partial specialization arguments are identical to the 2504/// implicit template arguments of the primary template. This is not 2505/// necessarily an error (C++0x), and it is left to the caller to diagnose 2506/// this condition when it is an error. 2507/// 2508/// \returns true if there was an error, false otherwise. 2509bool Sema::CheckClassTemplatePartialSpecializationArgs( 2510 TemplateParameterList *TemplateParams, 2511 const TemplateArgumentListBuilder &TemplateArgs, 2512 bool &MirrorsPrimaryTemplate) { 2513 // FIXME: the interface to this function will have to change to 2514 // accommodate variadic templates. 2515 MirrorsPrimaryTemplate = true; 2516 2517 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments(); 2518 2519 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 2520 // Determine whether the template argument list of the partial 2521 // specialization is identical to the implicit argument list of 2522 // the primary template. The caller may need to diagnostic this as 2523 // an error per C++ [temp.class.spec]p9b3. 2524 if (MirrorsPrimaryTemplate) { 2525 if (TemplateTypeParmDecl *TTP 2526 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) { 2527 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) != 2528 Context.getCanonicalType(ArgList[I].getAsType())) 2529 MirrorsPrimaryTemplate = false; 2530 } else if (TemplateTemplateParmDecl *TTP 2531 = dyn_cast<TemplateTemplateParmDecl>( 2532 TemplateParams->getParam(I))) { 2533 // FIXME: We should settle on either Declaration storage or 2534 // Expression storage for template template parameters. 2535 TemplateTemplateParmDecl *ArgDecl 2536 = dyn_cast_or_null<TemplateTemplateParmDecl>( 2537 ArgList[I].getAsDecl()); 2538 if (!ArgDecl) 2539 if (DeclRefExpr *DRE 2540 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr())) 2541 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl()); 2542 2543 if (!ArgDecl || 2544 ArgDecl->getIndex() != TTP->getIndex() || 2545 ArgDecl->getDepth() != TTP->getDepth()) 2546 MirrorsPrimaryTemplate = false; 2547 } 2548 } 2549 2550 NonTypeTemplateParmDecl *Param 2551 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 2552 if (!Param) { 2553 continue; 2554 } 2555 2556 Expr *ArgExpr = ArgList[I].getAsExpr(); 2557 if (!ArgExpr) { 2558 MirrorsPrimaryTemplate = false; 2559 continue; 2560 } 2561 2562 // C++ [temp.class.spec]p8: 2563 // A non-type argument is non-specialized if it is the name of a 2564 // non-type parameter. All other non-type arguments are 2565 // specialized. 2566 // 2567 // Below, we check the two conditions that only apply to 2568 // specialized non-type arguments, so skip any non-specialized 2569 // arguments. 2570 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 2571 if (NonTypeTemplateParmDecl *NTTP 2572 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) { 2573 if (MirrorsPrimaryTemplate && 2574 (Param->getIndex() != NTTP->getIndex() || 2575 Param->getDepth() != NTTP->getDepth())) 2576 MirrorsPrimaryTemplate = false; 2577 2578 continue; 2579 } 2580 2581 // C++ [temp.class.spec]p9: 2582 // Within the argument list of a class template partial 2583 // specialization, the following restrictions apply: 2584 // -- A partially specialized non-type argument expression 2585 // shall not involve a template parameter of the partial 2586 // specialization except when the argument expression is a 2587 // simple identifier. 2588 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) { 2589 Diag(ArgExpr->getLocStart(), 2590 diag::err_dependent_non_type_arg_in_partial_spec) 2591 << ArgExpr->getSourceRange(); 2592 return true; 2593 } 2594 2595 // -- The type of a template parameter corresponding to a 2596 // specialized non-type argument shall not be dependent on a 2597 // parameter of the specialization. 2598 if (Param->getType()->isDependentType()) { 2599 Diag(ArgExpr->getLocStart(), 2600 diag::err_dependent_typed_non_type_arg_in_partial_spec) 2601 << Param->getType() 2602 << ArgExpr->getSourceRange(); 2603 Diag(Param->getLocation(), diag::note_template_param_here); 2604 return true; 2605 } 2606 2607 MirrorsPrimaryTemplate = false; 2608 } 2609 2610 return false; 2611} 2612 2613Sema::DeclResult 2614Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, 2615 TagUseKind TUK, 2616 SourceLocation KWLoc, 2617 const CXXScopeSpec &SS, 2618 TemplateTy TemplateD, 2619 SourceLocation TemplateNameLoc, 2620 SourceLocation LAngleLoc, 2621 ASTTemplateArgsPtr TemplateArgsIn, 2622 SourceLocation *TemplateArgLocs, 2623 SourceLocation RAngleLoc, 2624 AttributeList *Attr, 2625 MultiTemplateParamsArg TemplateParameterLists) { 2626 assert(TUK != TUK_Reference && "References are not specializations"); 2627 2628 // Find the class template we're specializing 2629 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 2630 ClassTemplateDecl *ClassTemplate 2631 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); 2632 2633 bool isPartialSpecialization = false; 2634 2635 // Check the validity of the template headers that introduce this 2636 // template. 2637 // FIXME: We probably shouldn't complain about these headers for 2638 // friend declarations. 2639 TemplateParameterList *TemplateParams 2640 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS, 2641 (TemplateParameterList**)TemplateParameterLists.get(), 2642 TemplateParameterLists.size()); 2643 if (TemplateParams && TemplateParams->size() > 0) { 2644 isPartialSpecialization = true; 2645 2646 // C++ [temp.class.spec]p10: 2647 // The template parameter list of a specialization shall not 2648 // contain default template argument values. 2649 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 2650 Decl *Param = TemplateParams->getParam(I); 2651 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 2652 if (TTP->hasDefaultArgument()) { 2653 Diag(TTP->getDefaultArgumentLoc(), 2654 diag::err_default_arg_in_partial_spec); 2655 TTP->setDefaultArgument(QualType(), SourceLocation(), false); 2656 } 2657 } else if (NonTypeTemplateParmDecl *NTTP 2658 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2659 if (Expr *DefArg = NTTP->getDefaultArgument()) { 2660 Diag(NTTP->getDefaultArgumentLoc(), 2661 diag::err_default_arg_in_partial_spec) 2662 << DefArg->getSourceRange(); 2663 NTTP->setDefaultArgument(0); 2664 DefArg->Destroy(Context); 2665 } 2666 } else { 2667 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 2668 if (Expr *DefArg = TTP->getDefaultArgument()) { 2669 Diag(TTP->getDefaultArgumentLoc(), 2670 diag::err_default_arg_in_partial_spec) 2671 << DefArg->getSourceRange(); 2672 TTP->setDefaultArgument(0); 2673 DefArg->Destroy(Context); 2674 } 2675 } 2676 } 2677 } else if (!TemplateParams && TUK != TUK_Friend) 2678 Diag(KWLoc, diag::err_template_spec_needs_header) 2679 << CodeModificationHint::CreateInsertion(KWLoc, "template<> "); 2680 2681 // Check that the specialization uses the same tag kind as the 2682 // original template. 2683 TagDecl::TagKind Kind; 2684 switch (TagSpec) { 2685 default: assert(0 && "Unknown tag type!"); 2686 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 2687 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 2688 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 2689 } 2690 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 2691 Kind, KWLoc, 2692 *ClassTemplate->getIdentifier())) { 2693 Diag(KWLoc, diag::err_use_with_wrong_tag) 2694 << ClassTemplate 2695 << CodeModificationHint::CreateReplacement(KWLoc, 2696 ClassTemplate->getTemplatedDecl()->getKindName()); 2697 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 2698 diag::note_previous_use); 2699 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 2700 } 2701 2702 // Translate the parser's template argument list in our AST format. 2703 llvm::SmallVector<TemplateArgument, 16> TemplateArgs; 2704 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs); 2705 2706 // Check that the template argument list is well-formed for this 2707 // template. 2708 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 2709 TemplateArgs.size()); 2710 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc, 2711 TemplateArgs.data(), TemplateArgs.size(), 2712 RAngleLoc, false, Converted)) 2713 return true; 2714 2715 assert((Converted.structuredSize() == 2716 ClassTemplate->getTemplateParameters()->size()) && 2717 "Converted template argument list is too short!"); 2718 2719 // Find the class template (partial) specialization declaration that 2720 // corresponds to these arguments. 2721 llvm::FoldingSetNodeID ID; 2722 if (isPartialSpecialization) { 2723 bool MirrorsPrimaryTemplate; 2724 if (CheckClassTemplatePartialSpecializationArgs( 2725 ClassTemplate->getTemplateParameters(), 2726 Converted, MirrorsPrimaryTemplate)) 2727 return true; 2728 2729 if (MirrorsPrimaryTemplate) { 2730 // C++ [temp.class.spec]p9b3: 2731 // 2732 // -- The argument list of the specialization shall not be identical 2733 // to the implicit argument list of the primary template. 2734 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 2735 << (TUK == TUK_Definition) 2736 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc, 2737 RAngleLoc)); 2738 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, 2739 ClassTemplate->getIdentifier(), 2740 TemplateNameLoc, 2741 Attr, 2742 TemplateParams, 2743 AS_none); 2744 } 2745 2746 // FIXME: Diagnose friend partial specializations 2747 2748 // FIXME: Template parameter list matters, too 2749 ClassTemplatePartialSpecializationDecl::Profile(ID, 2750 Converted.getFlatArguments(), 2751 Converted.flatSize(), 2752 Context); 2753 } else 2754 ClassTemplateSpecializationDecl::Profile(ID, 2755 Converted.getFlatArguments(), 2756 Converted.flatSize(), 2757 Context); 2758 void *InsertPos = 0; 2759 ClassTemplateSpecializationDecl *PrevDecl = 0; 2760 2761 if (isPartialSpecialization) 2762 PrevDecl 2763 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 2764 InsertPos); 2765 else 2766 PrevDecl 2767 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 2768 2769 ClassTemplateSpecializationDecl *Specialization = 0; 2770 2771 // Check whether we can declare a class template specialization in 2772 // the current scope. 2773 if (TUK != TUK_Friend && 2774 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 2775 TemplateNameLoc, isPartialSpecialization, 2776 TSK_ExplicitSpecialization)) 2777 return true; 2778 2779 // The canonical type 2780 QualType CanonType; 2781 if (PrevDecl && 2782 (PrevDecl->getSpecializationKind() == TSK_Undeclared || 2783 TUK == TUK_Friend)) { 2784 // Since the only prior class template specialization with these 2785 // arguments was referenced but not declared, or we're only 2786 // referencing this specialization as a friend, reuse that 2787 // declaration node as our own, updating its source location to 2788 // reflect our new declaration. 2789 Specialization = PrevDecl; 2790 Specialization->setLocation(TemplateNameLoc); 2791 PrevDecl = 0; 2792 CanonType = Context.getTypeDeclType(Specialization); 2793 } else if (isPartialSpecialization) { 2794 // Build the canonical type that describes the converted template 2795 // arguments of the class template partial specialization. 2796 CanonType = Context.getTemplateSpecializationType( 2797 TemplateName(ClassTemplate), 2798 Converted.getFlatArguments(), 2799 Converted.flatSize()); 2800 2801 // Create a new class template partial specialization declaration node. 2802 TemplateParameterList *TemplateParams 2803 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get()); 2804 ClassTemplatePartialSpecializationDecl *PrevPartial 2805 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 2806 ClassTemplatePartialSpecializationDecl *Partial 2807 = ClassTemplatePartialSpecializationDecl::Create(Context, 2808 ClassTemplate->getDeclContext(), 2809 TemplateNameLoc, 2810 TemplateParams, 2811 ClassTemplate, 2812 Converted, 2813 PrevPartial); 2814 2815 if (PrevPartial) { 2816 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial); 2817 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial); 2818 } else { 2819 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos); 2820 } 2821 Specialization = Partial; 2822 2823 // Check that all of the template parameters of the class template 2824 // partial specialization are deducible from the template 2825 // arguments. If not, this class template partial specialization 2826 // will never be used. 2827 llvm::SmallVector<bool, 8> DeducibleParams; 2828 DeducibleParams.resize(TemplateParams->size()); 2829 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 2830 DeducibleParams); 2831 unsigned NumNonDeducible = 0; 2832 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) 2833 if (!DeducibleParams[I]) 2834 ++NumNonDeducible; 2835 2836 if (NumNonDeducible) { 2837 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible) 2838 << (NumNonDeducible > 1) 2839 << SourceRange(TemplateNameLoc, RAngleLoc); 2840 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 2841 if (!DeducibleParams[I]) { 2842 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I)); 2843 if (Param->getDeclName()) 2844 Diag(Param->getLocation(), 2845 diag::note_partial_spec_unused_parameter) 2846 << Param->getDeclName(); 2847 else 2848 Diag(Param->getLocation(), 2849 diag::note_partial_spec_unused_parameter) 2850 << std::string("<anonymous>"); 2851 } 2852 } 2853 } 2854 } else { 2855 // Create a new class template specialization declaration node for 2856 // this explicit specialization or friend declaration. 2857 Specialization 2858 = ClassTemplateSpecializationDecl::Create(Context, 2859 ClassTemplate->getDeclContext(), 2860 TemplateNameLoc, 2861 ClassTemplate, 2862 Converted, 2863 PrevDecl); 2864 2865 if (PrevDecl) { 2866 ClassTemplate->getSpecializations().RemoveNode(PrevDecl); 2867 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization); 2868 } else { 2869 ClassTemplate->getSpecializations().InsertNode(Specialization, 2870 InsertPos); 2871 } 2872 2873 CanonType = Context.getTypeDeclType(Specialization); 2874 } 2875 2876 // If this is not a friend, note that this is an explicit specialization. 2877 if (TUK != TUK_Friend) 2878 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 2879 2880 // Check that this isn't a redefinition of this specialization. 2881 if (TUK == TUK_Definition) { 2882 if (RecordDecl *Def = Specialization->getDefinition(Context)) { 2883 // FIXME: Should also handle explicit specialization after implicit 2884 // instantiation with a special diagnostic. 2885 SourceRange Range(TemplateNameLoc, RAngleLoc); 2886 Diag(TemplateNameLoc, diag::err_redefinition) 2887 << Context.getTypeDeclType(Specialization) << Range; 2888 Diag(Def->getLocation(), diag::note_previous_definition); 2889 Specialization->setInvalidDecl(); 2890 return true; 2891 } 2892 } 2893 2894 // Build the fully-sugared type for this class template 2895 // specialization as the user wrote in the specialization 2896 // itself. This means that we'll pretty-print the type retrieved 2897 // from the specialization's declaration the way that the user 2898 // actually wrote the specialization, rather than formatting the 2899 // name based on the "canonical" representation used to store the 2900 // template arguments in the specialization. 2901 QualType WrittenTy 2902 = Context.getTemplateSpecializationType(Name, 2903 TemplateArgs.data(), 2904 TemplateArgs.size(), 2905 CanonType); 2906 if (TUK != TUK_Friend) 2907 Specialization->setTypeAsWritten(WrittenTy); 2908 TemplateArgsIn.release(); 2909 2910 // C++ [temp.expl.spec]p9: 2911 // A template explicit specialization is in the scope of the 2912 // namespace in which the template was defined. 2913 // 2914 // We actually implement this paragraph where we set the semantic 2915 // context (in the creation of the ClassTemplateSpecializationDecl), 2916 // but we also maintain the lexical context where the actual 2917 // definition occurs. 2918 Specialization->setLexicalDeclContext(CurContext); 2919 2920 // We may be starting the definition of this specialization. 2921 if (TUK == TUK_Definition) 2922 Specialization->startDefinition(); 2923 2924 if (TUK == TUK_Friend) { 2925 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 2926 TemplateNameLoc, 2927 WrittenTy.getTypePtr(), 2928 /*FIXME:*/KWLoc); 2929 Friend->setAccess(AS_public); 2930 CurContext->addDecl(Friend); 2931 } else { 2932 // Add the specialization into its lexical context, so that it can 2933 // be seen when iterating through the list of declarations in that 2934 // context. However, specializations are not found by name lookup. 2935 CurContext->addDecl(Specialization); 2936 } 2937 return DeclPtrTy::make(Specialization); 2938} 2939 2940Sema::DeclPtrTy 2941Sema::ActOnTemplateDeclarator(Scope *S, 2942 MultiTemplateParamsArg TemplateParameterLists, 2943 Declarator &D) { 2944 return HandleDeclarator(S, D, move(TemplateParameterLists), false); 2945} 2946 2947Sema::DeclPtrTy 2948Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 2949 MultiTemplateParamsArg TemplateParameterLists, 2950 Declarator &D) { 2951 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 2952 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 2953 "Not a function declarator!"); 2954 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2955 2956 if (FTI.hasPrototype) { 2957 // FIXME: Diagnose arguments without names in C. 2958 } 2959 2960 Scope *ParentScope = FnBodyScope->getParent(); 2961 2962 DeclPtrTy DP = HandleDeclarator(ParentScope, D, 2963 move(TemplateParameterLists), 2964 /*IsFunctionDefinition=*/true); 2965 if (FunctionTemplateDecl *FunctionTemplate 2966 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>())) 2967 return ActOnStartOfFunctionDef(FnBodyScope, 2968 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl())); 2969 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>())) 2970 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function)); 2971 return DeclPtrTy(); 2972} 2973 2974/// \brief Perform semantic analysis for the given function template 2975/// specialization. 2976/// 2977/// This routine performs all of the semantic analysis required for an 2978/// explicit function template specialization. On successful completion, 2979/// the function declaration \p FD will become a function template 2980/// specialization. 2981/// 2982/// \param FD the function declaration, which will be updated to become a 2983/// function template specialization. 2984/// 2985/// \param HasExplicitTemplateArgs whether any template arguments were 2986/// explicitly provided. 2987/// 2988/// \param LAngleLoc the location of the left angle bracket ('<'), if 2989/// template arguments were explicitly provided. 2990/// 2991/// \param ExplicitTemplateArgs the explicitly-provided template arguments, 2992/// if any. 2993/// 2994/// \param NumExplicitTemplateArgs the number of explicitly-provided template 2995/// arguments. This number may be zero even when HasExplicitTemplateArgs is 2996/// true as in, e.g., \c void sort<>(char*, char*); 2997/// 2998/// \param RAngleLoc the location of the right angle bracket ('>'), if 2999/// template arguments were explicitly provided. 3000/// 3001/// \param PrevDecl the set of declarations that 3002bool 3003Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD, 3004 bool HasExplicitTemplateArgs, 3005 SourceLocation LAngleLoc, 3006 const TemplateArgument *ExplicitTemplateArgs, 3007 unsigned NumExplicitTemplateArgs, 3008 SourceLocation RAngleLoc, 3009 NamedDecl *&PrevDecl) { 3010 // The set of function template specializations that could match this 3011 // explicit function template specialization. 3012 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet; 3013 CandidateSet Candidates; 3014 3015 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext(); 3016 for (OverloadIterator Ovl(PrevDecl), OvlEnd; Ovl != OvlEnd; ++Ovl) { 3017 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*Ovl)) { 3018 // Only consider templates found within the same semantic lookup scope as 3019 // FD. 3020 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext())) 3021 continue; 3022 3023 // C++ [temp.expl.spec]p11: 3024 // A trailing template-argument can be left unspecified in the 3025 // template-id naming an explicit function template specialization 3026 // provided it can be deduced from the function argument type. 3027 // Perform template argument deduction to determine whether we may be 3028 // specializing this template. 3029 // FIXME: It is somewhat wasteful to build 3030 TemplateDeductionInfo Info(Context); 3031 FunctionDecl *Specialization = 0; 3032 if (TemplateDeductionResult TDK 3033 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs, 3034 ExplicitTemplateArgs, 3035 NumExplicitTemplateArgs, 3036 FD->getType(), 3037 Specialization, 3038 Info)) { 3039 // FIXME: Template argument deduction failed; record why it failed, so 3040 // that we can provide nifty diagnostics. 3041 (void)TDK; 3042 continue; 3043 } 3044 3045 // Record this candidate. 3046 Candidates.push_back(Specialization); 3047 } 3048 } 3049 3050 // Find the most specialized function template. 3051 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(), 3052 Candidates.size(), 3053 TPOC_Other, 3054 FD->getLocation(), 3055 PartialDiagnostic(diag::err_function_template_spec_no_match) 3056 << FD->getDeclName(), 3057 PartialDiagnostic(diag::err_function_template_spec_ambiguous) 3058 << FD->getDeclName() << HasExplicitTemplateArgs, 3059 PartialDiagnostic(diag::note_function_template_spec_matched)); 3060 if (!Specialization) 3061 return true; 3062 3063 // FIXME: Check if the prior specialization has a point of instantiation. 3064 // If so, we have run afoul of C++ [temp.expl.spec]p6. 3065 3066 // Check the scope of this explicit specialization. 3067 if (CheckTemplateSpecializationScope(*this, 3068 Specialization->getPrimaryTemplate(), 3069 Specialization, FD->getLocation(), 3070 false, TSK_ExplicitSpecialization)) 3071 return true; 3072 3073 // Mark the prior declaration as an explicit specialization, so that later 3074 // clients know that this is an explicit specialization. 3075 // FIXME: Check for prior explicit instantiations? 3076 Specialization->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 3077 3078 // Turn the given function declaration into a function template 3079 // specialization, with the template arguments from the previous 3080 // specialization. 3081 FD->setFunctionTemplateSpecialization(Context, 3082 Specialization->getPrimaryTemplate(), 3083 new (Context) TemplateArgumentList( 3084 *Specialization->getTemplateSpecializationArgs()), 3085 /*InsertPos=*/0, 3086 TSK_ExplicitSpecialization); 3087 3088 // The "previous declaration" for this function template specialization is 3089 // the prior function template specialization. 3090 PrevDecl = Specialization; 3091 return false; 3092} 3093 3094// Explicit instantiation of a class template specialization 3095// FIXME: Implement extern template semantics 3096Sema::DeclResult 3097Sema::ActOnExplicitInstantiation(Scope *S, 3098 SourceLocation ExternLoc, 3099 SourceLocation TemplateLoc, 3100 unsigned TagSpec, 3101 SourceLocation KWLoc, 3102 const CXXScopeSpec &SS, 3103 TemplateTy TemplateD, 3104 SourceLocation TemplateNameLoc, 3105 SourceLocation LAngleLoc, 3106 ASTTemplateArgsPtr TemplateArgsIn, 3107 SourceLocation *TemplateArgLocs, 3108 SourceLocation RAngleLoc, 3109 AttributeList *Attr) { 3110 // Find the class template we're specializing 3111 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 3112 ClassTemplateDecl *ClassTemplate 3113 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); 3114 3115 // Check that the specialization uses the same tag kind as the 3116 // original template. 3117 TagDecl::TagKind Kind; 3118 switch (TagSpec) { 3119 default: assert(0 && "Unknown tag type!"); 3120 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 3121 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 3122 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 3123 } 3124 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 3125 Kind, KWLoc, 3126 *ClassTemplate->getIdentifier())) { 3127 Diag(KWLoc, diag::err_use_with_wrong_tag) 3128 << ClassTemplate 3129 << CodeModificationHint::CreateReplacement(KWLoc, 3130 ClassTemplate->getTemplatedDecl()->getKindName()); 3131 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 3132 diag::note_previous_use); 3133 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 3134 } 3135 3136 TemplateSpecializationKind TSK 3137 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 3138 : TSK_ExplicitInstantiationDeclaration; 3139 3140 // Translate the parser's template argument list in our AST format. 3141 llvm::SmallVector<TemplateArgument, 16> TemplateArgs; 3142 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs); 3143 3144 // Check that the template argument list is well-formed for this 3145 // template. 3146 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 3147 TemplateArgs.size()); 3148 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc, 3149 TemplateArgs.data(), TemplateArgs.size(), 3150 RAngleLoc, false, Converted)) 3151 return true; 3152 3153 assert((Converted.structuredSize() == 3154 ClassTemplate->getTemplateParameters()->size()) && 3155 "Converted template argument list is too short!"); 3156 3157 // Find the class template specialization declaration that 3158 // corresponds to these arguments. 3159 llvm::FoldingSetNodeID ID; 3160 ClassTemplateSpecializationDecl::Profile(ID, 3161 Converted.getFlatArguments(), 3162 Converted.flatSize(), 3163 Context); 3164 void *InsertPos = 0; 3165 ClassTemplateSpecializationDecl *PrevDecl 3166 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 3167 3168 // C++0x [temp.explicit]p2: 3169 // [...] An explicit instantiation shall appear in an enclosing 3170 // namespace of its template. [...] 3171 // 3172 // This is C++ DR 275. 3173 if (CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 3174 TemplateNameLoc, false, 3175 TSK)) 3176 return true; 3177 3178 ClassTemplateSpecializationDecl *Specialization = 0; 3179 3180 bool SpecializationRequiresInstantiation = true; 3181 if (PrevDecl) { 3182 if (PrevDecl->getSpecializationKind() 3183 == TSK_ExplicitInstantiationDefinition) { 3184 // This particular specialization has already been declared or 3185 // instantiated. We cannot explicitly instantiate it. 3186 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate) 3187 << Context.getTypeDeclType(PrevDecl); 3188 Diag(PrevDecl->getLocation(), 3189 diag::note_previous_explicit_instantiation); 3190 return DeclPtrTy::make(PrevDecl); 3191 } 3192 3193 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) { 3194 // C++ DR 259, C++0x [temp.explicit]p4: 3195 // For a given set of template parameters, if an explicit 3196 // instantiation of a template appears after a declaration of 3197 // an explicit specialization for that template, the explicit 3198 // instantiation has no effect. 3199 if (!getLangOptions().CPlusPlus0x) { 3200 Diag(TemplateNameLoc, 3201 diag::ext_explicit_instantiation_after_specialization) 3202 << Context.getTypeDeclType(PrevDecl); 3203 Diag(PrevDecl->getLocation(), 3204 diag::note_previous_template_specialization); 3205 } 3206 3207 // Create a new class template specialization declaration node 3208 // for this explicit specialization. This node is only used to 3209 // record the existence of this explicit instantiation for 3210 // accurate reproduction of the source code; we don't actually 3211 // use it for anything, since it is semantically irrelevant. 3212 Specialization 3213 = ClassTemplateSpecializationDecl::Create(Context, 3214 ClassTemplate->getDeclContext(), 3215 TemplateNameLoc, 3216 ClassTemplate, 3217 Converted, 0); 3218 Specialization->setLexicalDeclContext(CurContext); 3219 CurContext->addDecl(Specialization); 3220 return DeclPtrTy::make(PrevDecl); 3221 } 3222 3223 // If we have already (implicitly) instantiated this 3224 // specialization, there is less work to do. 3225 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation) 3226 SpecializationRequiresInstantiation = false; 3227 3228 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation || 3229 PrevDecl->getSpecializationKind() == TSK_Undeclared) { 3230 // Since the only prior class template specialization with these 3231 // arguments was referenced but not declared, reuse that 3232 // declaration node as our own, updating its source location to 3233 // reflect our new declaration. 3234 Specialization = PrevDecl; 3235 Specialization->setLocation(TemplateNameLoc); 3236 PrevDecl = 0; 3237 } 3238 } 3239 3240 if (!Specialization) { 3241 // Create a new class template specialization declaration node for 3242 // this explicit specialization. 3243 Specialization 3244 = ClassTemplateSpecializationDecl::Create(Context, 3245 ClassTemplate->getDeclContext(), 3246 TemplateNameLoc, 3247 ClassTemplate, 3248 Converted, PrevDecl); 3249 3250 if (PrevDecl) { 3251 // Remove the previous declaration from the folding set, since we want 3252 // to introduce a new declaration. 3253 ClassTemplate->getSpecializations().RemoveNode(PrevDecl); 3254 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 3255 } 3256 3257 // Insert the new specialization. 3258 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos); 3259 } 3260 3261 // Build the fully-sugared type for this explicit instantiation as 3262 // the user wrote in the explicit instantiation itself. This means 3263 // that we'll pretty-print the type retrieved from the 3264 // specialization's declaration the way that the user actually wrote 3265 // the explicit instantiation, rather than formatting the name based 3266 // on the "canonical" representation used to store the template 3267 // arguments in the specialization. 3268 QualType WrittenTy 3269 = Context.getTemplateSpecializationType(Name, 3270 TemplateArgs.data(), 3271 TemplateArgs.size(), 3272 Context.getTypeDeclType(Specialization)); 3273 Specialization->setTypeAsWritten(WrittenTy); 3274 TemplateArgsIn.release(); 3275 3276 // Add the explicit instantiation into its lexical context. However, 3277 // since explicit instantiations are never found by name lookup, we 3278 // just put it into the declaration context directly. 3279 Specialization->setLexicalDeclContext(CurContext); 3280 CurContext->addDecl(Specialization); 3281 3282 Specialization->setPointOfInstantiation(TemplateNameLoc); 3283 3284 // C++ [temp.explicit]p3: 3285 // A definition of a class template or class member template 3286 // shall be in scope at the point of the explicit instantiation of 3287 // the class template or class member template. 3288 // 3289 // This check comes when we actually try to perform the 3290 // instantiation. 3291 if (SpecializationRequiresInstantiation) 3292 InstantiateClassTemplateSpecialization(Specialization, TSK); 3293 else // Instantiate the members of this class template specialization. 3294 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization, 3295 TSK); 3296 3297 return DeclPtrTy::make(Specialization); 3298} 3299 3300// Explicit instantiation of a member class of a class template. 3301Sema::DeclResult 3302Sema::ActOnExplicitInstantiation(Scope *S, 3303 SourceLocation ExternLoc, 3304 SourceLocation TemplateLoc, 3305 unsigned TagSpec, 3306 SourceLocation KWLoc, 3307 const CXXScopeSpec &SS, 3308 IdentifierInfo *Name, 3309 SourceLocation NameLoc, 3310 AttributeList *Attr) { 3311 3312 bool Owned = false; 3313 bool IsDependent = false; 3314 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference, 3315 KWLoc, SS, Name, NameLoc, Attr, AS_none, 3316 MultiTemplateParamsArg(*this, 0, 0), 3317 Owned, IsDependent); 3318 assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); 3319 3320 if (!TagD) 3321 return true; 3322 3323 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 3324 if (Tag->isEnum()) { 3325 Diag(TemplateLoc, diag::err_explicit_instantiation_enum) 3326 << Context.getTypeDeclType(Tag); 3327 return true; 3328 } 3329 3330 if (Tag->isInvalidDecl()) 3331 return true; 3332 3333 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 3334 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 3335 if (!Pattern) { 3336 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 3337 << Context.getTypeDeclType(Record); 3338 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 3339 return true; 3340 } 3341 3342 // C++0x [temp.explicit]p2: 3343 // [...] An explicit instantiation shall appear in an enclosing 3344 // namespace of its template. [...] 3345 // 3346 // This is C++ DR 275. 3347 if (getLangOptions().CPlusPlus0x) { 3348 // FIXME: In C++98, we would like to turn these errors into warnings, 3349 // dependent on a -Wc++0x flag. 3350 DeclContext *PatternContext 3351 = Pattern->getDeclContext()->getEnclosingNamespaceContext(); 3352 if (!CurContext->Encloses(PatternContext)) { 3353 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope) 3354 << Record << cast<NamedDecl>(PatternContext) << SS.getRange(); 3355 Diag(Pattern->getLocation(), diag::note_previous_declaration); 3356 } 3357 } 3358 3359 TemplateSpecializationKind TSK 3360 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 3361 : TSK_ExplicitInstantiationDeclaration; 3362 3363 if (!Record->getDefinition(Context)) { 3364 // If the class has a definition, instantiate it (and all of its 3365 // members, recursively). 3366 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context)); 3367 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern, 3368 getTemplateInstantiationArgs(Record), 3369 TSK)) 3370 return true; 3371 } else // Instantiate all of the members of the class. 3372 InstantiateClassMembers(TemplateLoc, Record, 3373 getTemplateInstantiationArgs(Record), TSK); 3374 3375 // FIXME: We don't have any representation for explicit instantiations of 3376 // member classes. Such a representation is not needed for compilation, but it 3377 // should be available for clients that want to see all of the declarations in 3378 // the source code. 3379 return TagD; 3380} 3381 3382Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S, 3383 SourceLocation ExternLoc, 3384 SourceLocation TemplateLoc, 3385 Declarator &D) { 3386 // Explicit instantiations always require a name. 3387 DeclarationName Name = GetNameForDeclarator(D); 3388 if (!Name) { 3389 if (!D.isInvalidType()) 3390 Diag(D.getDeclSpec().getSourceRange().getBegin(), 3391 diag::err_explicit_instantiation_requires_name) 3392 << D.getDeclSpec().getSourceRange() 3393 << D.getSourceRange(); 3394 3395 return true; 3396 } 3397 3398 // The scope passed in may not be a decl scope. Zip up the scope tree until 3399 // we find one that is. 3400 while ((S->getFlags() & Scope::DeclScope) == 0 || 3401 (S->getFlags() & Scope::TemplateParamScope) != 0) 3402 S = S->getParent(); 3403 3404 // Determine the type of the declaration. 3405 QualType R = GetTypeForDeclarator(D, S, 0); 3406 if (R.isNull()) 3407 return true; 3408 3409 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 3410 // Cannot explicitly instantiate a typedef. 3411 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) 3412 << Name; 3413 return true; 3414 } 3415 3416 // Determine what kind of explicit instantiation we have. 3417 TemplateSpecializationKind TSK 3418 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 3419 : TSK_ExplicitInstantiationDeclaration; 3420 3421 LookupResult Previous = LookupParsedName(S, &D.getCXXScopeSpec(), 3422 Name, LookupOrdinaryName); 3423 3424 if (!R->isFunctionType()) { 3425 // C++ [temp.explicit]p1: 3426 // A [...] static data member of a class template can be explicitly 3427 // instantiated from the member definition associated with its class 3428 // template. 3429 if (Previous.isAmbiguous()) { 3430 return DiagnoseAmbiguousLookup(Previous, Name, D.getIdentifierLoc(), 3431 D.getSourceRange()); 3432 } 3433 3434 VarDecl *Prev = dyn_cast_or_null<VarDecl>(Previous.getAsDecl()); 3435 if (!Prev || !Prev->isStaticDataMember()) { 3436 // We expect to see a data data member here. 3437 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) 3438 << Name; 3439 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 3440 P != PEnd; ++P) 3441 Diag(P->getLocation(), diag::note_explicit_instantiation_here); 3442 return true; 3443 } 3444 3445 if (!Prev->getInstantiatedFromStaticDataMember()) { 3446 // FIXME: Check for explicit specialization? 3447 Diag(D.getIdentifierLoc(), 3448 diag::err_explicit_instantiation_data_member_not_instantiated) 3449 << Prev; 3450 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); 3451 // FIXME: Can we provide a note showing where this was declared? 3452 return true; 3453 } 3454 3455 // Instantiate static data member. 3456 // FIXME: Note that this is an explicit instantiation. 3457 if (TSK == TSK_ExplicitInstantiationDefinition) 3458 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false); 3459 3460 // FIXME: Create an ExplicitInstantiation node? 3461 return DeclPtrTy(); 3462 } 3463 3464 // If the declarator is a template-id, translate the parser's template 3465 // argument list into our AST format. 3466 bool HasExplicitTemplateArgs = false; 3467 llvm::SmallVector<TemplateArgument, 16> TemplateArgs; 3468 if (D.getKind() == Declarator::DK_TemplateId) { 3469 TemplateIdAnnotation *TemplateId = D.getTemplateId(); 3470 ASTTemplateArgsPtr TemplateArgsPtr(*this, 3471 TemplateId->getTemplateArgs(), 3472 TemplateId->getTemplateArgIsType(), 3473 TemplateId->NumArgs); 3474 translateTemplateArguments(TemplateArgsPtr, 3475 TemplateId->getTemplateArgLocations(), 3476 TemplateArgs); 3477 HasExplicitTemplateArgs = true; 3478 TemplateArgsPtr.release(); 3479 } 3480 3481 // C++ [temp.explicit]p1: 3482 // A [...] function [...] can be explicitly instantiated from its template. 3483 // A member function [...] of a class template can be explicitly 3484 // instantiated from the member definition associated with its class 3485 // template. 3486 llvm::SmallVector<FunctionDecl *, 8> Matches; 3487 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 3488 P != PEnd; ++P) { 3489 NamedDecl *Prev = *P; 3490 if (!HasExplicitTemplateArgs) { 3491 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { 3492 if (Context.hasSameUnqualifiedType(Method->getType(), R)) { 3493 Matches.clear(); 3494 Matches.push_back(Method); 3495 break; 3496 } 3497 } 3498 } 3499 3500 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); 3501 if (!FunTmpl) 3502 continue; 3503 3504 TemplateDeductionInfo Info(Context); 3505 FunctionDecl *Specialization = 0; 3506 if (TemplateDeductionResult TDK 3507 = DeduceTemplateArguments(FunTmpl, HasExplicitTemplateArgs, 3508 TemplateArgs.data(), TemplateArgs.size(), 3509 R, Specialization, Info)) { 3510 // FIXME: Keep track of almost-matches? 3511 (void)TDK; 3512 continue; 3513 } 3514 3515 Matches.push_back(Specialization); 3516 } 3517 3518 // Find the most specialized function template specialization. 3519 FunctionDecl *Specialization 3520 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other, 3521 D.getIdentifierLoc(), 3522 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name, 3523 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name, 3524 PartialDiagnostic(diag::note_explicit_instantiation_candidate)); 3525 3526 if (!Specialization) 3527 return true; 3528 3529 switch (Specialization->getTemplateSpecializationKind()) { 3530 case TSK_Undeclared: 3531 Diag(D.getIdentifierLoc(), 3532 diag::err_explicit_instantiation_member_function_not_instantiated) 3533 << Specialization 3534 << (Specialization->getTemplateSpecializationKind() == 3535 TSK_ExplicitSpecialization); 3536 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); 3537 return true; 3538 3539 case TSK_ExplicitSpecialization: 3540 // C++ [temp.explicit]p4: 3541 // For a given set of template parameters, if an explicit instantiation 3542 // of a template appears after a declaration of an explicit 3543 // specialization for that template, the explicit instantiation has no 3544 // effect. 3545 break; 3546 3547 case TSK_ExplicitInstantiationDefinition: 3548 // FIXME: Check that we aren't trying to perform an explicit instantiation 3549 // declaration now. 3550 // Fall through 3551 3552 case TSK_ImplicitInstantiation: 3553 case TSK_ExplicitInstantiationDeclaration: 3554 // Instantiate the function, if this is an explicit instantiation 3555 // definition. 3556 if (TSK == TSK_ExplicitInstantiationDefinition) 3557 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization, 3558 false); 3559 3560 // FIXME: setTemplateSpecializationKind doesn't (yet) work for 3561 // non-templated member functions. 3562 if (!Specialization->getPrimaryTemplate()) 3563 break; 3564 3565 Specialization->setTemplateSpecializationKind(TSK); 3566 break; 3567 } 3568 3569 // FIXME: Create some kind of ExplicitInstantiationDecl here. 3570 return DeclPtrTy(); 3571} 3572 3573Sema::TypeResult 3574Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 3575 const CXXScopeSpec &SS, IdentifierInfo *Name, 3576 SourceLocation TagLoc, SourceLocation NameLoc) { 3577 // This has to hold, because SS is expected to be defined. 3578 assert(Name && "Expected a name in a dependent tag"); 3579 3580 NestedNameSpecifier *NNS 3581 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3582 if (!NNS) 3583 return true; 3584 3585 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc)); 3586 if (T.isNull()) 3587 return true; 3588 3589 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec); 3590 QualType ElabType = Context.getElaboratedType(T, TagKind); 3591 3592 return ElabType.getAsOpaquePtr(); 3593} 3594 3595Sema::TypeResult 3596Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, 3597 const IdentifierInfo &II, SourceLocation IdLoc) { 3598 NestedNameSpecifier *NNS 3599 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3600 if (!NNS) 3601 return true; 3602 3603 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc)); 3604 if (T.isNull()) 3605 return true; 3606 return T.getAsOpaquePtr(); 3607} 3608 3609Sema::TypeResult 3610Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, 3611 SourceLocation TemplateLoc, TypeTy *Ty) { 3612 QualType T = GetTypeFromParser(Ty); 3613 NestedNameSpecifier *NNS 3614 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3615 const TemplateSpecializationType *TemplateId 3616 = T->getAs<TemplateSpecializationType>(); 3617 assert(TemplateId && "Expected a template specialization type"); 3618 3619 if (computeDeclContext(SS, false)) { 3620 // If we can compute a declaration context, then the "typename" 3621 // keyword was superfluous. Just build a QualifiedNameType to keep 3622 // track of the nested-name-specifier. 3623 3624 // FIXME: Note that the QualifiedNameType had the "typename" keyword! 3625 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr(); 3626 } 3627 3628 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr(); 3629} 3630 3631/// \brief Build the type that describes a C++ typename specifier, 3632/// e.g., "typename T::type". 3633QualType 3634Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II, 3635 SourceRange Range) { 3636 CXXRecordDecl *CurrentInstantiation = 0; 3637 if (NNS->isDependent()) { 3638 CurrentInstantiation = getCurrentInstantiationOf(NNS); 3639 3640 // If the nested-name-specifier does not refer to the current 3641 // instantiation, then build a typename type. 3642 if (!CurrentInstantiation) 3643 return Context.getTypenameType(NNS, &II); 3644 3645 // The nested-name-specifier refers to the current instantiation, so the 3646 // "typename" keyword itself is superfluous. In C++03, the program is 3647 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such 3648 // extraneous "typename" keywords, and we retroactively apply this DR to 3649 // C++03 code. 3650 } 3651 3652 DeclContext *Ctx = 0; 3653 3654 if (CurrentInstantiation) 3655 Ctx = CurrentInstantiation; 3656 else { 3657 CXXScopeSpec SS; 3658 SS.setScopeRep(NNS); 3659 SS.setRange(Range); 3660 if (RequireCompleteDeclContext(SS)) 3661 return QualType(); 3662 3663 Ctx = computeDeclContext(SS); 3664 } 3665 assert(Ctx && "No declaration context?"); 3666 3667 DeclarationName Name(&II); 3668 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName, 3669 false); 3670 unsigned DiagID = 0; 3671 Decl *Referenced = 0; 3672 switch (Result.getKind()) { 3673 case LookupResult::NotFound: 3674 if (Ctx->isTranslationUnit()) 3675 DiagID = diag::err_typename_nested_not_found_global; 3676 else 3677 DiagID = diag::err_typename_nested_not_found; 3678 break; 3679 3680 case LookupResult::Found: 3681 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) { 3682 // We found a type. Build a QualifiedNameType, since the 3683 // typename-specifier was just sugar. FIXME: Tell 3684 // QualifiedNameType that it has a "typename" prefix. 3685 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type)); 3686 } 3687 3688 DiagID = diag::err_typename_nested_not_type; 3689 Referenced = Result.getAsDecl(); 3690 break; 3691 3692 case LookupResult::FoundOverloaded: 3693 DiagID = diag::err_typename_nested_not_type; 3694 Referenced = *Result.begin(); 3695 break; 3696 3697 case LookupResult::AmbiguousBaseSubobjectTypes: 3698 case LookupResult::AmbiguousBaseSubobjects: 3699 case LookupResult::AmbiguousReference: 3700 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range); 3701 return QualType(); 3702 } 3703 3704 // If we get here, it's because name lookup did not find a 3705 // type. Emit an appropriate diagnostic and return an error. 3706 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx)) 3707 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx; 3708 else 3709 Diag(Range.getEnd(), DiagID) << Range << Name; 3710 if (Referenced) 3711 Diag(Referenced->getLocation(), diag::note_typename_refers_here) 3712 << Name; 3713 return QualType(); 3714} 3715 3716namespace { 3717 // See Sema::RebuildTypeInCurrentInstantiation 3718 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder 3719 : public TreeTransform<CurrentInstantiationRebuilder> { 3720 SourceLocation Loc; 3721 DeclarationName Entity; 3722 3723 public: 3724 CurrentInstantiationRebuilder(Sema &SemaRef, 3725 SourceLocation Loc, 3726 DeclarationName Entity) 3727 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), 3728 Loc(Loc), Entity(Entity) { } 3729 3730 /// \brief Determine whether the given type \p T has already been 3731 /// transformed. 3732 /// 3733 /// For the purposes of type reconstruction, a type has already been 3734 /// transformed if it is NULL or if it is not dependent. 3735 bool AlreadyTransformed(QualType T) { 3736 return T.isNull() || !T->isDependentType(); 3737 } 3738 3739 /// \brief Returns the location of the entity whose type is being 3740 /// rebuilt. 3741 SourceLocation getBaseLocation() { return Loc; } 3742 3743 /// \brief Returns the name of the entity whose type is being rebuilt. 3744 DeclarationName getBaseEntity() { return Entity; } 3745 3746 /// \brief Transforms an expression by returning the expression itself 3747 /// (an identity function). 3748 /// 3749 /// FIXME: This is completely unsafe; we will need to actually clone the 3750 /// expressions. 3751 Sema::OwningExprResult TransformExpr(Expr *E) { 3752 return getSema().Owned(E); 3753 } 3754 3755 /// \brief Transforms a typename type by determining whether the type now 3756 /// refers to a member of the current instantiation, and then 3757 /// type-checking and building a QualifiedNameType (when possible). 3758 QualType TransformTypenameType(const TypenameType *T); 3759 }; 3760} 3761 3762QualType 3763CurrentInstantiationRebuilder::TransformTypenameType(const TypenameType *T) { 3764 NestedNameSpecifier *NNS 3765 = TransformNestedNameSpecifier(T->getQualifier(), 3766 /*FIXME:*/SourceRange(getBaseLocation())); 3767 if (!NNS) 3768 return QualType(); 3769 3770 // If the nested-name-specifier did not change, and we cannot compute the 3771 // context corresponding to the nested-name-specifier, then this 3772 // typename type will not change; exit early. 3773 CXXScopeSpec SS; 3774 SS.setRange(SourceRange(getBaseLocation())); 3775 SS.setScopeRep(NNS); 3776 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0) 3777 return QualType(T, 0); 3778 3779 // Rebuild the typename type, which will probably turn into a 3780 // QualifiedNameType. 3781 if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) { 3782 QualType NewTemplateId 3783 = TransformType(QualType(TemplateId, 0)); 3784 if (NewTemplateId.isNull()) 3785 return QualType(); 3786 3787 if (NNS == T->getQualifier() && 3788 NewTemplateId == QualType(TemplateId, 0)) 3789 return QualType(T, 0); 3790 3791 return getDerived().RebuildTypenameType(NNS, NewTemplateId); 3792 } 3793 3794 return getDerived().RebuildTypenameType(NNS, T->getIdentifier()); 3795} 3796 3797/// \brief Rebuilds a type within the context of the current instantiation. 3798/// 3799/// The type \p T is part of the type of an out-of-line member definition of 3800/// a class template (or class template partial specialization) that was parsed 3801/// and constructed before we entered the scope of the class template (or 3802/// partial specialization thereof). This routine will rebuild that type now 3803/// that we have entered the declarator's scope, which may produce different 3804/// canonical types, e.g., 3805/// 3806/// \code 3807/// template<typename T> 3808/// struct X { 3809/// typedef T* pointer; 3810/// pointer data(); 3811/// }; 3812/// 3813/// template<typename T> 3814/// typename X<T>::pointer X<T>::data() { ... } 3815/// \endcode 3816/// 3817/// Here, the type "typename X<T>::pointer" will be created as a TypenameType, 3818/// since we do not know that we can look into X<T> when we parsed the type. 3819/// This function will rebuild the type, performing the lookup of "pointer" 3820/// in X<T> and returning a QualifiedNameType whose canonical type is the same 3821/// as the canonical type of T*, allowing the return types of the out-of-line 3822/// definition and the declaration to match. 3823QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc, 3824 DeclarationName Name) { 3825 if (T.isNull() || !T->isDependentType()) 3826 return T; 3827 3828 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); 3829 return Rebuilder.TransformType(T); 3830} 3831 3832/// \brief Produces a formatted string that describes the binding of 3833/// template parameters to template arguments. 3834std::string 3835Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 3836 const TemplateArgumentList &Args) { 3837 std::string Result; 3838 3839 if (!Params || Params->size() == 0) 3840 return Result; 3841 3842 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 3843 if (I == 0) 3844 Result += "[with "; 3845 else 3846 Result += ", "; 3847 3848 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { 3849 Result += Id->getName(); 3850 } else { 3851 Result += '$'; 3852 Result += llvm::utostr(I); 3853 } 3854 3855 Result += " = "; 3856 3857 switch (Args[I].getKind()) { 3858 case TemplateArgument::Null: 3859 Result += "<no value>"; 3860 break; 3861 3862 case TemplateArgument::Type: { 3863 std::string TypeStr; 3864 Args[I].getAsType().getAsStringInternal(TypeStr, 3865 Context.PrintingPolicy); 3866 Result += TypeStr; 3867 break; 3868 } 3869 3870 case TemplateArgument::Declaration: { 3871 bool Unnamed = true; 3872 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) { 3873 if (ND->getDeclName()) { 3874 Unnamed = false; 3875 Result += ND->getNameAsString(); 3876 } 3877 } 3878 3879 if (Unnamed) { 3880 Result += "<anonymous>"; 3881 } 3882 break; 3883 } 3884 3885 case TemplateArgument::Integral: { 3886 Result += Args[I].getAsIntegral()->toString(10); 3887 break; 3888 } 3889 3890 case TemplateArgument::Expression: { 3891 assert(false && "No expressions in deduced template arguments!"); 3892 Result += "<expression>"; 3893 break; 3894 } 3895 3896 case TemplateArgument::Pack: 3897 // FIXME: Format template argument packs 3898 Result += "<template argument pack>"; 3899 break; 3900 } 3901 } 3902 3903 Result += ']'; 3904 return Result; 3905} 3906