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