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