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