SemaTemplate.cpp revision 5d290d584a82bb1cbfffa1b9a9a278538970e1b9
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/DeclTemplate.h" 18#include "clang/Parse/DeclSpec.h" 19#include "clang/Basic/LangOptions.h" 20 21using namespace clang; 22 23/// isTemplateName - Determines whether the identifier II is a 24/// template name in the current scope, and returns the template 25/// declaration if II names a template. An optional CXXScope can be 26/// passed to indicate the C++ scope in which the identifier will be 27/// found. 28Sema::TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S, 29 DeclTy *&Template, 30 const CXXScopeSpec *SS) { 31 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName); 32 33 if (IIDecl) { 34 if (isa<TemplateDecl>(IIDecl)) { 35 Template = IIDecl; 36 if (isa<FunctionTemplateDecl>(IIDecl)) 37 return TNK_Function_template; 38 else if (isa<ClassTemplateDecl>(IIDecl)) 39 return TNK_Class_template; 40 else if (isa<TemplateTemplateParmDecl>(IIDecl)) 41 return TNK_Template_template_parm; 42 else 43 assert(false && "Unknown TemplateDecl"); 44 } 45 46 // FIXME: What follows is a gross hack. 47 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) { 48 if (FD->getType()->isDependentType()) { 49 Template = FD; 50 return TNK_Function_template; 51 } 52 } else if (OverloadedFunctionDecl *Ovl 53 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) { 54 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 55 FEnd = Ovl->function_end(); 56 F != FEnd; ++F) { 57 if ((*F)->getType()->isDependentType()) { 58 Template = Ovl; 59 return TNK_Function_template; 60 } 61 } 62 } 63 } 64 return TNK_Non_template; 65} 66 67/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 68/// that the template parameter 'PrevDecl' is being shadowed by a new 69/// declaration at location Loc. Returns true to indicate that this is 70/// an error, and false otherwise. 71bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 72 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 73 74 // Microsoft Visual C++ permits template parameters to be shadowed. 75 if (getLangOptions().Microsoft) 76 return false; 77 78 // C++ [temp.local]p4: 79 // A template-parameter shall not be redeclared within its 80 // scope (including nested scopes). 81 Diag(Loc, diag::err_template_param_shadow) 82 << cast<NamedDecl>(PrevDecl)->getDeclName(); 83 Diag(PrevDecl->getLocation(), diag::note_template_param_here); 84 return true; 85} 86 87/// AdjustDeclForTemplates - If the given decl happens to be a template, reset 88/// the parameter D to reference the templated declaration and return a pointer 89/// to the template declaration. Otherwise, do nothing to D and return null. 90TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D) 91{ 92 if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) { 93 D = Temp->getTemplatedDecl(); 94 return Temp; 95 } 96 return 0; 97} 98 99/// ActOnTypeParameter - Called when a C++ template type parameter 100/// (e.g., "typename T") has been parsed. Typename specifies whether 101/// the keyword "typename" was used to declare the type parameter 102/// (otherwise, "class" was used), and KeyLoc is the location of the 103/// "class" or "typename" keyword. ParamName is the name of the 104/// parameter (NULL indicates an unnamed template parameter) and 105/// ParamName is the location of the parameter name (if any). 106/// If the type parameter has a default argument, it will be added 107/// later via ActOnTypeParameterDefault. 108Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename, 109 SourceLocation KeyLoc, 110 IdentifierInfo *ParamName, 111 SourceLocation ParamNameLoc, 112 unsigned Depth, unsigned Position) { 113 assert(S->isTemplateParamScope() && 114 "Template type parameter not in template parameter scope!"); 115 bool Invalid = false; 116 117 if (ParamName) { 118 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName); 119 if (PrevDecl && PrevDecl->isTemplateParameter()) 120 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc, 121 PrevDecl); 122 } 123 124 SourceLocation Loc = ParamNameLoc; 125 if (!ParamName) 126 Loc = KeyLoc; 127 128 TemplateTypeParmDecl *Param 129 = TemplateTypeParmDecl::Create(Context, CurContext, Loc, 130 Depth, Position, ParamName, Typename); 131 if (Invalid) 132 Param->setInvalidDecl(); 133 134 if (ParamName) { 135 // Add the template parameter into the current scope. 136 S->AddDecl(Param); 137 IdResolver.AddDecl(Param); 138 } 139 140 return Param; 141} 142 143/// ActOnNonTypeTemplateParameter - Called when a C++ non-type 144/// template parameter (e.g., "int Size" in "template<int Size> 145/// class Array") has been parsed. S is the current scope and D is 146/// the parsed declarator. 147Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 148 unsigned Depth, 149 unsigned Position) { 150 QualType T = GetTypeForDeclarator(D, S); 151 152 assert(S->isTemplateParamScope() && 153 "Non-type template parameter not in template parameter scope!"); 154 bool Invalid = false; 155 156 IdentifierInfo *ParamName = D.getIdentifier(); 157 if (ParamName) { 158 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName); 159 if (PrevDecl && PrevDecl->isTemplateParameter()) 160 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 161 PrevDecl); 162 } 163 164 // C++ [temp.param]p4: 165 // 166 // A non-type template-parameter shall have one of the following 167 // (optionally cv-qualified) types: 168 // 169 // -- integral or enumeration type, 170 if (T->isIntegralType() || T->isEnumeralType() || 171 // -- pointer to object or pointer to function, 172 T->isPointerType() || 173 // -- reference to object or reference to function, 174 T->isReferenceType() || 175 // -- pointer to member. 176 T->isMemberPointerType() || 177 // If T is a dependent type, we can't do the check now, so we 178 // assume that it is well-formed. 179 T->isDependentType()) { 180 // Okay: The template parameter is well-formed. 181 } 182 // C++ [temp.param]p8: 183 // 184 // A non-type template-parameter of type "array of T" or 185 // "function returning T" is adjusted to be of type "pointer to 186 // T" or "pointer to function returning T", respectively. 187 else if (T->isArrayType()) 188 // FIXME: Keep the type prior to promotion? 189 T = Context.getArrayDecayedType(T); 190 else if (T->isFunctionType()) 191 // FIXME: Keep the type prior to promotion? 192 T = Context.getPointerType(T); 193 else { 194 Diag(D.getIdentifierLoc(), diag::err_template_nontype_parm_bad_type) 195 << T; 196 return 0; 197 } 198 199 NonTypeTemplateParmDecl *Param 200 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(), 201 Depth, Position, ParamName, T); 202 if (Invalid) 203 Param->setInvalidDecl(); 204 205 if (D.getIdentifier()) { 206 // Add the template parameter into the current scope. 207 S->AddDecl(Param); 208 IdResolver.AddDecl(Param); 209 } 210 return Param; 211} 212 213 214/// ActOnTemplateTemplateParameter - Called when a C++ template template 215/// parameter (e.g. T in template <template <typename> class T> class array) 216/// has been parsed. S is the current scope. 217Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S, 218 SourceLocation TmpLoc, 219 TemplateParamsTy *Params, 220 IdentifierInfo *Name, 221 SourceLocation NameLoc, 222 unsigned Depth, 223 unsigned Position) 224{ 225 assert(S->isTemplateParamScope() && 226 "Template template parameter not in template parameter scope!"); 227 228 // Construct the parameter object. 229 TemplateTemplateParmDecl *Param = 230 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth, 231 Position, Name, 232 (TemplateParameterList*)Params); 233 234 // Make sure the parameter is valid. 235 // FIXME: Decl object is not currently invalidated anywhere so this doesn't 236 // do anything yet. However, if the template parameter list or (eventual) 237 // default value is ever invalidated, that will propagate here. 238 bool Invalid = false; 239 if (Invalid) { 240 Param->setInvalidDecl(); 241 } 242 243 // If the tt-param has a name, then link the identifier into the scope 244 // and lookup mechanisms. 245 if (Name) { 246 S->AddDecl(Param); 247 IdResolver.AddDecl(Param); 248 } 249 250 return Param; 251} 252 253/// ActOnTemplateParameterList - Builds a TemplateParameterList that 254/// contains the template parameters in Params/NumParams. 255Sema::TemplateParamsTy * 256Sema::ActOnTemplateParameterList(unsigned Depth, 257 SourceLocation ExportLoc, 258 SourceLocation TemplateLoc, 259 SourceLocation LAngleLoc, 260 DeclTy **Params, unsigned NumParams, 261 SourceLocation RAngleLoc) { 262 if (ExportLoc.isValid()) 263 Diag(ExportLoc, diag::note_template_export_unsupported); 264 265 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, 266 (Decl**)Params, NumParams, RAngleLoc); 267} 268 269Sema::DeclTy * 270Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK, 271 SourceLocation KWLoc, const CXXScopeSpec &SS, 272 IdentifierInfo *Name, SourceLocation NameLoc, 273 AttributeList *Attr, 274 MultiTemplateParamsArg TemplateParameterLists) { 275 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?"); 276 assert(TK != TK_Reference && "Can only declare or define class templates"); 277 278 // Check that we can declare a template here. 279 if (CheckTemplateDeclScope(S, TemplateParameterLists)) 280 return 0; 281 282 TagDecl::TagKind Kind; 283 switch (TagSpec) { 284 default: assert(0 && "Unknown tag type!"); 285 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 286 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 287 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 288 } 289 290 // There is no such thing as an unnamed class template. 291 if (!Name) { 292 Diag(KWLoc, diag::err_template_unnamed_class); 293 return 0; 294 } 295 296 // Find any previous declaration with this name. 297 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName, 298 true); 299 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?"); 300 NamedDecl *PrevDecl = 0; 301 if (Previous.begin() != Previous.end()) 302 PrevDecl = *Previous.begin(); 303 304 DeclContext *SemanticContext = CurContext; 305 if (SS.isNotEmpty() && !SS.isInvalid()) { 306 SemanticContext = static_cast<DeclContext*>(SS.getScopeRep()); 307 308 // FIXME: need to match up several levels of template parameter 309 // lists here. 310 } 311 312 // FIXME: member templates! 313 TemplateParameterList *TemplateParams 314 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release()); 315 316 // If there is a previous declaration with the same name, check 317 // whether this is a valid redeclaration. 318 ClassTemplateDecl *PrevClassTemplate 319 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); 320 if (PrevClassTemplate) { 321 // Ensure that the template parameter lists are compatible. 322 if (!TemplateParameterListsAreEqual(TemplateParams, 323 PrevClassTemplate->getTemplateParameters(), 324 /*Complain=*/true)) 325 return 0; 326 327 // C++ [temp.class]p4: 328 // In a redeclaration, partial specialization, explicit 329 // specialization or explicit instantiation of a class template, 330 // the class-key shall agree in kind with the original class 331 // template declaration (7.1.5.3). 332 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 333 if (PrevRecordDecl->getTagKind() != Kind) { 334 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 335 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 336 return 0; 337 } 338 339 340 // Check for redefinition of this class template. 341 if (TK == TK_Definition) { 342 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) { 343 Diag(NameLoc, diag::err_redefinition) << Name; 344 Diag(Def->getLocation(), diag::note_previous_definition); 345 // FIXME: Would it make sense to try to "forget" the previous 346 // definition, as part of error recovery? 347 return 0; 348 } 349 } 350 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 351 // Maybe we will complain about the shadowed template parameter. 352 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 353 // Just pretend that we didn't see the previous declaration. 354 PrevDecl = 0; 355 } else if (PrevDecl) { 356 // C++ [temp]p5: 357 // A class template shall not have the same name as any other 358 // template, class, function, object, enumeration, enumerator, 359 // namespace, or type in the same scope (3.3), except as specified 360 // in (14.5.4). 361 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 362 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 363 return 0; 364 } 365 366 // If we had a scope specifier, we better have a previous template 367 // declaration! 368 369 TagDecl *NewClass = 370 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, 371 PrevClassTemplate? 372 PrevClassTemplate->getTemplatedDecl() : 0); 373 374 ClassTemplateDecl *NewTemplate 375 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 376 DeclarationName(Name), TemplateParams, 377 NewClass); 378 379 // Set the lexical context of these templates 380 NewClass->setLexicalDeclContext(CurContext); 381 NewTemplate->setLexicalDeclContext(CurContext); 382 383 if (TK == TK_Definition) 384 NewClass->startDefinition(); 385 386 if (Attr) 387 ProcessDeclAttributeList(NewClass, Attr); 388 389 PushOnScopeChains(NewTemplate, S); 390 391 return NewTemplate; 392} 393 394 395 396Action::TypeTy * 397Sema::ActOnClassTemplateSpecialization(DeclTy *TemplateD, 398 SourceLocation TemplateLoc, 399 SourceLocation LAngleLoc, 400 ASTTemplateArgsPtr TemplateArgs, 401 SourceLocation *TemplateArgLocs, 402 SourceLocation RAngleLoc, 403 const CXXScopeSpec *SS) { 404 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD)); 405 406 // Check that the template argument list is well-formed for this 407 // template. 408 if (!CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc, 409 TemplateArgs, TemplateArgLocs, RAngleLoc)) 410 return 0; 411 412 // Yes, all class template specializations are just silly sugar for 413 // 'int'. Gotta problem wit dat? 414 QualType Result 415 = Context.getClassTemplateSpecializationType(Template, 416 TemplateArgs.size(), 417 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()), 418 TemplateArgs.getArgIsType(), 419 Context.IntTy); 420 TemplateArgs.release(); 421 return Result.getAsOpaquePtr(); 422} 423 424/// \brief Check that the given template argument list is well-formed 425/// for specializing the given template. 426bool Sema::CheckTemplateArgumentList(TemplateDecl *Template, 427 SourceLocation TemplateLoc, 428 SourceLocation LAngleLoc, 429 ASTTemplateArgsPtr& Args, 430 SourceLocation *TemplateArgLocs, 431 SourceLocation RAngleLoc) { 432 TemplateParameterList *Params = Template->getTemplateParameters(); 433 unsigned NumParams = Params->size(); 434 unsigned NumArgs = Args.size(); 435 bool Invalid = false; 436 437 if (NumArgs > NumParams || 438 NumArgs < NumParams /*FIXME: default arguments! */) { 439 // FIXME: point at either the first arg beyond what we can handle, 440 // or the '>', depending on whether we have too many or too few 441 // arguments. 442 SourceRange Range; 443 if (NumArgs > NumParams) 444 Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc); 445 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 446 << (NumArgs > NumParams) 447 << (isa<ClassTemplateDecl>(Template)? 0 : 448 isa<FunctionTemplateDecl>(Template)? 1 : 449 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 450 << Template << Range; 451 452 Invalid = true; 453 } 454 455 // C++ [temp.arg]p1: 456 // [...] The type and form of each template-argument specified in 457 // a template-id shall match the type and form specified for the 458 // corresponding parameter declared by the template in its 459 // template-parameter-list. 460 unsigned ArgIdx = 0; 461 for (TemplateParameterList::iterator Param = Params->begin(), 462 ParamEnd = Params->end(); 463 Param != ParamEnd; ++Param, ++ArgIdx) { 464 // Decode the template argument 465 QualType ArgType; 466 Expr *ArgExpr = 0; 467 SourceLocation ArgLoc; 468 if (ArgIdx >= NumArgs) { 469 // FIXME: Get the default argument here, which might 470 // (eventually) require instantiation. 471 break; 472 } else 473 ArgLoc = TemplateArgLocs[ArgIdx]; 474 475 if (Args.getArgIsType()[ArgIdx]) 476 ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]); 477 else 478 ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]); 479 480 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 481 // Check template type parameters. 482 if (!ArgType.isNull()) { 483 if (!CheckTemplateArgument(TTP, ArgType, ArgLoc)) 484 Invalid = true; 485 continue; 486 } 487 488 // C++ [temp.arg.type]p1: 489 // A template-argument for a template-parameter which is a 490 // type shall be a type-id. 491 492 // We have a template type parameter but the template argument 493 // is an expression. 494 Diag(ArgExpr->getSourceRange().getBegin(), 495 diag::err_template_arg_must_be_type); 496 Diag((*Param)->getLocation(), diag::note_template_param_here); 497 Invalid = true; 498 } else if (NonTypeTemplateParmDecl *NTTP 499 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 500 // Check non-type template parameters. 501 if (ArgExpr) { 502 if (!CheckTemplateArgument(NTTP, ArgExpr)) 503 Invalid = true; 504 continue; 505 } 506 507 // We have a non-type template parameter but the template 508 // argument is a type. 509 510 // C++ [temp.arg]p2: 511 // In a template-argument, an ambiguity between a type-id and 512 // an expression is resolved to a type-id, regardless of the 513 // form of the corresponding template-parameter. 514 // 515 // We warn specifically about this case, since it can be rather 516 // confusing for users. 517 if (ArgType->isFunctionType()) 518 Diag(ArgLoc, diag::err_template_arg_nontype_ambig) 519 << ArgType; 520 else 521 Diag(ArgLoc, diag::err_template_arg_must_be_expr); 522 Diag((*Param)->getLocation(), diag::note_template_param_here); 523 Invalid = true; 524 } else { 525 // Check template template parameters. 526 TemplateTemplateParmDecl *TempParm 527 = cast<TemplateTemplateParmDecl>(*Param); 528 529 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) && 530 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) { 531 if (!CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr))) 532 Invalid = true; 533 continue; 534 } 535 536 // We have a template template parameter but the template 537 // argument does not refer to a template. 538 Diag(ArgLoc, diag::err_template_arg_must_be_template); 539 Invalid = true; 540 } 541 } 542 543 return Invalid; 544} 545 546/// \brief Check a template argument against its corresponding 547/// template type parameter. 548/// 549/// This routine implements the semantics of C++ [temp.arg.type]. It 550/// returns true if an error occurred, and false otherwise. 551bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 552 QualType Arg, SourceLocation ArgLoc) { 553 // C++ [temp.arg.type]p2: 554 // A local type, a type with no linkage, an unnamed type or a type 555 // compounded from any of these types shall not be used as a 556 // template-argument for a template type-parameter. 557 // 558 // FIXME: Perform the recursive and no-linkage type checks. 559 const TagType *Tag = 0; 560 if (const EnumType *EnumT = Arg->getAsEnumType()) 561 Tag = EnumT; 562 else if (const RecordType *RecordT = Arg->getAsRecordType()) 563 Tag = RecordT; 564 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) 565 return Diag(ArgLoc, diag::err_template_arg_local_type) 566 << QualType(Tag, 0); 567 else if (Tag && !Tag->getDecl()->getDeclName()) { 568 Diag(ArgLoc, diag::err_template_arg_unnamed_type); 569 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here); 570 return true; 571 } 572 573 return false; 574} 575 576/// \brief Check a template argument against its corresponding 577/// non-type template parameter. 578/// 579/// This routine implements the semantics of C++ [temp.arg.nontype]. 580/// It returns true if an error occurred, and false otherwise. 581bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 582 Expr *Arg) { 583 return false; 584} 585 586/// \brief Check a template argument against its corresponding 587/// template template parameter. 588/// 589/// This routine implements the semantics of C++ [temp.arg.template]. 590/// It returns true if an error occurred, and false otherwise. 591bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, 592 DeclRefExpr *Arg) { 593 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed"); 594 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl()); 595 596 // C++ [temp.arg.template]p1: 597 // A template-argument for a template template-parameter shall be 598 // the name of a class template, expressed as id-expression. Only 599 // primary class templates are considered when matching the 600 // template template argument with the corresponding parameter; 601 // partial specializations are not considered even if their 602 // parameter lists match that of the template template parameter. 603 if (!isa<ClassTemplateDecl>(Template)) { 604 assert(isa<FunctionTemplateDecl>(Template) && 605 "Only function templates are possible here"); 606 Diag(Arg->getSourceRange().getBegin(), diag::note_template_arg_refers_here) 607 << Template; 608 } 609 610 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 611 Param->getTemplateParameters(), 612 true, true, 613 Arg->getSourceRange().getBegin()); 614} 615 616/// \brief Determine whether the given template parameter lists are 617/// equivalent. 618/// 619/// \param New The new template parameter list, typically written in the 620/// source code as part of a new template declaration. 621/// 622/// \param Old The old template parameter list, typically found via 623/// name lookup of the template declared with this template parameter 624/// list. 625/// 626/// \param Complain If true, this routine will produce a diagnostic if 627/// the template parameter lists are not equivalent. 628/// 629/// \param IsTemplateTemplateParm If true, this routine is being 630/// called to compare the template parameter lists of a template 631/// template parameter. 632/// 633/// \param TemplateArgLoc If this source location is valid, then we 634/// are actually checking the template parameter list of a template 635/// argument (New) against the template parameter list of its 636/// corresponding template template parameter (Old). We produce 637/// slightly different diagnostics in this scenario. 638/// 639/// \returns True if the template parameter lists are equal, false 640/// otherwise. 641bool 642Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 643 TemplateParameterList *Old, 644 bool Complain, 645 bool IsTemplateTemplateParm, 646 SourceLocation TemplateArgLoc) { 647 if (Old->size() != New->size()) { 648 if (Complain) { 649 unsigned NextDiag = diag::err_template_param_list_different_arity; 650 if (TemplateArgLoc.isValid()) { 651 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 652 NextDiag = diag::note_template_param_list_different_arity; 653 } 654 Diag(New->getTemplateLoc(), NextDiag) 655 << (New->size() > Old->size()) 656 << IsTemplateTemplateParm 657 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 658 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 659 << IsTemplateTemplateParm 660 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 661 } 662 663 return false; 664 } 665 666 for (TemplateParameterList::iterator OldParm = Old->begin(), 667 OldParmEnd = Old->end(), NewParm = New->begin(); 668 OldParm != OldParmEnd; ++OldParm, ++NewParm) { 669 if ((*OldParm)->getKind() != (*NewParm)->getKind()) { 670 unsigned NextDiag = diag::err_template_param_different_kind; 671 if (TemplateArgLoc.isValid()) { 672 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 673 NextDiag = diag::note_template_param_different_kind; 674 } 675 Diag((*NewParm)->getLocation(), NextDiag) 676 << IsTemplateTemplateParm; 677 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration) 678 << IsTemplateTemplateParm; 679 return false; 680 } 681 682 if (isa<TemplateTypeParmDecl>(*OldParm)) { 683 // Okay; all template type parameters are equivalent (since we 684 // know we're at the same index). 685#if 0 686 // FIXME: Enable this code in debug mode *after* we properly go 687 // through and "instantiate" the template parameter lists of 688 // template template parameters. It's only after this 689 // instantiation that (1) any dependent types within the 690 // template parameter list of the template template parameter 691 // can be checked, and (2) the template type parameter depths 692 // will match up. 693 QualType OldParmType 694 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm)); 695 QualType NewParmType 696 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm)); 697 assert(Context.getCanonicalType(OldParmType) == 698 Context.getCanonicalType(NewParmType) && 699 "type parameter mismatch?"); 700#endif 701 } else if (NonTypeTemplateParmDecl *OldNTTP 702 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) { 703 // The types of non-type template parameters must agree. 704 NonTypeTemplateParmDecl *NewNTTP 705 = cast<NonTypeTemplateParmDecl>(*NewParm); 706 if (Context.getCanonicalType(OldNTTP->getType()) != 707 Context.getCanonicalType(NewNTTP->getType())) { 708 if (Complain) { 709 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 710 if (TemplateArgLoc.isValid()) { 711 Diag(TemplateArgLoc, 712 diag::err_template_arg_template_params_mismatch); 713 NextDiag = diag::note_template_nontype_parm_different_type; 714 } 715 Diag(NewNTTP->getLocation(), NextDiag) 716 << NewNTTP->getType() 717 << IsTemplateTemplateParm; 718 Diag(OldNTTP->getLocation(), 719 diag::note_template_nontype_parm_prev_declaration) 720 << OldNTTP->getType(); 721 } 722 return false; 723 } 724 } else { 725 // The template parameter lists of template template 726 // parameters must agree. 727 // FIXME: Could we perform a faster "type" comparison here? 728 assert(isa<TemplateTemplateParmDecl>(*OldParm) && 729 "Only template template parameters handled here"); 730 TemplateTemplateParmDecl *OldTTP 731 = cast<TemplateTemplateParmDecl>(*OldParm); 732 TemplateTemplateParmDecl *NewTTP 733 = cast<TemplateTemplateParmDecl>(*NewParm); 734 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 735 OldTTP->getTemplateParameters(), 736 Complain, 737 /*IsTemplateTemplateParm=*/true, 738 TemplateArgLoc)) 739 return false; 740 } 741 } 742 743 return true; 744} 745 746/// \brief Check whether a template can be declared within this scope. 747/// 748/// If the template declaration is valid in this scope, returns 749/// false. Otherwise, issues a diagnostic and returns true. 750bool 751Sema::CheckTemplateDeclScope(Scope *S, 752 MultiTemplateParamsArg &TemplateParameterLists) { 753 assert(TemplateParameterLists.size() > 0 && "Not a template"); 754 755 // Find the nearest enclosing declaration scope. 756 while ((S->getFlags() & Scope::DeclScope) == 0 || 757 (S->getFlags() & Scope::TemplateParamScope) != 0) 758 S = S->getParent(); 759 760 TemplateParameterList *TemplateParams = 761 static_cast<TemplateParameterList*>(*TemplateParameterLists.get()); 762 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc(); 763 SourceRange TemplateRange 764 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc()); 765 766 // C++ [temp]p2: 767 // A template-declaration can appear only as a namespace scope or 768 // class scope declaration. 769 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 770 while (Ctx && isa<LinkageSpecDecl>(Ctx)) { 771 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx) 772 return Diag(TemplateLoc, diag::err_template_linkage) 773 << TemplateRange; 774 775 Ctx = Ctx->getParent(); 776 } 777 778 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord())) 779 return false; 780 781 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope) 782 << TemplateRange; 783} 784