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