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