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