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