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