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