SemaTemplate.cpp revision edce4dd44732dfad69f28822dddcf2b8e92b4483
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)) 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 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 TemplateArgumentListBuilder &Converted) { 1059 TemplateParameterList *Params = Template->getTemplateParameters(); 1060 unsigned NumParams = Params->size(); 1061 unsigned NumArgs = NumTemplateArgs; 1062 bool Invalid = false; 1063 1064 bool HasParameterPack = 1065 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack(); 1066 1067 if ((NumArgs > NumParams && !HasParameterPack) || 1068 NumArgs < Params->getMinRequiredArguments()) { 1069 // FIXME: point at either the first arg beyond what we can handle, 1070 // or the '>', depending on whether we have too many or too few 1071 // arguments. 1072 SourceRange Range; 1073 if (NumArgs > NumParams) 1074 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc); 1075 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 1076 << (NumArgs > NumParams) 1077 << (isa<ClassTemplateDecl>(Template)? 0 : 1078 isa<FunctionTemplateDecl>(Template)? 1 : 1079 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 1080 << Template << Range; 1081 Diag(Template->getLocation(), diag::note_template_decl_here) 1082 << Params->getSourceRange(); 1083 Invalid = true; 1084 } 1085 1086 // C++ [temp.arg]p1: 1087 // [...] The type and form of each template-argument specified in 1088 // a template-id shall match the type and form specified for the 1089 // corresponding parameter declared by the template in its 1090 // template-parameter-list. 1091 unsigned ArgIdx = 0; 1092 for (TemplateParameterList::iterator Param = Params->begin(), 1093 ParamEnd = Params->end(); 1094 Param != ParamEnd; ++Param, ++ArgIdx) { 1095 // Decode the template argument 1096 TemplateArgument Arg; 1097 if (ArgIdx >= NumArgs) { 1098 // Retrieve the default template argument from the template 1099 // parameter. 1100 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 1101 if (TTP->isParameterPack()) { 1102 // We have an empty argument pack. 1103 Converted.BeginPack(); 1104 Converted.EndPack(); 1105 break; 1106 } 1107 1108 if (!TTP->hasDefaultArgument()) 1109 break; 1110 1111 QualType ArgType = TTP->getDefaultArgument(); 1112 1113 // If the argument type is dependent, instantiate it now based 1114 // on the previously-computed template arguments. 1115 if (ArgType->isDependentType()) { 1116 InstantiatingTemplate Inst(*this, TemplateLoc, 1117 Template, Converted.getFlatArguments(), 1118 Converted.flatSize(), 1119 SourceRange(TemplateLoc, RAngleLoc)); 1120 1121 TemplateArgumentList TemplateArgs(Context, Converted, 1122 /*TakeArgs=*/false); 1123 ArgType = InstantiateType(ArgType, TemplateArgs, 1124 TTP->getDefaultArgumentLoc(), 1125 TTP->getDeclName()); 1126 } 1127 1128 if (ArgType.isNull()) 1129 return true; 1130 1131 Arg = TemplateArgument(TTP->getLocation(), ArgType); 1132 } else if (NonTypeTemplateParmDecl *NTTP 1133 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 1134 if (!NTTP->hasDefaultArgument()) 1135 break; 1136 1137 InstantiatingTemplate Inst(*this, TemplateLoc, 1138 Template, Converted.getFlatArguments(), 1139 Converted.flatSize(), 1140 SourceRange(TemplateLoc, RAngleLoc)); 1141 1142 TemplateArgumentList TemplateArgs(Context, Converted, 1143 /*TakeArgs=*/false); 1144 1145 Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(), 1146 TemplateArgs); 1147 if (E.isInvalid()) 1148 return true; 1149 1150 Arg = TemplateArgument(E.takeAs<Expr>()); 1151 } else { 1152 TemplateTemplateParmDecl *TempParm 1153 = cast<TemplateTemplateParmDecl>(*Param); 1154 1155 if (!TempParm->hasDefaultArgument()) 1156 break; 1157 1158 // FIXME: Instantiate default argument 1159 Arg = TemplateArgument(TempParm->getDefaultArgument()); 1160 } 1161 } else { 1162 // Retrieve the template argument produced by the user. 1163 Arg = TemplateArgs[ArgIdx]; 1164 } 1165 1166 1167 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 1168 if (TTP->isParameterPack()) { 1169 Converted.BeginPack(); 1170 // Check all the remaining arguments (if any). 1171 for (; ArgIdx < NumArgs; ++ArgIdx) { 1172 if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted)) 1173 Invalid = true; 1174 } 1175 1176 Converted.EndPack(); 1177 } else { 1178 if (CheckTemplateTypeArgument(TTP, Arg, Converted)) 1179 Invalid = true; 1180 } 1181 } else if (NonTypeTemplateParmDecl *NTTP 1182 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 1183 // Check non-type template parameters. 1184 1185 // Instantiate the type of the non-type template parameter with 1186 // the template arguments we've seen thus far. 1187 QualType NTTPType = NTTP->getType(); 1188 if (NTTPType->isDependentType()) { 1189 // Instantiate the type of the non-type template parameter. 1190 InstantiatingTemplate Inst(*this, TemplateLoc, 1191 Template, Converted.getFlatArguments(), 1192 Converted.flatSize(), 1193 SourceRange(TemplateLoc, RAngleLoc)); 1194 1195 TemplateArgumentList TemplateArgs(Context, Converted, 1196 /*TakeArgs=*/false); 1197 NTTPType = InstantiateType(NTTPType, TemplateArgs, 1198 NTTP->getLocation(), 1199 NTTP->getDeclName()); 1200 // If that worked, check the non-type template parameter type 1201 // for validity. 1202 if (!NTTPType.isNull()) 1203 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 1204 NTTP->getLocation()); 1205 if (NTTPType.isNull()) { 1206 Invalid = true; 1207 break; 1208 } 1209 } 1210 1211 switch (Arg.getKind()) { 1212 case TemplateArgument::Null: 1213 assert(false && "Should never see a NULL template argument here"); 1214 break; 1215 1216 case TemplateArgument::Expression: { 1217 Expr *E = Arg.getAsExpr(); 1218 TemplateArgument Result; 1219 if (CheckTemplateArgument(NTTP, NTTPType, E, Result)) 1220 Invalid = true; 1221 else 1222 Converted.Append(Result); 1223 break; 1224 } 1225 1226 case TemplateArgument::Declaration: 1227 case TemplateArgument::Integral: 1228 // We've already checked this template argument, so just copy 1229 // it to the list of converted arguments. 1230 Converted.Append(Arg); 1231 break; 1232 1233 case TemplateArgument::Type: 1234 // We have a non-type template parameter but the template 1235 // argument is a type. 1236 1237 // C++ [temp.arg]p2: 1238 // In a template-argument, an ambiguity between a type-id and 1239 // an expression is resolved to a type-id, regardless of the 1240 // form of the corresponding template-parameter. 1241 // 1242 // We warn specifically about this case, since it can be rather 1243 // confusing for users. 1244 if (Arg.getAsType()->isFunctionType()) 1245 Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig) 1246 << Arg.getAsType(); 1247 else 1248 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr); 1249 Diag((*Param)->getLocation(), diag::note_template_param_here); 1250 Invalid = true; 1251 break; 1252 1253 case TemplateArgument::Pack: 1254 assert(0 && "FIXME: Implement!"); 1255 break; 1256 } 1257 } else { 1258 // Check template template parameters. 1259 TemplateTemplateParmDecl *TempParm 1260 = cast<TemplateTemplateParmDecl>(*Param); 1261 1262 switch (Arg.getKind()) { 1263 case TemplateArgument::Null: 1264 assert(false && "Should never see a NULL template argument here"); 1265 break; 1266 1267 case TemplateArgument::Expression: { 1268 Expr *ArgExpr = Arg.getAsExpr(); 1269 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) && 1270 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) { 1271 if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr))) 1272 Invalid = true; 1273 1274 // Add the converted template argument. 1275 Decl *D 1276 = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl()); 1277 Converted.Append(TemplateArgument(Arg.getLocation(), D)); 1278 continue; 1279 } 1280 } 1281 // fall through 1282 1283 case TemplateArgument::Type: { 1284 // We have a template template parameter but the template 1285 // argument does not refer to a template. 1286 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template); 1287 Invalid = true; 1288 break; 1289 } 1290 1291 case TemplateArgument::Declaration: 1292 // We've already checked this template argument, so just copy 1293 // it to the list of converted arguments. 1294 Converted.Append(Arg); 1295 break; 1296 1297 case TemplateArgument::Integral: 1298 assert(false && "Integral argument with template template parameter"); 1299 break; 1300 1301 case TemplateArgument::Pack: 1302 assert(0 && "FIXME: Implement!"); 1303 break; 1304 } 1305 } 1306 } 1307 1308 return Invalid; 1309} 1310 1311/// \brief Check a template argument against its corresponding 1312/// template type parameter. 1313/// 1314/// This routine implements the semantics of C++ [temp.arg.type]. It 1315/// returns true if an error occurred, and false otherwise. 1316bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 1317 QualType Arg, SourceLocation ArgLoc) { 1318 // C++ [temp.arg.type]p2: 1319 // A local type, a type with no linkage, an unnamed type or a type 1320 // compounded from any of these types shall not be used as a 1321 // template-argument for a template type-parameter. 1322 // 1323 // FIXME: Perform the recursive and no-linkage type checks. 1324 const TagType *Tag = 0; 1325 if (const EnumType *EnumT = Arg->getAsEnumType()) 1326 Tag = EnumT; 1327 else if (const RecordType *RecordT = Arg->getAsRecordType()) 1328 Tag = RecordT; 1329 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) 1330 return Diag(ArgLoc, diag::err_template_arg_local_type) 1331 << QualType(Tag, 0); 1332 else if (Tag && !Tag->getDecl()->getDeclName() && 1333 !Tag->getDecl()->getTypedefForAnonDecl()) { 1334 Diag(ArgLoc, diag::err_template_arg_unnamed_type); 1335 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here); 1336 return true; 1337 } 1338 1339 return false; 1340} 1341 1342/// \brief Checks whether the given template argument is the address 1343/// of an object or function according to C++ [temp.arg.nontype]p1. 1344bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg, 1345 NamedDecl *&Entity) { 1346 bool Invalid = false; 1347 1348 // See through any implicit casts we added to fix the type. 1349 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 1350 Arg = Cast->getSubExpr(); 1351 1352 // C++0x allows nullptr, and there's no further checking to be done for that. 1353 if (Arg->getType()->isNullPtrType()) 1354 return false; 1355 1356 // C++ [temp.arg.nontype]p1: 1357 // 1358 // A template-argument for a non-type, non-template 1359 // template-parameter shall be one of: [...] 1360 // 1361 // -- the address of an object or function with external 1362 // linkage, including function templates and function 1363 // template-ids but excluding non-static class members, 1364 // expressed as & id-expression where the & is optional if 1365 // the name refers to a function or array, or if the 1366 // corresponding template-parameter is a reference; or 1367 DeclRefExpr *DRE = 0; 1368 1369 // Ignore (and complain about) any excess parentheses. 1370 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 1371 if (!Invalid) { 1372 Diag(Arg->getSourceRange().getBegin(), 1373 diag::err_template_arg_extra_parens) 1374 << Arg->getSourceRange(); 1375 Invalid = true; 1376 } 1377 1378 Arg = Parens->getSubExpr(); 1379 } 1380 1381 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 1382 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 1383 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 1384 } else 1385 DRE = dyn_cast<DeclRefExpr>(Arg); 1386 1387 if (!DRE || !isa<ValueDecl>(DRE->getDecl())) 1388 return Diag(Arg->getSourceRange().getBegin(), 1389 diag::err_template_arg_not_object_or_func_form) 1390 << Arg->getSourceRange(); 1391 1392 // Cannot refer to non-static data members 1393 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) 1394 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field) 1395 << Field << Arg->getSourceRange(); 1396 1397 // Cannot refer to non-static member functions 1398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl())) 1399 if (!Method->isStatic()) 1400 return Diag(Arg->getSourceRange().getBegin(), 1401 diag::err_template_arg_method) 1402 << Method << Arg->getSourceRange(); 1403 1404 // Functions must have external linkage. 1405 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) { 1406 if (Func->getStorageClass() == FunctionDecl::Static) { 1407 Diag(Arg->getSourceRange().getBegin(), 1408 diag::err_template_arg_function_not_extern) 1409 << Func << Arg->getSourceRange(); 1410 Diag(Func->getLocation(), diag::note_template_arg_internal_object) 1411 << true; 1412 return true; 1413 } 1414 1415 // Okay: we've named a function with external linkage. 1416 Entity = Func; 1417 return Invalid; 1418 } 1419 1420 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 1421 if (!Var->hasGlobalStorage()) { 1422 Diag(Arg->getSourceRange().getBegin(), 1423 diag::err_template_arg_object_not_extern) 1424 << Var << Arg->getSourceRange(); 1425 Diag(Var->getLocation(), diag::note_template_arg_internal_object) 1426 << true; 1427 return true; 1428 } 1429 1430 // Okay: we've named an object with external linkage 1431 Entity = Var; 1432 return Invalid; 1433 } 1434 1435 // We found something else, but we don't know specifically what it is. 1436 Diag(Arg->getSourceRange().getBegin(), 1437 diag::err_template_arg_not_object_or_func) 1438 << Arg->getSourceRange(); 1439 Diag(DRE->getDecl()->getLocation(), 1440 diag::note_template_arg_refers_here); 1441 return true; 1442} 1443 1444/// \brief Checks whether the given template argument is a pointer to 1445/// member constant according to C++ [temp.arg.nontype]p1. 1446bool 1447Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) { 1448 bool Invalid = false; 1449 1450 // See through any implicit casts we added to fix the type. 1451 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 1452 Arg = Cast->getSubExpr(); 1453 1454 // C++0x allows nullptr, and there's no further checking to be done for that. 1455 if (Arg->getType()->isNullPtrType()) 1456 return false; 1457 1458 // C++ [temp.arg.nontype]p1: 1459 // 1460 // A template-argument for a non-type, non-template 1461 // template-parameter shall be one of: [...] 1462 // 1463 // -- a pointer to member expressed as described in 5.3.1. 1464 QualifiedDeclRefExpr *DRE = 0; 1465 1466 // Ignore (and complain about) any excess parentheses. 1467 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 1468 if (!Invalid) { 1469 Diag(Arg->getSourceRange().getBegin(), 1470 diag::err_template_arg_extra_parens) 1471 << Arg->getSourceRange(); 1472 Invalid = true; 1473 } 1474 1475 Arg = Parens->getSubExpr(); 1476 } 1477 1478 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) 1479 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 1480 DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr()); 1481 1482 if (!DRE) 1483 return Diag(Arg->getSourceRange().getBegin(), 1484 diag::err_template_arg_not_pointer_to_member_form) 1485 << Arg->getSourceRange(); 1486 1487 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) { 1488 assert((isa<FieldDecl>(DRE->getDecl()) || 1489 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && 1490 "Only non-static member pointers can make it here"); 1491 1492 // Okay: this is the address of a non-static member, and therefore 1493 // a member pointer constant. 1494 Member = DRE->getDecl(); 1495 return Invalid; 1496 } 1497 1498 // We found something else, but we don't know specifically what it is. 1499 Diag(Arg->getSourceRange().getBegin(), 1500 diag::err_template_arg_not_pointer_to_member_form) 1501 << Arg->getSourceRange(); 1502 Diag(DRE->getDecl()->getLocation(), 1503 diag::note_template_arg_refers_here); 1504 return true; 1505} 1506 1507/// \brief Check a template argument against its corresponding 1508/// non-type template parameter. 1509/// 1510/// This routine implements the semantics of C++ [temp.arg.nontype]. 1511/// It returns true if an error occurred, and false otherwise. \p 1512/// InstantiatedParamType is the type of the non-type template 1513/// parameter after it has been instantiated. 1514/// 1515/// If no error was detected, Converted receives the converted template argument. 1516bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 1517 QualType InstantiatedParamType, Expr *&Arg, 1518 TemplateArgument &Converted) { 1519 SourceLocation StartLoc = Arg->getSourceRange().getBegin(); 1520 1521 // If either the parameter has a dependent type or the argument is 1522 // type-dependent, there's nothing we can check now. 1523 // FIXME: Add template argument to Converted! 1524 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) { 1525 // FIXME: Produce a cloned, canonical expression? 1526 Converted = TemplateArgument(Arg); 1527 return false; 1528 } 1529 1530 // C++ [temp.arg.nontype]p5: 1531 // The following conversions are performed on each expression used 1532 // as a non-type template-argument. If a non-type 1533 // template-argument cannot be converted to the type of the 1534 // corresponding template-parameter then the program is 1535 // ill-formed. 1536 // 1537 // -- for a non-type template-parameter of integral or 1538 // enumeration type, integral promotions (4.5) and integral 1539 // conversions (4.7) are applied. 1540 QualType ParamType = InstantiatedParamType; 1541 QualType ArgType = Arg->getType(); 1542 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) { 1543 // C++ [temp.arg.nontype]p1: 1544 // A template-argument for a non-type, non-template 1545 // template-parameter shall be one of: 1546 // 1547 // -- an integral constant-expression of integral or enumeration 1548 // type; or 1549 // -- the name of a non-type template-parameter; or 1550 SourceLocation NonConstantLoc; 1551 llvm::APSInt Value; 1552 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) { 1553 Diag(Arg->getSourceRange().getBegin(), 1554 diag::err_template_arg_not_integral_or_enumeral) 1555 << ArgType << Arg->getSourceRange(); 1556 Diag(Param->getLocation(), diag::note_template_param_here); 1557 return true; 1558 } else if (!Arg->isValueDependent() && 1559 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) { 1560 Diag(NonConstantLoc, diag::err_template_arg_not_ice) 1561 << ArgType << Arg->getSourceRange(); 1562 return true; 1563 } 1564 1565 // FIXME: We need some way to more easily get the unqualified form 1566 // of the types without going all the way to the 1567 // canonical type. 1568 if (Context.getCanonicalType(ParamType).getCVRQualifiers()) 1569 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType(); 1570 if (Context.getCanonicalType(ArgType).getCVRQualifiers()) 1571 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType(); 1572 1573 // Try to convert the argument to the parameter's type. 1574 if (ParamType == ArgType) { 1575 // Okay: no conversion necessary 1576 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 1577 !ParamType->isEnumeralType()) { 1578 // This is an integral promotion or conversion. 1579 ImpCastExprToType(Arg, ParamType); 1580 } else { 1581 // We can't perform this conversion. 1582 Diag(Arg->getSourceRange().getBegin(), 1583 diag::err_template_arg_not_convertible) 1584 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 1585 Diag(Param->getLocation(), diag::note_template_param_here); 1586 return true; 1587 } 1588 1589 QualType IntegerType = Context.getCanonicalType(ParamType); 1590 if (const EnumType *Enum = IntegerType->getAsEnumType()) 1591 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); 1592 1593 if (!Arg->isValueDependent()) { 1594 // Check that an unsigned parameter does not receive a negative 1595 // value. 1596 if (IntegerType->isUnsignedIntegerType() 1597 && (Value.isSigned() && Value.isNegative())) { 1598 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative) 1599 << Value.toString(10) << Param->getType() 1600 << Arg->getSourceRange(); 1601 Diag(Param->getLocation(), diag::note_template_param_here); 1602 return true; 1603 } 1604 1605 // Check that we don't overflow the template parameter type. 1606 unsigned AllowedBits = Context.getTypeSize(IntegerType); 1607 if (Value.getActiveBits() > AllowedBits) { 1608 Diag(Arg->getSourceRange().getBegin(), 1609 diag::err_template_arg_too_large) 1610 << Value.toString(10) << Param->getType() 1611 << Arg->getSourceRange(); 1612 Diag(Param->getLocation(), diag::note_template_param_here); 1613 return true; 1614 } 1615 1616 if (Value.getBitWidth() != AllowedBits) 1617 Value.extOrTrunc(AllowedBits); 1618 Value.setIsSigned(IntegerType->isSignedIntegerType()); 1619 } 1620 1621 // Add the value of this argument to the list of converted 1622 // arguments. We use the bitwidth and signedness of the template 1623 // parameter. 1624 if (Arg->isValueDependent()) { 1625 // The argument is value-dependent. Create a new 1626 // TemplateArgument with the converted expression. 1627 Converted = TemplateArgument(Arg); 1628 return false; 1629 } 1630 1631 Converted = TemplateArgument(StartLoc, Value, 1632 ParamType->isEnumeralType() ? ParamType 1633 : IntegerType); 1634 return false; 1635 } 1636 1637 // Handle pointer-to-function, reference-to-function, and 1638 // pointer-to-member-function all in (roughly) the same way. 1639 if (// -- For a non-type template-parameter of type pointer to 1640 // function, only the function-to-pointer conversion (4.3) is 1641 // applied. If the template-argument represents a set of 1642 // overloaded functions (or a pointer to such), the matching 1643 // function is selected from the set (13.4). 1644 // In C++0x, any std::nullptr_t value can be converted. 1645 (ParamType->isPointerType() && 1646 ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) || 1647 // -- For a non-type template-parameter of type reference to 1648 // function, no conversions apply. If the template-argument 1649 // represents a set of overloaded functions, the matching 1650 // function is selected from the set (13.4). 1651 (ParamType->isReferenceType() && 1652 ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) || 1653 // -- For a non-type template-parameter of type pointer to 1654 // member function, no conversions apply. If the 1655 // template-argument represents a set of overloaded member 1656 // functions, the matching member function is selected from 1657 // the set (13.4). 1658 // Again, C++0x allows a std::nullptr_t value. 1659 (ParamType->isMemberPointerType() && 1660 ParamType->getAsMemberPointerType()->getPointeeType() 1661 ->isFunctionType())) { 1662 if (Context.hasSameUnqualifiedType(ArgType, 1663 ParamType.getNonReferenceType())) { 1664 // We don't have to do anything: the types already match. 1665 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() || 1666 ParamType->isMemberPointerType())) { 1667 ArgType = ParamType; 1668 ImpCastExprToType(Arg, ParamType); 1669 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) { 1670 ArgType = Context.getPointerType(ArgType); 1671 ImpCastExprToType(Arg, ArgType); 1672 } else if (FunctionDecl *Fn 1673 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) { 1674 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 1675 return true; 1676 1677 FixOverloadedFunctionReference(Arg, Fn); 1678 ArgType = Arg->getType(); 1679 if (ArgType->isFunctionType() && ParamType->isPointerType()) { 1680 ArgType = Context.getPointerType(Arg->getType()); 1681 ImpCastExprToType(Arg, ArgType); 1682 } 1683 } 1684 1685 if (!Context.hasSameUnqualifiedType(ArgType, 1686 ParamType.getNonReferenceType())) { 1687 // We can't perform this conversion. 1688 Diag(Arg->getSourceRange().getBegin(), 1689 diag::err_template_arg_not_convertible) 1690 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 1691 Diag(Param->getLocation(), diag::note_template_param_here); 1692 return true; 1693 } 1694 1695 if (ParamType->isMemberPointerType()) { 1696 NamedDecl *Member = 0; 1697 if (CheckTemplateArgumentPointerToMember(Arg, Member)) 1698 return true; 1699 1700 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member)); 1701 Converted = TemplateArgument(StartLoc, Member); 1702 return false; 1703 } 1704 1705 NamedDecl *Entity = 0; 1706 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 1707 return true; 1708 1709 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity)); 1710 Converted = TemplateArgument(StartLoc, Entity); 1711 return false; 1712 } 1713 1714 if (ParamType->isPointerType()) { 1715 // -- for a non-type template-parameter of type pointer to 1716 // object, qualification conversions (4.4) and the 1717 // array-to-pointer conversion (4.2) are applied. 1718 // C++0x also allows a value of std::nullptr_t. 1719 assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() && 1720 "Only object pointers allowed here"); 1721 1722 if (ArgType->isNullPtrType()) { 1723 ArgType = ParamType; 1724 ImpCastExprToType(Arg, ParamType); 1725 } else if (ArgType->isArrayType()) { 1726 ArgType = Context.getArrayDecayedType(ArgType); 1727 ImpCastExprToType(Arg, ArgType); 1728 } 1729 1730 if (IsQualificationConversion(ArgType, ParamType)) { 1731 ArgType = ParamType; 1732 ImpCastExprToType(Arg, ParamType); 1733 } 1734 1735 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) { 1736 // We can't perform this conversion. 1737 Diag(Arg->getSourceRange().getBegin(), 1738 diag::err_template_arg_not_convertible) 1739 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 1740 Diag(Param->getLocation(), diag::note_template_param_here); 1741 return true; 1742 } 1743 1744 NamedDecl *Entity = 0; 1745 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 1746 return true; 1747 1748 Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity)); 1749 Converted = TemplateArgument(StartLoc, Entity); 1750 return false; 1751 } 1752 1753 if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) { 1754 // -- For a non-type template-parameter of type reference to 1755 // object, no conversions apply. The type referred to by the 1756 // reference may be more cv-qualified than the (otherwise 1757 // identical) type of the template-argument. The 1758 // template-parameter is bound directly to the 1759 // template-argument, which must be an lvalue. 1760 assert(ParamRefType->getPointeeType()->isObjectType() && 1761 "Only object references allowed here"); 1762 1763 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) { 1764 Diag(Arg->getSourceRange().getBegin(), 1765 diag::err_template_arg_no_ref_bind) 1766 << InstantiatedParamType << Arg->getType() 1767 << Arg->getSourceRange(); 1768 Diag(Param->getLocation(), diag::note_template_param_here); 1769 return true; 1770 } 1771 1772 unsigned ParamQuals 1773 = Context.getCanonicalType(ParamType).getCVRQualifiers(); 1774 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers(); 1775 1776 if ((ParamQuals | ArgQuals) != ParamQuals) { 1777 Diag(Arg->getSourceRange().getBegin(), 1778 diag::err_template_arg_ref_bind_ignores_quals) 1779 << InstantiatedParamType << Arg->getType() 1780 << Arg->getSourceRange(); 1781 Diag(Param->getLocation(), diag::note_template_param_here); 1782 return true; 1783 } 1784 1785 NamedDecl *Entity = 0; 1786 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 1787 return true; 1788 1789 Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity)); 1790 Converted = TemplateArgument(StartLoc, Entity); 1791 return false; 1792 } 1793 1794 // -- For a non-type template-parameter of type pointer to data 1795 // member, qualification conversions (4.4) are applied. 1796 // C++0x allows std::nullptr_t values. 1797 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 1798 1799 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) { 1800 // Types match exactly: nothing more to do here. 1801 } else if (ArgType->isNullPtrType()) { 1802 ImpCastExprToType(Arg, ParamType); 1803 } else if (IsQualificationConversion(ArgType, ParamType)) { 1804 ImpCastExprToType(Arg, ParamType); 1805 } else { 1806 // We can't perform this conversion. 1807 Diag(Arg->getSourceRange().getBegin(), 1808 diag::err_template_arg_not_convertible) 1809 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 1810 Diag(Param->getLocation(), diag::note_template_param_here); 1811 return true; 1812 } 1813 1814 NamedDecl *Member = 0; 1815 if (CheckTemplateArgumentPointerToMember(Arg, Member)) 1816 return true; 1817 1818 Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member)); 1819 Converted = TemplateArgument(StartLoc, Member); 1820 return false; 1821} 1822 1823/// \brief Check a template argument against its corresponding 1824/// template template parameter. 1825/// 1826/// This routine implements the semantics of C++ [temp.arg.template]. 1827/// It returns true if an error occurred, and false otherwise. 1828bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, 1829 DeclRefExpr *Arg) { 1830 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed"); 1831 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl()); 1832 1833 // C++ [temp.arg.template]p1: 1834 // A template-argument for a template template-parameter shall be 1835 // the name of a class template, expressed as id-expression. Only 1836 // primary class templates are considered when matching the 1837 // template template argument with the corresponding parameter; 1838 // partial specializations are not considered even if their 1839 // parameter lists match that of the template template parameter. 1840 // 1841 // Note that we also allow template template parameters here, which 1842 // will happen when we are dealing with, e.g., class template 1843 // partial specializations. 1844 if (!isa<ClassTemplateDecl>(Template) && 1845 !isa<TemplateTemplateParmDecl>(Template)) { 1846 assert(isa<FunctionTemplateDecl>(Template) && 1847 "Only function templates are possible here"); 1848 Diag(Arg->getLocStart(), diag::err_template_arg_not_class_template); 1849 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 1850 << Template; 1851 } 1852 1853 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 1854 Param->getTemplateParameters(), 1855 true, true, 1856 Arg->getSourceRange().getBegin()); 1857} 1858 1859/// \brief Determine whether the given template parameter lists are 1860/// equivalent. 1861/// 1862/// \param New The new template parameter list, typically written in the 1863/// source code as part of a new template declaration. 1864/// 1865/// \param Old The old template parameter list, typically found via 1866/// name lookup of the template declared with this template parameter 1867/// list. 1868/// 1869/// \param Complain If true, this routine will produce a diagnostic if 1870/// the template parameter lists are not equivalent. 1871/// 1872/// \param IsTemplateTemplateParm If true, this routine is being 1873/// called to compare the template parameter lists of a template 1874/// template parameter. 1875/// 1876/// \param TemplateArgLoc If this source location is valid, then we 1877/// are actually checking the template parameter list of a template 1878/// argument (New) against the template parameter list of its 1879/// corresponding template template parameter (Old). We produce 1880/// slightly different diagnostics in this scenario. 1881/// 1882/// \returns True if the template parameter lists are equal, false 1883/// otherwise. 1884bool 1885Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 1886 TemplateParameterList *Old, 1887 bool Complain, 1888 bool IsTemplateTemplateParm, 1889 SourceLocation TemplateArgLoc) { 1890 if (Old->size() != New->size()) { 1891 if (Complain) { 1892 unsigned NextDiag = diag::err_template_param_list_different_arity; 1893 if (TemplateArgLoc.isValid()) { 1894 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 1895 NextDiag = diag::note_template_param_list_different_arity; 1896 } 1897 Diag(New->getTemplateLoc(), NextDiag) 1898 << (New->size() > Old->size()) 1899 << IsTemplateTemplateParm 1900 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 1901 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 1902 << IsTemplateTemplateParm 1903 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 1904 } 1905 1906 return false; 1907 } 1908 1909 for (TemplateParameterList::iterator OldParm = Old->begin(), 1910 OldParmEnd = Old->end(), NewParm = New->begin(); 1911 OldParm != OldParmEnd; ++OldParm, ++NewParm) { 1912 if ((*OldParm)->getKind() != (*NewParm)->getKind()) { 1913 if (Complain) { 1914 unsigned NextDiag = diag::err_template_param_different_kind; 1915 if (TemplateArgLoc.isValid()) { 1916 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 1917 NextDiag = diag::note_template_param_different_kind; 1918 } 1919 Diag((*NewParm)->getLocation(), NextDiag) 1920 << IsTemplateTemplateParm; 1921 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration) 1922 << IsTemplateTemplateParm; 1923 } 1924 return false; 1925 } 1926 1927 if (isa<TemplateTypeParmDecl>(*OldParm)) { 1928 // Okay; all template type parameters are equivalent (since we 1929 // know we're at the same index). 1930#if 0 1931 // FIXME: Enable this code in debug mode *after* we properly go through 1932 // and "instantiate" the template parameter lists of template template 1933 // parameters. It's only after this instantiation that (1) any dependent 1934 // types within the template parameter list of the template template 1935 // parameter can be checked, and (2) the template type parameter depths 1936 // will match up. 1937 QualType OldParmType 1938 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm)); 1939 QualType NewParmType 1940 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm)); 1941 assert(Context.getCanonicalType(OldParmType) == 1942 Context.getCanonicalType(NewParmType) && 1943 "type parameter mismatch?"); 1944#endif 1945 } else if (NonTypeTemplateParmDecl *OldNTTP 1946 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) { 1947 // The types of non-type template parameters must agree. 1948 NonTypeTemplateParmDecl *NewNTTP 1949 = cast<NonTypeTemplateParmDecl>(*NewParm); 1950 if (Context.getCanonicalType(OldNTTP->getType()) != 1951 Context.getCanonicalType(NewNTTP->getType())) { 1952 if (Complain) { 1953 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 1954 if (TemplateArgLoc.isValid()) { 1955 Diag(TemplateArgLoc, 1956 diag::err_template_arg_template_params_mismatch); 1957 NextDiag = diag::note_template_nontype_parm_different_type; 1958 } 1959 Diag(NewNTTP->getLocation(), NextDiag) 1960 << NewNTTP->getType() 1961 << IsTemplateTemplateParm; 1962 Diag(OldNTTP->getLocation(), 1963 diag::note_template_nontype_parm_prev_declaration) 1964 << OldNTTP->getType(); 1965 } 1966 return false; 1967 } 1968 } else { 1969 // The template parameter lists of template template 1970 // parameters must agree. 1971 // FIXME: Could we perform a faster "type" comparison here? 1972 assert(isa<TemplateTemplateParmDecl>(*OldParm) && 1973 "Only template template parameters handled here"); 1974 TemplateTemplateParmDecl *OldTTP 1975 = cast<TemplateTemplateParmDecl>(*OldParm); 1976 TemplateTemplateParmDecl *NewTTP 1977 = cast<TemplateTemplateParmDecl>(*NewParm); 1978 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 1979 OldTTP->getTemplateParameters(), 1980 Complain, 1981 /*IsTemplateTemplateParm=*/true, 1982 TemplateArgLoc)) 1983 return false; 1984 } 1985 } 1986 1987 return true; 1988} 1989 1990/// \brief Check whether a template can be declared within this scope. 1991/// 1992/// If the template declaration is valid in this scope, returns 1993/// false. Otherwise, issues a diagnostic and returns true. 1994bool 1995Sema::CheckTemplateDeclScope(Scope *S, 1996 MultiTemplateParamsArg &TemplateParameterLists) { 1997 assert(TemplateParameterLists.size() > 0 && "Not a template"); 1998 1999 // Find the nearest enclosing declaration scope. 2000 while ((S->getFlags() & Scope::DeclScope) == 0 || 2001 (S->getFlags() & Scope::TemplateParamScope) != 0) 2002 S = S->getParent(); 2003 2004 TemplateParameterList *TemplateParams = 2005 static_cast<TemplateParameterList*>(*TemplateParameterLists.get()); 2006 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc(); 2007 SourceRange TemplateRange 2008 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc()); 2009 2010 // C++ [temp]p2: 2011 // A template-declaration can appear only as a namespace scope or 2012 // class scope declaration. 2013 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 2014 while (Ctx && isa<LinkageSpecDecl>(Ctx)) { 2015 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx) 2016 return Diag(TemplateLoc, diag::err_template_linkage) 2017 << TemplateRange; 2018 2019 Ctx = Ctx->getParent(); 2020 } 2021 2022 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord())) 2023 return false; 2024 2025 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope) 2026 << TemplateRange; 2027} 2028 2029/// \brief Check whether a class template specialization or explicit 2030/// instantiation in the current context is well-formed. 2031/// 2032/// This routine determines whether a class template specialization or 2033/// explicit instantiation can be declared in the current context 2034/// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits 2035/// appropriate diagnostics if there was an error. It returns true if 2036// there was an error that we cannot recover from, and false otherwise. 2037bool 2038Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate, 2039 ClassTemplateSpecializationDecl *PrevDecl, 2040 SourceLocation TemplateNameLoc, 2041 SourceRange ScopeSpecifierRange, 2042 bool PartialSpecialization, 2043 bool ExplicitInstantiation) { 2044 // C++ [temp.expl.spec]p2: 2045 // An explicit specialization shall be declared in the namespace 2046 // of which the template is a member, or, for member templates, in 2047 // the namespace of which the enclosing class or enclosing class 2048 // template is a member. An explicit specialization of a member 2049 // function, member class or static data member of a class 2050 // template shall be declared in the namespace of which the class 2051 // template is a member. Such a declaration may also be a 2052 // definition. If the declaration is not a definition, the 2053 // specialization may be defined later in the name- space in which 2054 // the explicit specialization was declared, or in a namespace 2055 // that encloses the one in which the explicit specialization was 2056 // declared. 2057 if (CurContext->getLookupContext()->isFunctionOrMethod()) { 2058 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0; 2059 Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope) 2060 << Kind << ClassTemplate; 2061 return true; 2062 } 2063 2064 DeclContext *DC = CurContext->getEnclosingNamespaceContext(); 2065 DeclContext *TemplateContext 2066 = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext(); 2067 if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) && 2068 !ExplicitInstantiation) { 2069 // There is no prior declaration of this entity, so this 2070 // specialization must be in the same context as the template 2071 // itself. 2072 if (DC != TemplateContext) { 2073 if (isa<TranslationUnitDecl>(TemplateContext)) 2074 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global) 2075 << PartialSpecialization 2076 << ClassTemplate << ScopeSpecifierRange; 2077 else if (isa<NamespaceDecl>(TemplateContext)) 2078 Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope) 2079 << PartialSpecialization << ClassTemplate 2080 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange; 2081 2082 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here); 2083 } 2084 2085 return false; 2086 } 2087 2088 // We have a previous declaration of this entity. Make sure that 2089 // this redeclaration (or definition) occurs in an enclosing namespace. 2090 if (!CurContext->Encloses(TemplateContext)) { 2091 // FIXME: In C++98, we would like to turn these errors into warnings, 2092 // dependent on a -Wc++0x flag. 2093 bool SuppressedDiag = false; 2094 int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0; 2095 if (isa<TranslationUnitDecl>(TemplateContext)) { 2096 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x) 2097 Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope) 2098 << Kind << ClassTemplate << ScopeSpecifierRange; 2099 else 2100 SuppressedDiag = true; 2101 } else if (isa<NamespaceDecl>(TemplateContext)) { 2102 if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x) 2103 Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope) 2104 << Kind << ClassTemplate 2105 << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange; 2106 else 2107 SuppressedDiag = true; 2108 } 2109 2110 if (!SuppressedDiag) 2111 Diag(ClassTemplate->getLocation(), diag::note_template_decl_here); 2112 } 2113 2114 return false; 2115} 2116 2117/// \brief Check the non-type template arguments of a class template 2118/// partial specialization according to C++ [temp.class.spec]p9. 2119/// 2120/// \param TemplateParams the template parameters of the primary class 2121/// template. 2122/// 2123/// \param TemplateArg the template arguments of the class template 2124/// partial specialization. 2125/// 2126/// \param MirrorsPrimaryTemplate will be set true if the class 2127/// template partial specialization arguments are identical to the 2128/// implicit template arguments of the primary template. This is not 2129/// necessarily an error (C++0x), and it is left to the caller to diagnose 2130/// this condition when it is an error. 2131/// 2132/// \returns true if there was an error, false otherwise. 2133bool Sema::CheckClassTemplatePartialSpecializationArgs( 2134 TemplateParameterList *TemplateParams, 2135 const TemplateArgumentListBuilder &TemplateArgs, 2136 bool &MirrorsPrimaryTemplate) { 2137 // FIXME: the interface to this function will have to change to 2138 // accommodate variadic templates. 2139 MirrorsPrimaryTemplate = true; 2140 2141 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments(); 2142 2143 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 2144 // Determine whether the template argument list of the partial 2145 // specialization is identical to the implicit argument list of 2146 // the primary template. The caller may need to diagnostic this as 2147 // an error per C++ [temp.class.spec]p9b3. 2148 if (MirrorsPrimaryTemplate) { 2149 if (TemplateTypeParmDecl *TTP 2150 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) { 2151 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) != 2152 Context.getCanonicalType(ArgList[I].getAsType())) 2153 MirrorsPrimaryTemplate = false; 2154 } else if (TemplateTemplateParmDecl *TTP 2155 = dyn_cast<TemplateTemplateParmDecl>( 2156 TemplateParams->getParam(I))) { 2157 // FIXME: We should settle on either Declaration storage or 2158 // Expression storage for template template parameters. 2159 TemplateTemplateParmDecl *ArgDecl 2160 = dyn_cast_or_null<TemplateTemplateParmDecl>( 2161 ArgList[I].getAsDecl()); 2162 if (!ArgDecl) 2163 if (DeclRefExpr *DRE 2164 = dyn_cast_or_null<DeclRefExpr>(ArgList[I].getAsExpr())) 2165 ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl()); 2166 2167 if (!ArgDecl || 2168 ArgDecl->getIndex() != TTP->getIndex() || 2169 ArgDecl->getDepth() != TTP->getDepth()) 2170 MirrorsPrimaryTemplate = false; 2171 } 2172 } 2173 2174 NonTypeTemplateParmDecl *Param 2175 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 2176 if (!Param) { 2177 continue; 2178 } 2179 2180 Expr *ArgExpr = ArgList[I].getAsExpr(); 2181 if (!ArgExpr) { 2182 MirrorsPrimaryTemplate = false; 2183 continue; 2184 } 2185 2186 // C++ [temp.class.spec]p8: 2187 // A non-type argument is non-specialized if it is the name of a 2188 // non-type parameter. All other non-type arguments are 2189 // specialized. 2190 // 2191 // Below, we check the two conditions that only apply to 2192 // specialized non-type arguments, so skip any non-specialized 2193 // arguments. 2194 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 2195 if (NonTypeTemplateParmDecl *NTTP 2196 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) { 2197 if (MirrorsPrimaryTemplate && 2198 (Param->getIndex() != NTTP->getIndex() || 2199 Param->getDepth() != NTTP->getDepth())) 2200 MirrorsPrimaryTemplate = false; 2201 2202 continue; 2203 } 2204 2205 // C++ [temp.class.spec]p9: 2206 // Within the argument list of a class template partial 2207 // specialization, the following restrictions apply: 2208 // -- A partially specialized non-type argument expression 2209 // shall not involve a template parameter of the partial 2210 // specialization except when the argument expression is a 2211 // simple identifier. 2212 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) { 2213 Diag(ArgExpr->getLocStart(), 2214 diag::err_dependent_non_type_arg_in_partial_spec) 2215 << ArgExpr->getSourceRange(); 2216 return true; 2217 } 2218 2219 // -- The type of a template parameter corresponding to a 2220 // specialized non-type argument shall not be dependent on a 2221 // parameter of the specialization. 2222 if (Param->getType()->isDependentType()) { 2223 Diag(ArgExpr->getLocStart(), 2224 diag::err_dependent_typed_non_type_arg_in_partial_spec) 2225 << Param->getType() 2226 << ArgExpr->getSourceRange(); 2227 Diag(Param->getLocation(), diag::note_template_param_here); 2228 return true; 2229 } 2230 2231 MirrorsPrimaryTemplate = false; 2232 } 2233 2234 return false; 2235} 2236 2237Sema::DeclResult 2238Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK, 2239 SourceLocation KWLoc, 2240 const CXXScopeSpec &SS, 2241 TemplateTy TemplateD, 2242 SourceLocation TemplateNameLoc, 2243 SourceLocation LAngleLoc, 2244 ASTTemplateArgsPtr TemplateArgsIn, 2245 SourceLocation *TemplateArgLocs, 2246 SourceLocation RAngleLoc, 2247 AttributeList *Attr, 2248 MultiTemplateParamsArg TemplateParameterLists) { 2249 // Find the class template we're specializing 2250 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 2251 ClassTemplateDecl *ClassTemplate 2252 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); 2253 2254 bool isPartialSpecialization = false; 2255 2256 // Check the validity of the template headers that introduce this 2257 // template. 2258 // FIXME: Once we have member templates, we'll need to check 2259 // C++ [temp.expl.spec]p17-18, where we could have multiple levels of 2260 // template<> headers. 2261 if (TemplateParameterLists.size() == 0) 2262 Diag(KWLoc, diag::err_template_spec_needs_header) 2263 << CodeModificationHint::CreateInsertion(KWLoc, "template<> "); 2264 else { 2265 TemplateParameterList *TemplateParams 2266 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get()); 2267 if (TemplateParameterLists.size() > 1) { 2268 Diag(TemplateParams->getTemplateLoc(), 2269 diag::err_template_spec_extra_headers); 2270 return true; 2271 } 2272 2273 if (TemplateParams->size() > 0) { 2274 isPartialSpecialization = true; 2275 2276 // C++ [temp.class.spec]p10: 2277 // The template parameter list of a specialization shall not 2278 // contain default template argument values. 2279 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 2280 Decl *Param = TemplateParams->getParam(I); 2281 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 2282 if (TTP->hasDefaultArgument()) { 2283 Diag(TTP->getDefaultArgumentLoc(), 2284 diag::err_default_arg_in_partial_spec); 2285 TTP->setDefaultArgument(QualType(), SourceLocation(), false); 2286 } 2287 } else if (NonTypeTemplateParmDecl *NTTP 2288 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2289 if (Expr *DefArg = NTTP->getDefaultArgument()) { 2290 Diag(NTTP->getDefaultArgumentLoc(), 2291 diag::err_default_arg_in_partial_spec) 2292 << DefArg->getSourceRange(); 2293 NTTP->setDefaultArgument(0); 2294 DefArg->Destroy(Context); 2295 } 2296 } else { 2297 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 2298 if (Expr *DefArg = TTP->getDefaultArgument()) { 2299 Diag(TTP->getDefaultArgumentLoc(), 2300 diag::err_default_arg_in_partial_spec) 2301 << DefArg->getSourceRange(); 2302 TTP->setDefaultArgument(0); 2303 DefArg->Destroy(Context); 2304 } 2305 } 2306 } 2307 } 2308 } 2309 2310 // Check that the specialization uses the same tag kind as the 2311 // original template. 2312 TagDecl::TagKind Kind; 2313 switch (TagSpec) { 2314 default: assert(0 && "Unknown tag type!"); 2315 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 2316 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 2317 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 2318 } 2319 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 2320 Kind, KWLoc, 2321 *ClassTemplate->getIdentifier())) { 2322 Diag(KWLoc, diag::err_use_with_wrong_tag) 2323 << ClassTemplate 2324 << CodeModificationHint::CreateReplacement(KWLoc, 2325 ClassTemplate->getTemplatedDecl()->getKindName()); 2326 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 2327 diag::note_previous_use); 2328 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 2329 } 2330 2331 // Translate the parser's template argument list in our AST format. 2332 llvm::SmallVector<TemplateArgument, 16> TemplateArgs; 2333 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs); 2334 2335 // Check that the template argument list is well-formed for this 2336 // template. 2337 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 2338 TemplateArgs.size()); 2339 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc, 2340 TemplateArgs.data(), TemplateArgs.size(), 2341 RAngleLoc, Converted)) 2342 return true; 2343 2344 assert((Converted.structuredSize() == 2345 ClassTemplate->getTemplateParameters()->size()) && 2346 "Converted template argument list is too short!"); 2347 2348 // Find the class template (partial) specialization declaration that 2349 // corresponds to these arguments. 2350 llvm::FoldingSetNodeID ID; 2351 if (isPartialSpecialization) { 2352 bool MirrorsPrimaryTemplate; 2353 if (CheckClassTemplatePartialSpecializationArgs( 2354 ClassTemplate->getTemplateParameters(), 2355 Converted, MirrorsPrimaryTemplate)) 2356 return true; 2357 2358 if (MirrorsPrimaryTemplate) { 2359 // C++ [temp.class.spec]p9b3: 2360 // 2361 // -- The argument list of the specialization shall not be identical 2362 // to the implicit argument list of the primary template. 2363 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 2364 << (TK == TK_Definition) 2365 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc, 2366 RAngleLoc)); 2367 return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS, 2368 ClassTemplate->getIdentifier(), 2369 TemplateNameLoc, 2370 Attr, 2371 move(TemplateParameterLists), 2372 AS_none); 2373 } 2374 2375 // FIXME: Template parameter list matters, too 2376 ClassTemplatePartialSpecializationDecl::Profile(ID, 2377 Converted.getFlatArguments(), 2378 Converted.flatSize()); 2379 } 2380 else 2381 ClassTemplateSpecializationDecl::Profile(ID, 2382 Converted.getFlatArguments(), 2383 Converted.flatSize()); 2384 void *InsertPos = 0; 2385 ClassTemplateSpecializationDecl *PrevDecl = 0; 2386 2387 if (isPartialSpecialization) 2388 PrevDecl 2389 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 2390 InsertPos); 2391 else 2392 PrevDecl 2393 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 2394 2395 ClassTemplateSpecializationDecl *Specialization = 0; 2396 2397 // Check whether we can declare a class template specialization in 2398 // the current scope. 2399 if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl, 2400 TemplateNameLoc, 2401 SS.getRange(), 2402 isPartialSpecialization, 2403 /*ExplicitInstantiation=*/false)) 2404 return true; 2405 2406 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) { 2407 // Since the only prior class template specialization with these 2408 // arguments was referenced but not declared, reuse that 2409 // declaration node as our own, updating its source location to 2410 // reflect our new declaration. 2411 Specialization = PrevDecl; 2412 Specialization->setLocation(TemplateNameLoc); 2413 PrevDecl = 0; 2414 } else if (isPartialSpecialization) { 2415 // Create a new class template partial specialization declaration node. 2416 TemplateParameterList *TemplateParams 2417 = static_cast<TemplateParameterList*>(*TemplateParameterLists.get()); 2418 ClassTemplatePartialSpecializationDecl *PrevPartial 2419 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 2420 ClassTemplatePartialSpecializationDecl *Partial 2421 = ClassTemplatePartialSpecializationDecl::Create(Context, 2422 ClassTemplate->getDeclContext(), 2423 TemplateNameLoc, 2424 TemplateParams, 2425 ClassTemplate, 2426 Converted, 2427 PrevPartial); 2428 2429 if (PrevPartial) { 2430 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial); 2431 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial); 2432 } else { 2433 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos); 2434 } 2435 Specialization = Partial; 2436 2437 // Check that all of the template parameters of the class template 2438 // partial specialization are deducible from the template 2439 // arguments. If not, this class template partial specialization 2440 // will never be used. 2441 llvm::SmallVector<bool, 8> DeducibleParams; 2442 DeducibleParams.resize(TemplateParams->size()); 2443 MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams); 2444 unsigned NumNonDeducible = 0; 2445 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) 2446 if (!DeducibleParams[I]) 2447 ++NumNonDeducible; 2448 2449 if (NumNonDeducible) { 2450 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible) 2451 << (NumNonDeducible > 1) 2452 << SourceRange(TemplateNameLoc, RAngleLoc); 2453 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 2454 if (!DeducibleParams[I]) { 2455 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I)); 2456 if (Param->getDeclName()) 2457 Diag(Param->getLocation(), 2458 diag::note_partial_spec_unused_parameter) 2459 << Param->getDeclName(); 2460 else 2461 Diag(Param->getLocation(), 2462 diag::note_partial_spec_unused_parameter) 2463 << std::string("<anonymous>"); 2464 } 2465 } 2466 } 2467 2468 } else { 2469 // Create a new class template specialization declaration node for 2470 // this explicit specialization. 2471 Specialization 2472 = ClassTemplateSpecializationDecl::Create(Context, 2473 ClassTemplate->getDeclContext(), 2474 TemplateNameLoc, 2475 ClassTemplate, 2476 Converted, 2477 PrevDecl); 2478 2479 if (PrevDecl) { 2480 ClassTemplate->getSpecializations().RemoveNode(PrevDecl); 2481 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization); 2482 } else { 2483 ClassTemplate->getSpecializations().InsertNode(Specialization, 2484 InsertPos); 2485 } 2486 } 2487 2488 // Note that this is an explicit specialization. 2489 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 2490 2491 // Check that this isn't a redefinition of this specialization. 2492 if (TK == TK_Definition) { 2493 if (RecordDecl *Def = Specialization->getDefinition(Context)) { 2494 // FIXME: Should also handle explicit specialization after implicit 2495 // instantiation with a special diagnostic. 2496 SourceRange Range(TemplateNameLoc, RAngleLoc); 2497 Diag(TemplateNameLoc, diag::err_redefinition) 2498 << Context.getTypeDeclType(Specialization) << Range; 2499 Diag(Def->getLocation(), diag::note_previous_definition); 2500 Specialization->setInvalidDecl(); 2501 return true; 2502 } 2503 } 2504 2505 // Build the fully-sugared type for this class template 2506 // specialization as the user wrote in the specialization 2507 // itself. This means that we'll pretty-print the type retrieved 2508 // from the specialization's declaration the way that the user 2509 // actually wrote the specialization, rather than formatting the 2510 // name based on the "canonical" representation used to store the 2511 // template arguments in the specialization. 2512 QualType WrittenTy 2513 = Context.getTemplateSpecializationType(Name, 2514 TemplateArgs.data(), 2515 TemplateArgs.size(), 2516 Context.getTypeDeclType(Specialization)); 2517 Specialization->setTypeAsWritten(WrittenTy); 2518 TemplateArgsIn.release(); 2519 2520 // C++ [temp.expl.spec]p9: 2521 // A template explicit specialization is in the scope of the 2522 // namespace in which the template was defined. 2523 // 2524 // We actually implement this paragraph where we set the semantic 2525 // context (in the creation of the ClassTemplateSpecializationDecl), 2526 // but we also maintain the lexical context where the actual 2527 // definition occurs. 2528 Specialization->setLexicalDeclContext(CurContext); 2529 2530 // We may be starting the definition of this specialization. 2531 if (TK == TK_Definition) 2532 Specialization->startDefinition(); 2533 2534 // Add the specialization into its lexical context, so that it can 2535 // be seen when iterating through the list of declarations in that 2536 // context. However, specializations are not found by name lookup. 2537 CurContext->addDecl(Specialization); 2538 return DeclPtrTy::make(Specialization); 2539} 2540 2541Sema::DeclPtrTy 2542Sema::ActOnTemplateDeclarator(Scope *S, 2543 MultiTemplateParamsArg TemplateParameterLists, 2544 Declarator &D) { 2545 return HandleDeclarator(S, D, move(TemplateParameterLists), false); 2546} 2547 2548Sema::DeclPtrTy 2549Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 2550 MultiTemplateParamsArg TemplateParameterLists, 2551 Declarator &D) { 2552 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 2553 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 2554 "Not a function declarator!"); 2555 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2556 2557 if (FTI.hasPrototype) { 2558 // FIXME: Diagnose arguments without names in C. 2559 } 2560 2561 Scope *ParentScope = FnBodyScope->getParent(); 2562 2563 DeclPtrTy DP = HandleDeclarator(ParentScope, D, 2564 move(TemplateParameterLists), 2565 /*IsFunctionDefinition=*/true); 2566 FunctionTemplateDecl *FunctionTemplate 2567 = cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()); 2568 if (FunctionTemplate) 2569 return ActOnStartOfFunctionDef(FnBodyScope, 2570 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl())); 2571 2572 return DeclPtrTy(); 2573} 2574 2575// Explicit instantiation of a class template specialization 2576Sema::DeclResult 2577Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc, 2578 unsigned TagSpec, 2579 SourceLocation KWLoc, 2580 const CXXScopeSpec &SS, 2581 TemplateTy TemplateD, 2582 SourceLocation TemplateNameLoc, 2583 SourceLocation LAngleLoc, 2584 ASTTemplateArgsPtr TemplateArgsIn, 2585 SourceLocation *TemplateArgLocs, 2586 SourceLocation RAngleLoc, 2587 AttributeList *Attr) { 2588 // Find the class template we're specializing 2589 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 2590 ClassTemplateDecl *ClassTemplate 2591 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); 2592 2593 // Check that the specialization uses the same tag kind as the 2594 // original template. 2595 TagDecl::TagKind Kind; 2596 switch (TagSpec) { 2597 default: assert(0 && "Unknown tag type!"); 2598 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 2599 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 2600 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 2601 } 2602 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 2603 Kind, KWLoc, 2604 *ClassTemplate->getIdentifier())) { 2605 Diag(KWLoc, diag::err_use_with_wrong_tag) 2606 << ClassTemplate 2607 << CodeModificationHint::CreateReplacement(KWLoc, 2608 ClassTemplate->getTemplatedDecl()->getKindName()); 2609 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 2610 diag::note_previous_use); 2611 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 2612 } 2613 2614 // C++0x [temp.explicit]p2: 2615 // [...] An explicit instantiation shall appear in an enclosing 2616 // namespace of its template. [...] 2617 // 2618 // This is C++ DR 275. 2619 if (CheckClassTemplateSpecializationScope(ClassTemplate, 0, 2620 TemplateNameLoc, 2621 SS.getRange(), 2622 /*PartialSpecialization=*/false, 2623 /*ExplicitInstantiation=*/true)) 2624 return true; 2625 2626 // Translate the parser's template argument list in our AST format. 2627 llvm::SmallVector<TemplateArgument, 16> TemplateArgs; 2628 translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs); 2629 2630 // Check that the template argument list is well-formed for this 2631 // template. 2632 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 2633 TemplateArgs.size()); 2634 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc, 2635 TemplateArgs.data(), TemplateArgs.size(), 2636 RAngleLoc, Converted)) 2637 return true; 2638 2639 assert((Converted.structuredSize() == 2640 ClassTemplate->getTemplateParameters()->size()) && 2641 "Converted template argument list is too short!"); 2642 2643 // Find the class template specialization declaration that 2644 // corresponds to these arguments. 2645 llvm::FoldingSetNodeID ID; 2646 ClassTemplateSpecializationDecl::Profile(ID, 2647 Converted.getFlatArguments(), 2648 Converted.flatSize()); 2649 void *InsertPos = 0; 2650 ClassTemplateSpecializationDecl *PrevDecl 2651 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 2652 2653 ClassTemplateSpecializationDecl *Specialization = 0; 2654 2655 bool SpecializationRequiresInstantiation = true; 2656 if (PrevDecl) { 2657 if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) { 2658 // This particular specialization has already been declared or 2659 // instantiated. We cannot explicitly instantiate it. 2660 Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate) 2661 << Context.getTypeDeclType(PrevDecl); 2662 Diag(PrevDecl->getLocation(), 2663 diag::note_previous_explicit_instantiation); 2664 return DeclPtrTy::make(PrevDecl); 2665 } 2666 2667 if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) { 2668 // C++ DR 259, C++0x [temp.explicit]p4: 2669 // For a given set of template parameters, if an explicit 2670 // instantiation of a template appears after a declaration of 2671 // an explicit specialization for that template, the explicit 2672 // instantiation has no effect. 2673 if (!getLangOptions().CPlusPlus0x) { 2674 Diag(TemplateNameLoc, 2675 diag::ext_explicit_instantiation_after_specialization) 2676 << Context.getTypeDeclType(PrevDecl); 2677 Diag(PrevDecl->getLocation(), 2678 diag::note_previous_template_specialization); 2679 } 2680 2681 // Create a new class template specialization declaration node 2682 // for this explicit specialization. This node is only used to 2683 // record the existence of this explicit instantiation for 2684 // accurate reproduction of the source code; we don't actually 2685 // use it for anything, since it is semantically irrelevant. 2686 Specialization 2687 = ClassTemplateSpecializationDecl::Create(Context, 2688 ClassTemplate->getDeclContext(), 2689 TemplateNameLoc, 2690 ClassTemplate, 2691 Converted, 0); 2692 Specialization->setLexicalDeclContext(CurContext); 2693 CurContext->addDecl(Specialization); 2694 return DeclPtrTy::make(Specialization); 2695 } 2696 2697 // If we have already (implicitly) instantiated this 2698 // specialization, there is less work to do. 2699 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation) 2700 SpecializationRequiresInstantiation = false; 2701 2702 // Since the only prior class template specialization with these 2703 // arguments was referenced but not declared, reuse that 2704 // declaration node as our own, updating its source location to 2705 // reflect our new declaration. 2706 Specialization = PrevDecl; 2707 Specialization->setLocation(TemplateNameLoc); 2708 PrevDecl = 0; 2709 } else { 2710 // Create a new class template specialization declaration node for 2711 // this explicit specialization. 2712 Specialization 2713 = ClassTemplateSpecializationDecl::Create(Context, 2714 ClassTemplate->getDeclContext(), 2715 TemplateNameLoc, 2716 ClassTemplate, 2717 Converted, 0); 2718 2719 ClassTemplate->getSpecializations().InsertNode(Specialization, 2720 InsertPos); 2721 } 2722 2723 // Build the fully-sugared type for this explicit instantiation as 2724 // the user wrote in the explicit instantiation itself. This means 2725 // that we'll pretty-print the type retrieved from the 2726 // specialization's declaration the way that the user actually wrote 2727 // the explicit instantiation, rather than formatting the name based 2728 // on the "canonical" representation used to store the template 2729 // arguments in the specialization. 2730 QualType WrittenTy 2731 = Context.getTemplateSpecializationType(Name, 2732 TemplateArgs.data(), 2733 TemplateArgs.size(), 2734 Context.getTypeDeclType(Specialization)); 2735 Specialization->setTypeAsWritten(WrittenTy); 2736 TemplateArgsIn.release(); 2737 2738 // Add the explicit instantiation into its lexical context. However, 2739 // since explicit instantiations are never found by name lookup, we 2740 // just put it into the declaration context directly. 2741 Specialization->setLexicalDeclContext(CurContext); 2742 CurContext->addDecl(Specialization); 2743 2744 // C++ [temp.explicit]p3: 2745 // A definition of a class template or class member template 2746 // shall be in scope at the point of the explicit instantiation of 2747 // the class template or class member template. 2748 // 2749 // This check comes when we actually try to perform the 2750 // instantiation. 2751 if (SpecializationRequiresInstantiation) 2752 InstantiateClassTemplateSpecialization(Specialization, true); 2753 else // Instantiate the members of this class template specialization. 2754 InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization); 2755 2756 return DeclPtrTy::make(Specialization); 2757} 2758 2759// Explicit instantiation of a member class of a class template. 2760Sema::DeclResult 2761Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc, 2762 unsigned TagSpec, 2763 SourceLocation KWLoc, 2764 const CXXScopeSpec &SS, 2765 IdentifierInfo *Name, 2766 SourceLocation NameLoc, 2767 AttributeList *Attr) { 2768 2769 bool Owned = false; 2770 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference, 2771 KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned); 2772 if (!TagD) 2773 return true; 2774 2775 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 2776 if (Tag->isEnum()) { 2777 Diag(TemplateLoc, diag::err_explicit_instantiation_enum) 2778 << Context.getTypeDeclType(Tag); 2779 return true; 2780 } 2781 2782 if (Tag->isInvalidDecl()) 2783 return true; 2784 2785 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 2786 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 2787 if (!Pattern) { 2788 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 2789 << Context.getTypeDeclType(Record); 2790 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 2791 return true; 2792 } 2793 2794 // C++0x [temp.explicit]p2: 2795 // [...] An explicit instantiation shall appear in an enclosing 2796 // namespace of its template. [...] 2797 // 2798 // This is C++ DR 275. 2799 if (getLangOptions().CPlusPlus0x) { 2800 // FIXME: In C++98, we would like to turn these errors into warnings, 2801 // dependent on a -Wc++0x flag. 2802 DeclContext *PatternContext 2803 = Pattern->getDeclContext()->getEnclosingNamespaceContext(); 2804 if (!CurContext->Encloses(PatternContext)) { 2805 Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope) 2806 << Record << cast<NamedDecl>(PatternContext) << SS.getRange(); 2807 Diag(Pattern->getLocation(), diag::note_previous_declaration); 2808 } 2809 } 2810 2811 if (!Record->getDefinition(Context)) { 2812 // If the class has a definition, instantiate it (and all of its 2813 // members, recursively). 2814 Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context)); 2815 if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern, 2816 getTemplateInstantiationArgs(Record), 2817 /*ExplicitInstantiation=*/true)) 2818 return true; 2819 } else // Instantiate all of the members of class. 2820 InstantiateClassMembers(TemplateLoc, Record, 2821 getTemplateInstantiationArgs(Record)); 2822 2823 // FIXME: We don't have any representation for explicit instantiations of 2824 // member classes. Such a representation is not needed for compilation, but it 2825 // should be available for clients that want to see all of the declarations in 2826 // the source code. 2827 return TagD; 2828} 2829 2830Sema::TypeResult 2831Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, 2832 const IdentifierInfo &II, SourceLocation IdLoc) { 2833 NestedNameSpecifier *NNS 2834 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 2835 if (!NNS) 2836 return true; 2837 2838 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc)); 2839 if (T.isNull()) 2840 return true; 2841 return T.getAsOpaquePtr(); 2842} 2843 2844Sema::TypeResult 2845Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, 2846 SourceLocation TemplateLoc, TypeTy *Ty) { 2847 QualType T = QualType::getFromOpaquePtr(Ty); 2848 NestedNameSpecifier *NNS 2849 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 2850 const TemplateSpecializationType *TemplateId 2851 = T->getAsTemplateSpecializationType(); 2852 assert(TemplateId && "Expected a template specialization type"); 2853 2854 if (NNS->isDependent()) 2855 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr(); 2856 2857 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr(); 2858} 2859 2860/// \brief Build the type that describes a C++ typename specifier, 2861/// e.g., "typename T::type". 2862QualType 2863Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II, 2864 SourceRange Range) { 2865 CXXRecordDecl *CurrentInstantiation = 0; 2866 if (NNS->isDependent()) { 2867 CurrentInstantiation = getCurrentInstantiationOf(NNS); 2868 2869 // If the nested-name-specifier does not refer to the current 2870 // instantiation, then build a typename type. 2871 if (!CurrentInstantiation) 2872 return Context.getTypenameType(NNS, &II); 2873 } 2874 2875 DeclContext *Ctx = 0; 2876 2877 if (CurrentInstantiation) 2878 Ctx = CurrentInstantiation; 2879 else { 2880 CXXScopeSpec SS; 2881 SS.setScopeRep(NNS); 2882 SS.setRange(Range); 2883 if (RequireCompleteDeclContext(SS)) 2884 return QualType(); 2885 2886 Ctx = computeDeclContext(SS); 2887 } 2888 assert(Ctx && "No declaration context?"); 2889 2890 DeclarationName Name(&II); 2891 LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName, 2892 false); 2893 unsigned DiagID = 0; 2894 Decl *Referenced = 0; 2895 switch (Result.getKind()) { 2896 case LookupResult::NotFound: 2897 if (Ctx->isTranslationUnit()) 2898 DiagID = diag::err_typename_nested_not_found_global; 2899 else 2900 DiagID = diag::err_typename_nested_not_found; 2901 break; 2902 2903 case LookupResult::Found: 2904 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) { 2905 // We found a type. Build a QualifiedNameType, since the 2906 // typename-specifier was just sugar. FIXME: Tell 2907 // QualifiedNameType that it has a "typename" prefix. 2908 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type)); 2909 } 2910 2911 DiagID = diag::err_typename_nested_not_type; 2912 Referenced = Result.getAsDecl(); 2913 break; 2914 2915 case LookupResult::FoundOverloaded: 2916 DiagID = diag::err_typename_nested_not_type; 2917 Referenced = *Result.begin(); 2918 break; 2919 2920 case LookupResult::AmbiguousBaseSubobjectTypes: 2921 case LookupResult::AmbiguousBaseSubobjects: 2922 case LookupResult::AmbiguousReference: 2923 DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range); 2924 return QualType(); 2925 } 2926 2927 // If we get here, it's because name lookup did not find a 2928 // type. Emit an appropriate diagnostic and return an error. 2929 if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx)) 2930 Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx; 2931 else 2932 Diag(Range.getEnd(), DiagID) << Range << Name; 2933 if (Referenced) 2934 Diag(Referenced->getLocation(), diag::note_typename_refers_here) 2935 << Name; 2936 return QualType(); 2937} 2938