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