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