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