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