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