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