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