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