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