clang API Documentation
00001 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/ 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 //===----------------------------------------------------------------------===/ 00008 // 00009 // This file implements semantic analysis for C++ templates. 00010 //===----------------------------------------------------------------------===/ 00011 00012 #include "Sema.h" 00013 #include "Lookup.h" 00014 #include "TreeTransform.h" 00015 #include "clang/AST/ASTContext.h" 00016 #include "clang/AST/Expr.h" 00017 #include "clang/AST/ExprCXX.h" 00018 #include "clang/AST/DeclFriend.h" 00019 #include "clang/AST/DeclTemplate.h" 00020 #include "clang/Parse/DeclSpec.h" 00021 #include "clang/Parse/Template.h" 00022 #include "clang/Basic/LangOptions.h" 00023 #include "clang/Basic/PartialDiagnostic.h" 00024 #include "llvm/ADT/StringExtras.h" 00025 using namespace clang; 00026 00027 /// \brief Determine whether the declaration found is acceptable as the name 00028 /// of a template and, if so, return that template declaration. Otherwise, 00029 /// returns NULL. 00030 static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) { 00031 if (!D) 00032 return 0; 00033 00034 if (isa<TemplateDecl>(D)) 00035 return D; 00036 00037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 00038 // C++ [temp.local]p1: 00039 // Like normal (non-template) classes, class templates have an 00040 // injected-class-name (Clause 9). The injected-class-name 00041 // can be used with or without a template-argument-list. When 00042 // it is used without a template-argument-list, it is 00043 // equivalent to the injected-class-name followed by the 00044 // template-parameters of the class template enclosed in 00045 // <>. When it is used with a template-argument-list, it 00046 // refers to the specified class template specialization, 00047 // which could be the current specialization or another 00048 // specialization. 00049 if (Record->isInjectedClassName()) { 00050 Record = cast<CXXRecordDecl>(Record->getDeclContext()); 00051 if (Record->getDescribedClassTemplate()) 00052 return Record->getDescribedClassTemplate(); 00053 00054 if (ClassTemplateSpecializationDecl *Spec 00055 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) 00056 return Spec->getSpecializedTemplate(); 00057 } 00058 00059 return 0; 00060 } 00061 00062 return 0; 00063 } 00064 00065 static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) { 00066 LookupResult::Filter filter = R.makeFilter(); 00067 while (filter.hasNext()) { 00068 NamedDecl *Orig = filter.next(); 00069 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl()); 00070 if (!Repl) 00071 filter.erase(); 00072 else if (Repl != Orig) 00073 filter.replace(Repl); 00074 } 00075 filter.done(); 00076 } 00077 00078 TemplateNameKind Sema::isTemplateName(Scope *S, 00079 const CXXScopeSpec &SS, 00080 UnqualifiedId &Name, 00081 TypeTy *ObjectTypePtr, 00082 bool EnteringContext, 00083 TemplateTy &TemplateResult) { 00084 assert(getLangOptions().CPlusPlus && "No template names in C!"); 00085 00086 DeclarationName TName; 00087 00088 switch (Name.getKind()) { 00089 case UnqualifiedId::IK_Identifier: 00090 TName = DeclarationName(Name.Identifier); 00091 break; 00092 00093 case UnqualifiedId::IK_OperatorFunctionId: 00094 TName = Context.DeclarationNames.getCXXOperatorName( 00095 Name.OperatorFunctionId.Operator); 00096 break; 00097 00098 case UnqualifiedId::IK_LiteralOperatorId: 00099 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); 00100 break; 00101 00102 default: 00103 return TNK_Non_template; 00104 } 00105 00106 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr); 00107 00108 LookupResult R(*this, TName, Name.getSourceRange().getBegin(), 00109 LookupOrdinaryName); 00110 R.suppressDiagnostics(); 00111 LookupTemplateName(R, S, SS, ObjectType, EnteringContext); 00112 if (R.empty()) 00113 return TNK_Non_template; 00114 00115 TemplateName Template; 00116 TemplateNameKind TemplateKind; 00117 00118 unsigned ResultCount = R.end() - R.begin(); 00119 if (ResultCount > 1) { 00120 // We assume that we'll preserve the qualifier from a function 00121 // template name in other ways. 00122 Template = Context.getOverloadedTemplateName(R.begin(), R.end()); 00123 TemplateKind = TNK_Function_template; 00124 } else { 00125 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl()); 00126 00127 if (SS.isSet() && !SS.isInvalid()) { 00128 NestedNameSpecifier *Qualifier 00129 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 00130 Template = Context.getQualifiedTemplateName(Qualifier, false, TD); 00131 } else { 00132 Template = TemplateName(TD); 00133 } 00134 00135 if (isa<FunctionTemplateDecl>(TD)) 00136 TemplateKind = TNK_Function_template; 00137 else { 00138 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD)); 00139 TemplateKind = TNK_Type_template; 00140 } 00141 } 00142 00143 TemplateResult = TemplateTy::make(Template); 00144 return TemplateKind; 00145 } 00146 00147 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, 00148 SourceLocation IILoc, 00149 Scope *S, 00150 const CXXScopeSpec *SS, 00151 TemplateTy &SuggestedTemplate, 00152 TemplateNameKind &SuggestedKind) { 00153 // We can't recover unless there's a dependent scope specifier preceding the 00154 // template name. 00155 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || 00156 computeDeclContext(*SS)) 00157 return false; 00158 00159 // The code is missing a 'template' keyword prior to the dependent template 00160 // name. 00161 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); 00162 Diag(IILoc, diag::err_template_kw_missing) 00163 << Qualifier << II.getName() 00164 << CodeModificationHint::CreateInsertion(IILoc, "template "); 00165 SuggestedTemplate 00166 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); 00167 SuggestedKind = TNK_Dependent_template_name; 00168 return true; 00169 } 00170 00171 void Sema::LookupTemplateName(LookupResult &Found, 00172 Scope *S, const CXXScopeSpec &SS, 00173 QualType ObjectType, 00174 bool EnteringContext) { 00175 // Determine where to perform name lookup 00176 DeclContext *LookupCtx = 0; 00177 bool isDependent = false; 00178 if (!ObjectType.isNull()) { 00179 // This nested-name-specifier occurs in a member access expression, e.g., 00180 // x->B::f, and we are looking into the type of the object. 00181 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 00182 LookupCtx = computeDeclContext(ObjectType); 00183 isDependent = ObjectType->isDependentType(); 00184 assert((isDependent || !ObjectType->isIncompleteType()) && 00185 "Caller should have completed object type"); 00186 } else if (SS.isSet()) { 00187 // This nested-name-specifier occurs after another nested-name-specifier, 00188 // so long into the context associated with the prior nested-name-specifier. 00189 LookupCtx = computeDeclContext(SS, EnteringContext); 00190 isDependent = isDependentScopeSpecifier(SS); 00191 00192 // The declaration context must be complete. 00193 if (LookupCtx && RequireCompleteDeclContext(SS)) 00194 return; 00195 } 00196 00197 bool ObjectTypeSearchedInScope = false; 00198 if (LookupCtx) { 00199 // Perform "qualified" name lookup into the declaration context we 00200 // computed, which is either the type of the base of a member access 00201 // expression or the declaration context associated with a prior 00202 // nested-name-specifier. 00203 LookupQualifiedName(Found, LookupCtx); 00204 00205 if (!ObjectType.isNull() && Found.empty()) { 00206 // C++ [basic.lookup.classref]p1: 00207 // In a class member access expression (5.2.5), if the . or -> token is 00208 // immediately followed by an identifier followed by a <, the 00209 // identifier must be looked up to determine whether the < is the 00210 // beginning of a template argument list (14.2) or a less-than operator. 00211 // The identifier is first looked up in the class of the object 00212 // expression. If the identifier is not found, it is then looked up in 00213 // the context of the entire postfix-expression and shall name a class 00214 // or function template. 00215 // 00216 // FIXME: When we're instantiating a template, do we actually have to 00217 // look in the scope of the template? Seems fishy... 00218 if (S) LookupName(Found, S); 00219 ObjectTypeSearchedInScope = true; 00220 } 00221 } else if (isDependent) { 00222 // We cannot look into a dependent object type or nested nme 00223 // specifier. 00224 return; 00225 } else { 00226 // Perform unqualified name lookup in the current scope. 00227 LookupName(Found, S); 00228 } 00229 00230 // FIXME: Cope with ambiguous name-lookup results. 00231 assert(!Found.isAmbiguous() && 00232 "Cannot handle template name-lookup ambiguities"); 00233 00234 if (Found.empty() && !isDependent) { 00235 // If we did not find any names, attempt to correct any typos. 00236 DeclarationName Name = Found.getLookupName(); 00237 if (CorrectTypo(Found, S, &SS, LookupCtx)) { 00238 FilterAcceptableTemplateNames(Context, Found); 00239 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) { 00240 if (LookupCtx) 00241 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest) 00242 << Name << LookupCtx << Found.getLookupName() << SS.getRange() 00243 << CodeModificationHint::CreateReplacement(Found.getNameLoc(), 00244 Found.getLookupName().getAsString()); 00245 else 00246 Diag(Found.getNameLoc(), diag::err_no_template_suggest) 00247 << Name << Found.getLookupName() 00248 << CodeModificationHint::CreateReplacement(Found.getNameLoc(), 00249 Found.getLookupName().getAsString()); 00250 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>()) 00251 Diag(Template->getLocation(), diag::note_previous_decl) 00252 << Template->getDeclName(); 00253 } else 00254 Found.clear(); 00255 } else { 00256 Found.clear(); 00257 } 00258 } 00259 00260 FilterAcceptableTemplateNames(Context, Found); 00261 if (Found.empty()) 00262 return; 00263 00264 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) { 00265 // C++ [basic.lookup.classref]p1: 00266 // [...] If the lookup in the class of the object expression finds a 00267 // template, the name is also looked up in the context of the entire 00268 // postfix-expression and [...] 00269 // 00270 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), 00271 LookupOrdinaryName); 00272 LookupName(FoundOuter, S); 00273 FilterAcceptableTemplateNames(Context, FoundOuter); 00274 // FIXME: Handle ambiguities in this lookup better 00275 00276 if (FoundOuter.empty()) { 00277 // - if the name is not found, the name found in the class of the 00278 // object expression is used, otherwise 00279 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) { 00280 // - if the name is found in the context of the entire 00281 // postfix-expression and does not name a class template, the name 00282 // found in the class of the object expression is used, otherwise 00283 } else { 00284 // - if the name found is a class template, it must refer to the same 00285 // entity as the one found in the class of the object expression, 00286 // otherwise the program is ill-formed. 00287 if (!Found.isSingleResult() || 00288 Found.getFoundDecl()->getCanonicalDecl() 00289 != FoundOuter.getFoundDecl()->getCanonicalDecl()) { 00290 Diag(Found.getNameLoc(), 00291 diag::err_nested_name_member_ref_lookup_ambiguous) 00292 << Found.getLookupName(); 00293 Diag(Found.getRepresentativeDecl()->getLocation(), 00294 diag::note_ambig_member_ref_object_type) 00295 << ObjectType; 00296 Diag(FoundOuter.getFoundDecl()->getLocation(), 00297 diag::note_ambig_member_ref_scope); 00298 00299 // Recover by taking the template that we found in the object 00300 // expression's type. 00301 } 00302 } 00303 } 00304 } 00305 00306 /// ActOnDependentIdExpression - Handle a dependent id-expression that 00307 /// was just parsed. This is only possible with an explicit scope 00308 /// specifier naming a dependent type. 00309 Sema::OwningExprResult 00310 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, 00311 DeclarationName Name, 00312 SourceLocation NameLoc, 00313 bool isAddressOfOperand, 00314 const TemplateArgumentListInfo *TemplateArgs) { 00315 NestedNameSpecifier *Qualifier 00316 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 00317 00318 if (!isAddressOfOperand && 00319 isa<CXXMethodDecl>(CurContext) && 00320 cast<CXXMethodDecl>(CurContext)->isInstance()) { 00321 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context); 00322 00323 // Since the 'this' expression is synthesized, we don't need to 00324 // perform the double-lookup check. 00325 NamedDecl *FirstQualifierInScope = 0; 00326 00327 return Owned(CXXDependentScopeMemberExpr::Create(Context, 00328 /*This*/ 0, ThisType, 00329 /*IsArrow*/ true, 00330 /*Op*/ SourceLocation(), 00331 Qualifier, SS.getRange(), 00332 FirstQualifierInScope, 00333 Name, NameLoc, 00334 TemplateArgs)); 00335 } 00336 00337 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs); 00338 } 00339 00340 Sema::OwningExprResult 00341 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 00342 DeclarationName Name, 00343 SourceLocation NameLoc, 00344 const TemplateArgumentListInfo *TemplateArgs) { 00345 return Owned(DependentScopeDeclRefExpr::Create(Context, 00346 static_cast<NestedNameSpecifier*>(SS.getScopeRep()), 00347 SS.getRange(), 00348 Name, NameLoc, 00349 TemplateArgs)); 00350 } 00351 00352 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 00353 /// that the template parameter 'PrevDecl' is being shadowed by a new 00354 /// declaration at location Loc. Returns true to indicate that this is 00355 /// an error, and false otherwise. 00356 bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 00357 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 00358 00359 // Microsoft Visual C++ permits template parameters to be shadowed. 00360 if (getLangOptions().Microsoft) 00361 return false; 00362 00363 // C++ [temp.local]p4: 00364 // A template-parameter shall not be redeclared within its 00365 // scope (including nested scopes). 00366 Diag(Loc, diag::err_template_param_shadow) 00367 << cast<NamedDecl>(PrevDecl)->getDeclName(); 00368 Diag(PrevDecl->getLocation(), diag::note_template_param_here); 00369 return true; 00370 } 00371 00372 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 00373 /// the parameter D to reference the templated declaration and return a pointer 00374 /// to the template declaration. Otherwise, do nothing to D and return null. 00375 TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) { 00376 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) { 00377 D = DeclPtrTy::make(Temp->getTemplatedDecl()); 00378 return Temp; 00379 } 00380 return 0; 00381 } 00382 00383 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, 00384 const ParsedTemplateArgument &Arg) { 00385 00386 switch (Arg.getKind()) { 00387 case ParsedTemplateArgument::Type: { 00388 TypeSourceInfo *DI; 00389 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); 00390 if (!DI) 00391 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); 00392 return TemplateArgumentLoc(TemplateArgument(T), DI); 00393 } 00394 00395 case ParsedTemplateArgument::NonType: { 00396 Expr *E = static_cast<Expr *>(Arg.getAsExpr()); 00397 return TemplateArgumentLoc(TemplateArgument(E), E); 00398 } 00399 00400 case ParsedTemplateArgument::Template: { 00401 TemplateName Template 00402 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get()); 00403 return TemplateArgumentLoc(TemplateArgument(Template), 00404 Arg.getScopeSpec().getRange(), 00405 Arg.getLocation()); 00406 } 00407 } 00408 00409 llvm_unreachable("Unhandled parsed template argument"); 00410 return TemplateArgumentLoc(); 00411 } 00412 00413 /// \brief Translates template arguments as provided by the parser 00414 /// into template arguments used by semantic analysis. 00415 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, 00416 TemplateArgumentListInfo &TemplateArgs) { 00417 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) 00418 TemplateArgs.addArgument(translateTemplateArgument(*this, 00419 TemplateArgsIn[I])); 00420 } 00421 00422 /// ActOnTypeParameter - Called when a C++ template type parameter 00423 /// (e.g., "typename T") has been parsed. Typename specifies whether 00424 /// the keyword "typename" was used to declare the type parameter 00425 /// (otherwise, "class" was used), and KeyLoc is the location of the 00426 /// "class" or "typename" keyword. ParamName is the name of the 00427 /// parameter (NULL indicates an unnamed template parameter) and 00428 /// ParamName is the location of the parameter name (if any). 00429 /// If the type parameter has a default argument, it will be added 00430 /// later via ActOnTypeParameterDefault. 00431 Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 00432 SourceLocation EllipsisLoc, 00433 SourceLocation KeyLoc, 00434 IdentifierInfo *ParamName, 00435 SourceLocation ParamNameLoc, 00436 unsigned Depth, unsigned Position) { 00437 assert(S->isTemplateParamScope() && 00438 "Template type parameter not in template parameter scope!"); 00439 bool Invalid = false; 00440 00441 if (ParamName) { 00442 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName); 00443 if (PrevDecl && PrevDecl->isTemplateParameter()) 00444 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc, 00445 PrevDecl); 00446 } 00447 00448 SourceLocation Loc = ParamNameLoc; 00449 if (!ParamName) 00450 Loc = KeyLoc; 00451 00452 TemplateTypeParmDecl *Param 00453 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), 00454 Loc, Depth, Position, ParamName, Typename, 00455 Ellipsis); 00456 if (Invalid) 00457 Param->setInvalidDecl(); 00458 00459 if (ParamName) { 00460 // Add the template parameter into the current scope. 00461 S->AddDecl(DeclPtrTy::make(Param)); 00462 IdResolver.AddDecl(Param); 00463 } 00464 00465 return DeclPtrTy::make(Param); 00466 } 00467 00468 /// ActOnTypeParameterDefault - Adds a default argument (the type 00469 /// Default) to the given template type parameter (TypeParam). 00470 void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam, 00471 SourceLocation EqualLoc, 00472 SourceLocation DefaultLoc, 00473 TypeTy *DefaultT) { 00474 TemplateTypeParmDecl *Parm 00475 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>()); 00476 00477 TypeSourceInfo *DefaultTInfo; 00478 GetTypeFromParser(DefaultT, &DefaultTInfo); 00479 00480 assert(DefaultTInfo && "expected source information for type"); 00481 00482 // C++0x [temp.param]p9: 00483 // A default template-argument may be specified for any kind of 00484 // template-parameter that is not a template parameter pack. 00485 if (Parm->isParameterPack()) { 00486 Diag(DefaultLoc, diag::err_template_param_pack_default_arg); 00487 return; 00488 } 00489 00490 // C++ [temp.param]p14: 00491 // A template-parameter shall not be used in its own default argument. 00492 // FIXME: Implement this check! Needs a recursive walk over the types. 00493 00494 // Check the template argument itself. 00495 if (CheckTemplateArgument(Parm, DefaultTInfo)) { 00496 Parm->setInvalidDecl(); 00497 return; 00498 } 00499 00500 Parm->setDefaultArgument(DefaultTInfo, false); 00501 } 00502 00503 /// \brief Check that the type of a non-type template parameter is 00504 /// well-formed. 00505 /// 00506 /// \returns the (possibly-promoted) parameter type if valid; 00507 /// otherwise, produces a diagnostic and returns a NULL type. 00508 QualType 00509 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) { 00510 // C++ [temp.param]p4: 00511 // 00512 // A non-type template-parameter shall have one of the following 00513 // (optionally cv-qualified) types: 00514 // 00515 // -- integral or enumeration type, 00516 if (T->isIntegralType() || T->isEnumeralType() || 00517 // -- pointer to object or pointer to function, 00518 (T->isPointerType() && 00519 (T->getAs<PointerType>()->getPointeeType()->isObjectType() || 00520 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) || 00521 // -- reference to object or reference to function, 00522 T->isReferenceType() || 00523 // -- pointer to member. 00524 T->isMemberPointerType() || 00525 // If T is a dependent type, we can't do the check now, so we 00526 // assume that it is well-formed. 00527 T->isDependentType()) 00528 return T; 00529 // C++ [temp.param]p8: 00530 // 00531 // A non-type template-parameter of type "array of T" or 00532 // "function returning T" is adjusted to be of type "pointer to 00533 // T" or "pointer to function returning T", respectively. 00534 else if (T->isArrayType()) 00535 // FIXME: Keep the type prior to promotion? 00536 return Context.getArrayDecayedType(T); 00537 else if (T->isFunctionType()) 00538 // FIXME: Keep the type prior to promotion? 00539 return Context.getPointerType(T); 00540 00541 Diag(Loc, diag::err_template_nontype_parm_bad_type) 00542 << T; 00543 00544 return QualType(); 00545 } 00546 00547 /// ActOnNonTypeTemplateParameter - Called when a C++ non-type 00548 /// template parameter (e.g., "int Size" in "template<int Size> 00549 /// class Array") has been parsed. S is the current scope and D is 00550 /// the parsed declarator. 00551 Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 00552 unsigned Depth, 00553 unsigned Position) { 00554 TypeSourceInfo *TInfo = 0; 00555 QualType T = GetTypeForDeclarator(D, S, &TInfo); 00556 00557 assert(S->isTemplateParamScope() && 00558 "Non-type template parameter not in template parameter scope!"); 00559 bool Invalid = false; 00560 00561 IdentifierInfo *ParamName = D.getIdentifier(); 00562 if (ParamName) { 00563 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName); 00564 if (PrevDecl && PrevDecl->isTemplateParameter()) 00565 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 00566 PrevDecl); 00567 } 00568 00569 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc()); 00570 if (T.isNull()) { 00571 T = Context.IntTy; // Recover with an 'int' type. 00572 Invalid = true; 00573 } 00574 00575 NonTypeTemplateParmDecl *Param 00576 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 00577 D.getIdentifierLoc(), 00578 Depth, Position, ParamName, T, TInfo); 00579 if (Invalid) 00580 Param->setInvalidDecl(); 00581 00582 if (D.getIdentifier()) { 00583 // Add the template parameter into the current scope. 00584 S->AddDecl(DeclPtrTy::make(Param)); 00585 IdResolver.AddDecl(Param); 00586 } 00587 return DeclPtrTy::make(Param); 00588 } 00589 00590 /// \brief Adds a default argument to the given non-type template 00591 /// parameter. 00592 void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD, 00593 SourceLocation EqualLoc, 00594 ExprArg DefaultE) { 00595 NonTypeTemplateParmDecl *TemplateParm 00596 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>()); 00597 Expr *Default = static_cast<Expr *>(DefaultE.get()); 00598 00599 // C++ [temp.param]p14: 00600 // A template-parameter shall not be used in its own default argument. 00601 // FIXME: Implement this check! Needs a recursive walk over the types. 00602 00603 // Check the well-formedness of the default template argument. 00604 TemplateArgument Converted; 00605 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default, 00606 Converted)) { 00607 TemplateParm->setInvalidDecl(); 00608 return; 00609 } 00610 00611 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>()); 00612 } 00613 00614 00615 /// ActOnTemplateTemplateParameter - Called when a C++ template template 00616 /// parameter (e.g. T in template <template <typename> class T> class array) 00617 /// has been parsed. S is the current scope. 00618 Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S, 00619 SourceLocation TmpLoc, 00620 TemplateParamsTy *Params, 00621 IdentifierInfo *Name, 00622 SourceLocation NameLoc, 00623 unsigned Depth, 00624 unsigned Position) { 00625 assert(S->isTemplateParamScope() && 00626 "Template template parameter not in template parameter scope!"); 00627 00628 // Construct the parameter object. 00629 TemplateTemplateParmDecl *Param = 00630 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 00631 TmpLoc, Depth, Position, Name, 00632 (TemplateParameterList*)Params); 00633 00634 // Make sure the parameter is valid. 00635 // FIXME: Decl object is not currently invalidated anywhere so this doesn't 00636 // do anything yet. However, if the template parameter list or (eventual) 00637 // default value is ever invalidated, that will propagate here. 00638 bool Invalid = false; 00639 if (Invalid) { 00640 Param->setInvalidDecl(); 00641 } 00642 00643 // If the tt-param has a name, then link the identifier into the scope 00644 // and lookup mechanisms. 00645 if (Name) { 00646 S->AddDecl(DeclPtrTy::make(Param)); 00647 IdResolver.AddDecl(Param); 00648 } 00649 00650 return DeclPtrTy::make(Param); 00651 } 00652 00653 /// \brief Adds a default argument to the given template template 00654 /// parameter. 00655 void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD, 00656 SourceLocation EqualLoc, 00657 const ParsedTemplateArgument &Default) { 00658 TemplateTemplateParmDecl *TemplateParm 00659 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>()); 00660 00661 // C++ [temp.param]p14: 00662 // A template-parameter shall not be used in its own default argument. 00663 // FIXME: Implement this check! Needs a recursive walk over the types. 00664 00665 // Check only that we have a template template argument. We don't want to 00666 // try to check well-formedness now, because our template template parameter 00667 // might have dependent types in its template parameters, which we wouldn't 00668 // be able to match now. 00669 // 00670 // If none of the template template parameter's template arguments mention 00671 // other template parameters, we could actually perform more checking here. 00672 // However, it isn't worth doing. 00673 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); 00674 if (DefaultArg.getArgument().getAsTemplate().isNull()) { 00675 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template) 00676 << DefaultArg.getSourceRange(); 00677 return; 00678 } 00679 00680 TemplateParm->setDefaultArgument(DefaultArg); 00681 } 00682 00683 /// ActOnTemplateParameterList - Builds a TemplateParameterList that 00684 /// contains the template parameters in Params/NumParams. 00685 Sema::TemplateParamsTy * 00686 Sema::ActOnTemplateParameterList(unsigned Depth, 00687 SourceLocation ExportLoc, 00688 SourceLocation TemplateLoc, 00689 SourceLocation LAngleLoc, 00690 DeclPtrTy *Params, unsigned NumParams, 00691 SourceLocation RAngleLoc) { 00692 if (ExportLoc.isValid()) 00693 Diag(ExportLoc, diag::warn_template_export_unsupported); 00694 00695 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, 00696 (NamedDecl**)Params, NumParams, 00697 RAngleLoc); 00698 } 00699 00700 Sema::DeclResult 00701 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 00702 SourceLocation KWLoc, const CXXScopeSpec &SS, 00703 IdentifierInfo *Name, SourceLocation NameLoc, 00704 AttributeList *Attr, 00705 TemplateParameterList *TemplateParams, 00706 AccessSpecifier AS) { 00707 assert(TemplateParams && TemplateParams->size() > 0 && 00708 "No template parameters"); 00709 assert(TUK != TUK_Reference && "Can only declare or define class templates"); 00710 bool Invalid = false; 00711 00712 // Check that we can declare a template here. 00713 if (CheckTemplateDeclScope(S, TemplateParams)) 00714 return true; 00715 00716 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec); 00717 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type"); 00718 00719 // There is no such thing as an unnamed class template. 00720 if (!Name) { 00721 Diag(KWLoc, diag::err_template_unnamed_class); 00722 return true; 00723 } 00724 00725 // Find any previous declaration with this name. 00726 DeclContext *SemanticContext; 00727 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName, 00728 ForRedeclaration); 00729 if (SS.isNotEmpty() && !SS.isInvalid()) { 00730 if (RequireCompleteDeclContext(SS)) 00731 return true; 00732 00733 SemanticContext = computeDeclContext(SS, true); 00734 if (!SemanticContext) { 00735 // FIXME: Produce a reasonable diagnostic here 00736 return true; 00737 } 00738 00739 LookupQualifiedName(Previous, SemanticContext); 00740 } else { 00741 SemanticContext = CurContext; 00742 LookupName(Previous, S); 00743 } 00744 00745 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?"); 00746 NamedDecl *PrevDecl = 0; 00747 if (Previous.begin() != Previous.end()) 00748 PrevDecl = *Previous.begin(); 00749 00750 // If there is a previous declaration with the same name, check 00751 // whether this is a valid redeclaration. 00752 ClassTemplateDecl *PrevClassTemplate 00753 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); 00754 00755 // We may have found the injected-class-name of a class template, 00756 // class template partial specialization, or class template specialization. 00757 // In these cases, grab the template that is being defined or specialized. 00758 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && 00759 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { 00760 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); 00761 PrevClassTemplate 00762 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); 00763 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { 00764 PrevClassTemplate 00765 = cast<ClassTemplateSpecializationDecl>(PrevDecl) 00766 ->getSpecializedTemplate(); 00767 } 00768 } 00769 00770 if (TUK == TUK_Friend) { 00771 // C++ [namespace.memdef]p3: 00772 // [...] When looking for a prior declaration of a class or a function 00773 // declared as a friend, and when the name of the friend class or 00774 // function is neither a qualified name nor a template-id, scopes outside 00775 // the innermost enclosing namespace scope are not considered. 00776 DeclContext *OutermostContext = CurContext; 00777 while (!OutermostContext->isFileContext()) 00778 OutermostContext = OutermostContext->getLookupParent(); 00779 00780 if (PrevDecl && 00781 (OutermostContext->Equals(PrevDecl->getDeclContext()) || 00782 OutermostContext->Encloses(PrevDecl->getDeclContext()))) { 00783 SemanticContext = PrevDecl->getDeclContext(); 00784 } else { 00785 // Declarations in outer scopes don't matter. However, the outermost 00786 // context we computed is the semantic context for our new 00787 // declaration. 00788 PrevDecl = PrevClassTemplate = 0; 00789 SemanticContext = OutermostContext; 00790 } 00791 00792 if (CurContext->isDependentContext()) { 00793 // If this is a dependent context, we don't want to link the friend 00794 // class template to the template in scope, because that would perform 00795 // checking of the template parameter lists that can't be performed 00796 // until the outer context is instantiated. 00797 PrevDecl = PrevClassTemplate = 0; 00798 } 00799 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S)) 00800 PrevDecl = PrevClassTemplate = 0; 00801 00802 if (PrevClassTemplate) { 00803 // Ensure that the template parameter lists are compatible. 00804 if (!TemplateParameterListsAreEqual(TemplateParams, 00805 PrevClassTemplate->getTemplateParameters(), 00806 /*Complain=*/true, 00807 TPL_TemplateMatch)) 00808 return true; 00809 00810 // C++ [temp.class]p4: 00811 // In a redeclaration, partial specialization, explicit 00812 // specialization or explicit instantiation of a class template, 00813 // the class-key shall agree in kind with the original class 00814 // template declaration (7.1.5.3). 00815 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 00816 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) { 00817 Diag(KWLoc, diag::err_use_with_wrong_tag) 00818 << Name 00819 << CodeModificationHint::CreateReplacement(KWLoc, 00820 PrevRecordDecl->getKindName()); 00821 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 00822 Kind = PrevRecordDecl->getTagKind(); 00823 } 00824 00825 // Check for redefinition of this class template. 00826 if (TUK == TUK_Definition) { 00827 if (TagDecl *Def = PrevRecordDecl->getDefinition()) { 00828 Diag(NameLoc, diag::err_redefinition) << Name; 00829 Diag(Def->getLocation(), diag::note_previous_definition); 00830 // FIXME: Would it make sense to try to "forget" the previous 00831 // definition, as part of error recovery? 00832 return true; 00833 } 00834 } 00835 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 00836 // Maybe we will complain about the shadowed template parameter. 00837 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 00838 // Just pretend that we didn't see the previous declaration. 00839 PrevDecl = 0; 00840 } else if (PrevDecl) { 00841 // C++ [temp]p5: 00842 // A class template shall not have the same name as any other 00843 // template, class, function, object, enumeration, enumerator, 00844 // namespace, or type in the same scope (3.3), except as specified 00845 // in (14.5.4). 00846 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 00847 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 00848 return true; 00849 } 00850 00851 // Check the template parameter list of this declaration, possibly 00852 // merging in the template parameter list from the previous class 00853 // template declaration. 00854 if (CheckTemplateParameterList(TemplateParams, 00855 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0, 00856 TPC_ClassTemplate)) 00857 Invalid = true; 00858 00859 // FIXME: If we had a scope specifier, we better have a previous template 00860 // declaration! 00861 00862 CXXRecordDecl *NewClass = 00863 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc, 00864 PrevClassTemplate? 00865 PrevClassTemplate->getTemplatedDecl() : 0, 00866 /*DelayTypeCreation=*/true); 00867 00868 ClassTemplateDecl *NewTemplate 00869 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 00870 DeclarationName(Name), TemplateParams, 00871 NewClass, PrevClassTemplate); 00872 NewClass->setDescribedClassTemplate(NewTemplate); 00873 00874 // Build the type for the class template declaration now. 00875 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context); 00876 T = Context.getInjectedClassNameType(NewClass, T); 00877 assert(T->isDependentType() && "Class template type is not dependent?"); 00878 (void)T; 00879 00880 // If we are providing an explicit specialization of a member that is a 00881 // class template, make a note of that. 00882 if (PrevClassTemplate && 00883 PrevClassTemplate->getInstantiatedFromMemberTemplate()) 00884 PrevClassTemplate->setMemberSpecialization(); 00885 00886 // Set the access specifier. 00887 if (!Invalid && TUK != TUK_Friend) 00888 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); 00889 00890 // Set the lexical context of these templates 00891 NewClass->setLexicalDeclContext(CurContext); 00892 NewTemplate->setLexicalDeclContext(CurContext); 00893 00894 if (TUK == TUK_Definition) 00895 NewClass->startDefinition(); 00896 00897 if (Attr) 00898 ProcessDeclAttributeList(S, NewClass, Attr); 00899 00900 if (TUK != TUK_Friend) 00901 PushOnScopeChains(NewTemplate, S); 00902 else { 00903 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { 00904 NewTemplate->setAccess(PrevClassTemplate->getAccess()); 00905 NewClass->setAccess(PrevClassTemplate->getAccess()); 00906 } 00907 00908 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */ 00909 PrevClassTemplate != NULL); 00910 00911 // Friend templates are visible in fairly strange ways. 00912 if (!CurContext->isDependentContext()) { 00913 DeclContext *DC = SemanticContext->getLookupContext(); 00914 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false); 00915 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 00916 PushOnScopeChains(NewTemplate, EnclosingScope, 00917 /* AddToContext = */ false); 00918 } 00919 00920 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 00921 NewClass->getLocation(), 00922 NewTemplate, 00923 /*FIXME:*/NewClass->getLocation()); 00924 Friend->setAccess(AS_public); 00925 CurContext->addDecl(Friend); 00926 } 00927 00928 if (Invalid) { 00929 NewTemplate->setInvalidDecl(); 00930 NewClass->setInvalidDecl(); 00931 } 00932 return DeclPtrTy::make(NewTemplate); 00933 } 00934 00935 /// \brief Diagnose the presence of a default template argument on a 00936 /// template parameter, which is ill-formed in certain contexts. 00937 /// 00938 /// \returns true if the default template argument should be dropped. 00939 static bool DiagnoseDefaultTemplateArgument(Sema &S, 00940 Sema::TemplateParamListContext TPC, 00941 SourceLocation ParamLoc, 00942 SourceRange DefArgRange) { 00943 switch (TPC) { 00944 case Sema::TPC_ClassTemplate: 00945 return false; 00946 00947 case Sema::TPC_FunctionTemplate: 00948 // C++ [temp.param]p9: 00949 // A default template-argument shall not be specified in a 00950 // function template declaration or a function template 00951 // definition [...] 00952 // (This sentence is not in C++0x, per DR226). 00953 if (!S.getLangOptions().CPlusPlus0x) 00954 S.Diag(ParamLoc, 00955 diag::err_template_parameter_default_in_function_template) 00956 << DefArgRange; 00957 return false; 00958 00959 case Sema::TPC_ClassTemplateMember: 00960 // C++0x [temp.param]p9: 00961 // A default template-argument shall not be specified in the 00962 // template-parameter-lists of the definition of a member of a 00963 // class template that appears outside of the member's class. 00964 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) 00965 << DefArgRange; 00966 return true; 00967 00968 case Sema::TPC_FriendFunctionTemplate: 00969 // C++ [temp.param]p9: 00970 // A default template-argument shall not be specified in a 00971 // friend template declaration. 00972 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) 00973 << DefArgRange; 00974 return true; 00975 00976 // FIXME: C++0x [temp.param]p9 allows default template-arguments 00977 // for friend function templates if there is only a single 00978 // declaration (and it is a definition). Strange! 00979 } 00980 00981 return false; 00982 } 00983 00984 /// \brief Checks the validity of a template parameter list, possibly 00985 /// considering the template parameter list from a previous 00986 /// declaration. 00987 /// 00988 /// If an "old" template parameter list is provided, it must be 00989 /// equivalent (per TemplateParameterListsAreEqual) to the "new" 00990 /// template parameter list. 00991 /// 00992 /// \param NewParams Template parameter list for a new template 00993 /// declaration. This template parameter list will be updated with any 00994 /// default arguments that are carried through from the previous 00995 /// template parameter list. 00996 /// 00997 /// \param OldParams If provided, template parameter list from a 00998 /// previous declaration of the same template. Default template 00999 /// arguments will be merged from the old template parameter list to 01000 /// the new template parameter list. 01001 /// 01002 /// \param TPC Describes the context in which we are checking the given 01003 /// template parameter list. 01004 /// 01005 /// \returns true if an error occurred, false otherwise. 01006 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, 01007 TemplateParameterList *OldParams, 01008 TemplateParamListContext TPC) { 01009 bool Invalid = false; 01010 01011 // C++ [temp.param]p10: 01012 // The set of default template-arguments available for use with a 01013 // template declaration or definition is obtained by merging the 01014 // default arguments from the definition (if in scope) and all 01015 // declarations in scope in the same way default function 01016 // arguments are (8.3.6). 01017 bool SawDefaultArgument = false; 01018 SourceLocation PreviousDefaultArgLoc; 01019 01020 bool SawParameterPack = false; 01021 SourceLocation ParameterPackLoc; 01022 01023 // Dummy initialization to avoid warnings. 01024 TemplateParameterList::iterator OldParam = NewParams->end(); 01025 if (OldParams) 01026 OldParam = OldParams->begin(); 01027 01028 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 01029 NewParamEnd = NewParams->end(); 01030 NewParam != NewParamEnd; ++NewParam) { 01031 // Variables used to diagnose redundant default arguments 01032 bool RedundantDefaultArg = false; 01033 SourceLocation OldDefaultLoc; 01034 SourceLocation NewDefaultLoc; 01035 01036 // Variables used to diagnose missing default arguments 01037 bool MissingDefaultArg = false; 01038 01039 // C++0x [temp.param]p11: 01040 // If a template parameter of a class template is a template parameter pack, 01041 // it must be the last template parameter. 01042 if (SawParameterPack) { 01043 Diag(ParameterPackLoc, 01044 diag::err_template_param_pack_must_be_last_template_parameter); 01045 Invalid = true; 01046 } 01047 01048 if (TemplateTypeParmDecl *NewTypeParm 01049 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { 01050 // Check the presence of a default argument here. 01051 if (NewTypeParm->hasDefaultArgument() && 01052 DiagnoseDefaultTemplateArgument(*this, TPC, 01053 NewTypeParm->getLocation(), 01054 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() 01055 .getFullSourceRange())) 01056 NewTypeParm->removeDefaultArgument(); 01057 01058 // Merge default arguments for template type parameters. 01059 TemplateTypeParmDecl *OldTypeParm 01060 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0; 01061 01062 if (NewTypeParm->isParameterPack()) { 01063 assert(!NewTypeParm->hasDefaultArgument() && 01064 "Parameter packs can't have a default argument!"); 01065 SawParameterPack = true; 01066 ParameterPackLoc = NewTypeParm->getLocation(); 01067 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() && 01068 NewTypeParm->hasDefaultArgument()) { 01069 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); 01070 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); 01071 SawDefaultArgument = true; 01072 RedundantDefaultArg = true; 01073 PreviousDefaultArgLoc = NewDefaultLoc; 01074 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { 01075 // Merge the default argument from the old declaration to the 01076 // new declaration. 01077 SawDefaultArgument = true; 01078 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(), 01079 true); 01080 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); 01081 } else if (NewTypeParm->hasDefaultArgument()) { 01082 SawDefaultArgument = true; 01083 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); 01084 } else if (SawDefaultArgument) 01085 MissingDefaultArg = true; 01086 } else if (NonTypeTemplateParmDecl *NewNonTypeParm 01087 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { 01088 // Check the presence of a default argument here. 01089 if (NewNonTypeParm->hasDefaultArgument() && 01090 DiagnoseDefaultTemplateArgument(*this, TPC, 01091 NewNonTypeParm->getLocation(), 01092 NewNonTypeParm->getDefaultArgument()->getSourceRange())) { 01093 NewNonTypeParm->getDefaultArgument()->Destroy(Context); 01094 NewNonTypeParm->setDefaultArgument(0); 01095 } 01096 01097 // Merge default arguments for non-type template parameters 01098 NonTypeTemplateParmDecl *OldNonTypeParm 01099 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0; 01100 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() && 01101 NewNonTypeParm->hasDefaultArgument()) { 01102 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); 01103 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); 01104 SawDefaultArgument = true; 01105 RedundantDefaultArg = true; 01106 PreviousDefaultArgLoc = NewDefaultLoc; 01107 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { 01108 // Merge the default argument from the old declaration to the 01109 // new declaration. 01110 SawDefaultArgument = true; 01111 // FIXME: We need to create a new kind of "default argument" 01112 // expression that points to a previous template template 01113 // parameter. 01114 NewNonTypeParm->setDefaultArgument( 01115 OldNonTypeParm->getDefaultArgument()); 01116 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); 01117 } else if (NewNonTypeParm->hasDefaultArgument()) { 01118 SawDefaultArgument = true; 01119 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); 01120 } else if (SawDefaultArgument) 01121 MissingDefaultArg = true; 01122 } else { 01123 // Check the presence of a default argument here. 01124 TemplateTemplateParmDecl *NewTemplateParm 01125 = cast<TemplateTemplateParmDecl>(*NewParam); 01126 if (NewTemplateParm->hasDefaultArgument() && 01127 DiagnoseDefaultTemplateArgument(*this, TPC, 01128 NewTemplateParm->getLocation(), 01129 NewTemplateParm->getDefaultArgument().getSourceRange())) 01130 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc()); 01131 01132 // Merge default arguments for template template parameters 01133 TemplateTemplateParmDecl *OldTemplateParm 01134 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0; 01135 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() && 01136 NewTemplateParm->hasDefaultArgument()) { 01137 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); 01138 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); 01139 SawDefaultArgument = true; 01140 RedundantDefaultArg = true; 01141 PreviousDefaultArgLoc = NewDefaultLoc; 01142 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { 01143 // Merge the default argument from the old declaration to the 01144 // new declaration. 01145 SawDefaultArgument = true; 01146 // FIXME: We need to create a new kind of "default argument" expression 01147 // that points to a previous template template parameter. 01148 NewTemplateParm->setDefaultArgument( 01149 OldTemplateParm->getDefaultArgument()); 01150 PreviousDefaultArgLoc 01151 = OldTemplateParm->getDefaultArgument().getLocation(); 01152 } else if (NewTemplateParm->hasDefaultArgument()) { 01153 SawDefaultArgument = true; 01154 PreviousDefaultArgLoc 01155 = NewTemplateParm->getDefaultArgument().getLocation(); 01156 } else if (SawDefaultArgument) 01157 MissingDefaultArg = true; 01158 } 01159 01160 if (RedundantDefaultArg) { 01161 // C++ [temp.param]p12: 01162 // A template-parameter shall not be given default arguments 01163 // by two different declarations in the same scope. 01164 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); 01165 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); 01166 Invalid = true; 01167 } else if (MissingDefaultArg) { 01168 // C++ [temp.param]p11: 01169 // If a template-parameter has a default template-argument, 01170 // all subsequent template-parameters shall have a default 01171 // template-argument supplied. 01172 Diag((*NewParam)->getLocation(), 01173 diag::err_template_param_default_arg_missing); 01174 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); 01175 Invalid = true; 01176 } 01177 01178 // If we have an old template parameter list that we're merging 01179 // in, move on to the next parameter. 01180 if (OldParams) 01181 ++OldParam; 01182 } 01183 01184 return Invalid; 01185 } 01186 01187 /// \brief Match the given template parameter lists to the given scope 01188 /// specifier, returning the template parameter list that applies to the 01189 /// name. 01190 /// 01191 /// \param DeclStartLoc the start of the declaration that has a scope 01192 /// specifier or a template parameter list. 01193 /// 01194 /// \param SS the scope specifier that will be matched to the given template 01195 /// parameter lists. This scope specifier precedes a qualified name that is 01196 /// being declared. 01197 /// 01198 /// \param ParamLists the template parameter lists, from the outermost to the 01199 /// innermost template parameter lists. 01200 /// 01201 /// \param NumParamLists the number of template parameter lists in ParamLists. 01202 /// 01203 /// \param IsExplicitSpecialization will be set true if the entity being 01204 /// declared is an explicit specialization, false otherwise. 01205 /// 01206 /// \returns the template parameter list, if any, that corresponds to the 01207 /// name that is preceded by the scope specifier @p SS. This template 01208 /// parameter list may be have template parameters (if we're declaring a 01209 /// template) or may have no template parameters (if we're declaring a 01210 /// template specialization), or may be NULL (if we were's declaring isn't 01211 /// itself a template). 01212 TemplateParameterList * 01213 Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 01214 const CXXScopeSpec &SS, 01215 TemplateParameterList **ParamLists, 01216 unsigned NumParamLists, 01217 bool &IsExplicitSpecialization) { 01218 IsExplicitSpecialization = false; 01219 01220 // Find the template-ids that occur within the nested-name-specifier. These 01221 // template-ids will match up with the template parameter lists. 01222 llvm::SmallVector<const TemplateSpecializationType *, 4> 01223 TemplateIdsInSpecifier; 01224 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4> 01225 ExplicitSpecializationsInSpecifier; 01226 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 01227 NNS; NNS = NNS->getPrefix()) { 01228 const Type *T = NNS->getAsType(); 01229 if (!T) break; 01230 01231 // C++0x [temp.expl.spec]p17: 01232 // A member or a member template may be nested within many 01233 // enclosing class templates. In an explicit specialization for 01234 // such a member, the member declaration shall be preceded by a 01235 // template<> for each enclosing class template that is 01236 // explicitly specialized. 01237 // 01238 // Following the existing practice of GNU and EDG, we allow a typedef of a 01239 // template specialization type. 01240 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 01241 T = TT->LookThroughTypedefs().getTypePtr(); 01242 01243 if (const TemplateSpecializationType *SpecType 01244 = dyn_cast<TemplateSpecializationType>(T)) { 01245 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl(); 01246 if (!Template) 01247 continue; // FIXME: should this be an error? probably... 01248 01249 if (const RecordType *Record = SpecType->getAs<RecordType>()) { 01250 ClassTemplateSpecializationDecl *SpecDecl 01251 = cast<ClassTemplateSpecializationDecl>(Record->getDecl()); 01252 // If the nested name specifier refers to an explicit specialization, 01253 // we don't need a template<> header. 01254 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) { 01255 ExplicitSpecializationsInSpecifier.push_back(SpecDecl); 01256 continue; 01257 } 01258 } 01259 01260 TemplateIdsInSpecifier.push_back(SpecType); 01261 } 01262 } 01263 01264 // Reverse the list of template-ids in the scope specifier, so that we can 01265 // more easily match up the template-ids and the template parameter lists. 01266 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end()); 01267 01268 SourceLocation FirstTemplateLoc = DeclStartLoc; 01269 if (NumParamLists) 01270 FirstTemplateLoc = ParamLists[0]->getTemplateLoc(); 01271 01272 // Match the template-ids found in the specifier to the template parameter 01273 // lists. 01274 unsigned Idx = 0; 01275 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size(); 01276 Idx != NumTemplateIds; ++Idx) { 01277 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0); 01278 bool DependentTemplateId = TemplateId->isDependentType(); 01279 if (Idx >= NumParamLists) { 01280 // We have a template-id without a corresponding template parameter 01281 // list. 01282 if (DependentTemplateId) { 01283 // FIXME: the location information here isn't great. 01284 Diag(SS.getRange().getBegin(), 01285 diag::err_template_spec_needs_template_parameters) 01286 << TemplateId 01287 << SS.getRange(); 01288 } else { 01289 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header) 01290 << SS.getRange() 01291 << CodeModificationHint::CreateInsertion(FirstTemplateLoc, 01292 "template<> "); 01293 IsExplicitSpecialization = true; 01294 } 01295 return 0; 01296 } 01297 01298 // Check the template parameter list against its corresponding template-id. 01299 if (DependentTemplateId) { 01300 TemplateDecl *Template 01301 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl(); 01302 01303 if (ClassTemplateDecl *ClassTemplate 01304 = dyn_cast<ClassTemplateDecl>(Template)) { 01305 TemplateParameterList *ExpectedTemplateParams = 0; 01306 // Is this template-id naming the primary template? 01307 if (Context.hasSameType(TemplateId, 01308 ClassTemplate->getInjectedClassNameSpecialization(Context))) 01309 ExpectedTemplateParams = ClassTemplate->getTemplateParameters(); 01310 // ... or a partial specialization? 01311 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 01312 = ClassTemplate->findPartialSpecialization(TemplateId)) 01313 ExpectedTemplateParams = PartialSpec->getTemplateParameters(); 01314 01315 if (ExpectedTemplateParams) 01316 TemplateParameterListsAreEqual(ParamLists[Idx], 01317 ExpectedTemplateParams, 01318 true, TPL_TemplateMatch); 01319 } 01320 01321 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember); 01322 } else if (ParamLists[Idx]->size() > 0) 01323 Diag(ParamLists[Idx]->getTemplateLoc(), 01324 diag::err_template_param_list_matches_nontemplate) 01325 << TemplateId 01326 << ParamLists[Idx]->getSourceRange(); 01327 else 01328 IsExplicitSpecialization = true; 01329 } 01330 01331 // If there were at least as many template-ids as there were template 01332 // parameter lists, then there are no template parameter lists remaining for 01333 // the declaration itself. 01334 if (Idx >= NumParamLists) 01335 return 0; 01336 01337 // If there were too many template parameter lists, complain about that now. 01338 if (Idx != NumParamLists - 1) { 01339 while (Idx < NumParamLists - 1) { 01340 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0; 01341 Diag(ParamLists[Idx]->getTemplateLoc(), 01342 isExplicitSpecHeader? diag::warn_template_spec_extra_headers 01343 : diag::err_template_spec_extra_headers) 01344 << SourceRange(ParamLists[Idx]->getTemplateLoc(), 01345 ParamLists[Idx]->getRAngleLoc()); 01346 01347 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) { 01348 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(), 01349 diag::note_explicit_template_spec_does_not_need_header) 01350 << ExplicitSpecializationsInSpecifier.back(); 01351 ExplicitSpecializationsInSpecifier.pop_back(); 01352 } 01353 01354 ++Idx; 01355 } 01356 } 01357 01358 // Return the last template parameter list, which corresponds to the 01359 // entity being declared. 01360 return ParamLists[NumParamLists - 1]; 01361 } 01362 01363 QualType Sema::CheckTemplateIdType(TemplateName Name, 01364 SourceLocation TemplateLoc, 01365 const TemplateArgumentListInfo &TemplateArgs) { 01366 TemplateDecl *Template = Name.getAsTemplateDecl(); 01367 if (!Template) { 01368 // The template name does not resolve to a template, so we just 01369 // build a dependent template-id type. 01370 return Context.getTemplateSpecializationType(Name, TemplateArgs); 01371 } 01372 01373 // Check that the template argument list is well-formed for this 01374 // template. 01375 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(), 01376 TemplateArgs.size()); 01377 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, 01378 false, Converted)) 01379 return QualType(); 01380 01381 assert((Converted.structuredSize() == 01382 Template->getTemplateParameters()->size()) && 01383 "Converted template argument list is too short!"); 01384 01385 QualType CanonType; 01386 01387 if (Name.isDependent() || 01388 TemplateSpecializationType::anyDependentTemplateArguments( 01389 TemplateArgs)) { 01390 // This class template specialization is a dependent 01391 // type. Therefore, its canonical type is another class template 01392 // specialization type that contains all of the converted 01393 // arguments in canonical form. This ensures that, e.g., A<T> and 01394 // A<T, T> have identical types when A is declared as: 01395 // 01396 // template<typename T, typename U = T> struct A; 01397 TemplateName CanonName = Context.getCanonicalTemplateName(Name); 01398 CanonType = Context.getTemplateSpecializationType(CanonName, 01399 Converted.getFlatArguments(), 01400 Converted.flatSize()); 01401 01402 // FIXME: CanonType is not actually the canonical type, and unfortunately 01403 // it is a TemplateSpecializationType that we will never use again. 01404 // In the future, we need to teach getTemplateSpecializationType to only 01405 // build the canonical type and return that to us. 01406 CanonType = Context.getCanonicalType(CanonType); 01407 } else if (ClassTemplateDecl *ClassTemplate 01408 = dyn_cast<ClassTemplateDecl>(Template)) { 01409 // Find the class template specialization declaration that 01410 // corresponds to these arguments. 01411 llvm::FoldingSetNodeID ID; 01412 ClassTemplateSpecializationDecl::Profile(ID, 01413 Converted.getFlatArguments(), 01414 Converted.flatSize(), 01415 Context); 01416 void *InsertPos = 0; 01417 ClassTemplateSpecializationDecl *Decl 01418 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 01419 if (!Decl) { 01420 // This is the first time we have referenced this class template 01421 // specialization. Create the canonical declaration and add it to 01422 // the set of specializations. 01423 Decl = ClassTemplateSpecializationDecl::Create(Context, 01424 ClassTemplate->getDeclContext(), 01425 ClassTemplate->getLocation(), 01426 ClassTemplate, 01427 Converted, 0); 01428 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos); 01429 Decl->setLexicalDeclContext(CurContext); 01430 } 01431 01432 CanonType = Context.getTypeDeclType(Decl); 01433 assert(isa<RecordType>(CanonType) && 01434 "type of non-dependent specialization is not a RecordType"); 01435 } 01436 01437 // Build the fully-sugared type for this class template 01438 // specialization, which refers back to the class template 01439 // specialization we created or found. 01440 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); 01441 } 01442 01443 Action::TypeResult 01444 Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc, 01445 SourceLocation LAngleLoc, 01446 ASTTemplateArgsPtr TemplateArgsIn, 01447 SourceLocation RAngleLoc) { 01448 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 01449 01450 // Translate the parser's template argument list in our AST format. 01451 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 01452 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 01453 01454 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 01455 TemplateArgsIn.release(); 01456 01457 if (Result.isNull()) 01458 return true; 01459 01460 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result); 01461 TemplateSpecializationTypeLoc TL 01462 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 01463 TL.setTemplateNameLoc(TemplateLoc); 01464 TL.setLAngleLoc(LAngleLoc); 01465 TL.setRAngleLoc(RAngleLoc); 01466 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 01467 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 01468 01469 return CreateLocInfoType(Result, DI).getAsOpaquePtr(); 01470 } 01471 01472 Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult, 01473 TagUseKind TUK, 01474 DeclSpec::TST TagSpec, 01475 SourceLocation TagLoc) { 01476 if (TypeResult.isInvalid()) 01477 return Sema::TypeResult(); 01478 01479 // FIXME: preserve source info, ideally without copying the DI. 01480 TypeSourceInfo *DI; 01481 QualType Type = GetTypeFromParser(TypeResult.get(), &DI); 01482 01483 // Verify the tag specifier. 01484 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec); 01485 01486 if (const RecordType *RT = Type->getAs<RecordType>()) { 01487 RecordDecl *D = RT->getDecl(); 01488 01489 IdentifierInfo *Id = D->getIdentifier(); 01490 assert(Id && "templated class must have an identifier"); 01491 01492 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) { 01493 Diag(TagLoc, diag::err_use_with_wrong_tag) 01494 << Type 01495 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc), 01496 D->getKindName()); 01497 Diag(D->getLocation(), diag::note_previous_use); 01498 } 01499 } 01500 01501 QualType ElabType = Context.getElaboratedType(Type, TagKind); 01502 01503 return ElabType.getAsOpaquePtr(); 01504 } 01505 01506 Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, 01507 LookupResult &R, 01508 bool RequiresADL, 01509 const TemplateArgumentListInfo &TemplateArgs) { 01510 // FIXME: Can we do any checking at this point? I guess we could check the 01511 // template arguments that we have against the template name, if the template 01512 // name refers to a single template. That's not a terribly common case, 01513 // though. 01514 01515 // These should be filtered out by our callers. 01516 assert(!R.empty() && "empty lookup results when building templateid"); 01517 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid"); 01518 01519 NestedNameSpecifier *Qualifier = 0; 01520 SourceRange QualifierRange; 01521 if (SS.isSet()) { 01522 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 01523 QualifierRange = SS.getRange(); 01524 } 01525 01526 // We don't want lookup warnings at this point. 01527 R.suppressDiagnostics(); 01528 01529 bool Dependent 01530 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 01531 &TemplateArgs); 01532 UnresolvedLookupExpr *ULE 01533 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(), 01534 Qualifier, QualifierRange, 01535 R.getLookupName(), R.getNameLoc(), 01536 RequiresADL, TemplateArgs); 01537 ULE->addDecls(R.begin(), R.end()); 01538 01539 return Owned(ULE); 01540 } 01541 01542 // We actually only call this from template instantiation. 01543 Sema::OwningExprResult 01544 Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS, 01545 DeclarationName Name, 01546 SourceLocation NameLoc, 01547 const TemplateArgumentListInfo &TemplateArgs) { 01548 DeclContext *DC; 01549 if (!(DC = computeDeclContext(SS, false)) || 01550 DC->isDependentContext() || 01551 RequireCompleteDeclContext(SS)) 01552 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs); 01553 01554 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName); 01555 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false); 01556 01557 if (R.isAmbiguous()) 01558 return ExprError(); 01559 01560 if (R.empty()) { 01561 Diag(NameLoc, diag::err_template_kw_refers_to_non_template) 01562 << Name << SS.getRange(); 01563 return ExprError(); 01564 } 01565 01566 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) { 01567 Diag(NameLoc, diag::err_template_kw_refers_to_class_template) 01568 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange(); 01569 Diag(Temp->getLocation(), diag::note_referenced_class_template); 01570 return ExprError(); 01571 } 01572 01573 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs); 01574 } 01575 01576 /// \brief Form a dependent template name. 01577 /// 01578 /// This action forms a dependent template name given the template 01579 /// name and its (presumably dependent) scope specifier. For 01580 /// example, given "MetaFun::template apply", the scope specifier \p 01581 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location 01582 /// of the "template" keyword, and "apply" is the \p Name. 01583 Sema::TemplateTy 01584 Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc, 01585 const CXXScopeSpec &SS, 01586 UnqualifiedId &Name, 01587 TypeTy *ObjectType, 01588 bool EnteringContext) { 01589 DeclContext *LookupCtx = 0; 01590 if (SS.isSet()) 01591 LookupCtx = computeDeclContext(SS, EnteringContext); 01592 if (!LookupCtx && ObjectType) 01593 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType)); 01594 if (LookupCtx) { 01595 // C++0x [temp.names]p5: 01596 // If a name prefixed by the keyword template is not the name of 01597 // a template, the program is ill-formed. [Note: the keyword 01598 // template may not be applied to non-template members of class 01599 // templates. -end note ] [ Note: as is the case with the 01600 // typename prefix, the template prefix is allowed in cases 01601 // where it is not strictly necessary; i.e., when the 01602 // nested-name-specifier or the expression on the left of the -> 01603 // or . is not dependent on a template-parameter, or the use 01604 // does not appear in the scope of a template. -end note] 01605 // 01606 // Note: C++03 was more strict here, because it banned the use of 01607 // the "template" keyword prior to a template-name that was not a 01608 // dependent name. C++ DR468 relaxed this requirement (the 01609 // "template" keyword is now permitted). We follow the C++0x 01610 // rules, even in C++03 mode, retroactively applying the DR. 01611 TemplateTy Template; 01612 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType, 01613 EnteringContext, Template); 01614 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() && 01615 isa<CXXRecordDecl>(LookupCtx) && 01616 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) { 01617 // This is a dependent template. 01618 } else if (TNK == TNK_Non_template) { 01619 Diag(Name.getSourceRange().getBegin(), 01620 diag::err_template_kw_refers_to_non_template) 01621 << GetNameFromUnqualifiedId(Name) 01622 << Name.getSourceRange(); 01623 return TemplateTy(); 01624 } else { 01625 // We found something; return it. 01626 return Template; 01627 } 01628 } 01629 01630 NestedNameSpecifier *Qualifier 01631 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 01632 01633 switch (Name.getKind()) { 01634 case UnqualifiedId::IK_Identifier: 01635 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, 01636 Name.Identifier)); 01637 01638 case UnqualifiedId::IK_OperatorFunctionId: 01639 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, 01640 Name.OperatorFunctionId.Operator)); 01641 01642 case UnqualifiedId::IK_LiteralOperatorId: 01643 assert(false && "We don't support these; Parse shouldn't have allowed propagation"); 01644 01645 default: 01646 break; 01647 } 01648 01649 Diag(Name.getSourceRange().getBegin(), 01650 diag::err_template_kw_refers_to_non_template) 01651 << GetNameFromUnqualifiedId(Name) 01652 << Name.getSourceRange(); 01653 return TemplateTy(); 01654 } 01655 01656 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 01657 const TemplateArgumentLoc &AL, 01658 TemplateArgumentListBuilder &Converted) { 01659 const TemplateArgument &Arg = AL.getArgument(); 01660 01661 // Check template type parameter. 01662 if (Arg.getKind() != TemplateArgument::Type) { 01663 // C++ [temp.arg.type]p1: 01664 // A template-argument for a template-parameter which is a 01665 // type shall be a type-id. 01666 01667 // We have a template type parameter but the template argument 01668 // is not a type. 01669 SourceRange SR = AL.getSourceRange(); 01670 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; 01671 Diag(Param->getLocation(), diag::note_template_param_here); 01672 01673 return true; 01674 } 01675 01676 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo())) 01677 return true; 01678 01679 // Add the converted template type argument. 01680 Converted.Append( 01681 TemplateArgument(Context.getCanonicalType(Arg.getAsType()))); 01682 return false; 01683 } 01684 01685 /// \brief Substitute template arguments into the default template argument for 01686 /// the given template type parameter. 01687 /// 01688 /// \param SemaRef the semantic analysis object for which we are performing 01689 /// the substitution. 01690 /// 01691 /// \param Template the template that we are synthesizing template arguments 01692 /// for. 01693 /// 01694 /// \param TemplateLoc the location of the template name that started the 01695 /// template-id we are checking. 01696 /// 01697 /// \param RAngleLoc the location of the right angle bracket ('>') that 01698 /// terminates the template-id. 01699 /// 01700 /// \param Param the template template parameter whose default we are 01701 /// substituting into. 01702 /// 01703 /// \param Converted the list of template arguments provided for template 01704 /// parameters that precede \p Param in the template parameter list. 01705 /// 01706 /// \returns the substituted template argument, or NULL if an error occurred. 01707 static TypeSourceInfo * 01708 SubstDefaultTemplateArgument(Sema &SemaRef, 01709 TemplateDecl *Template, 01710 SourceLocation TemplateLoc, 01711 SourceLocation RAngleLoc, 01712 TemplateTypeParmDecl *Param, 01713 TemplateArgumentListBuilder &Converted) { 01714 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); 01715 01716 // If the argument type is dependent, instantiate it now based 01717 // on the previously-computed template arguments. 01718 if (ArgType->getType()->isDependentType()) { 01719 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted, 01720 /*TakeArgs=*/false); 01721 01722 MultiLevelTemplateArgumentList AllTemplateArgs 01723 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 01724 01725 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 01726 Template, Converted.getFlatArguments(), 01727 Converted.flatSize(), 01728 SourceRange(TemplateLoc, RAngleLoc)); 01729 01730 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs, 01731 Param->getDefaultArgumentLoc(), 01732 Param->getDeclName()); 01733 } 01734 01735 return ArgType; 01736 } 01737 01738 /// \brief Substitute template arguments into the default template argument for 01739 /// the given non-type template parameter. 01740 /// 01741 /// \param SemaRef the semantic analysis object for which we are performing 01742 /// the substitution. 01743 /// 01744 /// \param Template the template that we are synthesizing template arguments 01745 /// for. 01746 /// 01747 /// \param TemplateLoc the location of the template name that started the 01748 /// template-id we are checking. 01749 /// 01750 /// \param RAngleLoc the location of the right angle bracket ('>') that 01751 /// terminates the template-id. 01752 /// 01753 /// \param Param the non-type template parameter whose default we are 01754 /// substituting into. 01755 /// 01756 /// \param Converted the list of template arguments provided for template 01757 /// parameters that precede \p Param in the template parameter list. 01758 /// 01759 /// \returns the substituted template argument, or NULL if an error occurred. 01760 static Sema::OwningExprResult 01761 SubstDefaultTemplateArgument(Sema &SemaRef, 01762 TemplateDecl *Template, 01763 SourceLocation TemplateLoc, 01764 SourceLocation RAngleLoc, 01765 NonTypeTemplateParmDecl *Param, 01766 TemplateArgumentListBuilder &Converted) { 01767 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted, 01768 /*TakeArgs=*/false); 01769 01770 MultiLevelTemplateArgumentList AllTemplateArgs 01771 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 01772 01773 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 01774 Template, Converted.getFlatArguments(), 01775 Converted.flatSize(), 01776 SourceRange(TemplateLoc, RAngleLoc)); 01777 01778 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs); 01779 } 01780 01781 /// \brief Substitute template arguments into the default template argument for 01782 /// the given template template parameter. 01783 /// 01784 /// \param SemaRef the semantic analysis object for which we are performing 01785 /// the substitution. 01786 /// 01787 /// \param Template the template that we are synthesizing template arguments 01788 /// for. 01789 /// 01790 /// \param TemplateLoc the location of the template name that started the 01791 /// template-id we are checking. 01792 /// 01793 /// \param RAngleLoc the location of the right angle bracket ('>') that 01794 /// terminates the template-id. 01795 /// 01796 /// \param Param the template template parameter whose default we are 01797 /// substituting into. 01798 /// 01799 /// \param Converted the list of template arguments provided for template 01800 /// parameters that precede \p Param in the template parameter list. 01801 /// 01802 /// \returns the substituted template argument, or NULL if an error occurred. 01803 static TemplateName 01804 SubstDefaultTemplateArgument(Sema &SemaRef, 01805 TemplateDecl *Template, 01806 SourceLocation TemplateLoc, 01807 SourceLocation RAngleLoc, 01808 TemplateTemplateParmDecl *Param, 01809 TemplateArgumentListBuilder &Converted) { 01810 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted, 01811 /*TakeArgs=*/false); 01812 01813 MultiLevelTemplateArgumentList AllTemplateArgs 01814 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 01815 01816 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 01817 Template, Converted.getFlatArguments(), 01818 Converted.flatSize(), 01819 SourceRange(TemplateLoc, RAngleLoc)); 01820 01821 return SemaRef.SubstTemplateName( 01822 Param->getDefaultArgument().getArgument().getAsTemplate(), 01823 Param->getDefaultArgument().getTemplateNameLoc(), 01824 AllTemplateArgs); 01825 } 01826 01827 /// \brief If the given template parameter has a default template 01828 /// argument, substitute into that default template argument and 01829 /// return the corresponding template argument. 01830 TemplateArgumentLoc 01831 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 01832 SourceLocation TemplateLoc, 01833 SourceLocation RAngleLoc, 01834 Decl *Param, 01835 TemplateArgumentListBuilder &Converted) { 01836 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { 01837 if (!TypeParm->hasDefaultArgument()) 01838 return TemplateArgumentLoc(); 01839 01840 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template, 01841 TemplateLoc, 01842 RAngleLoc, 01843 TypeParm, 01844 Converted); 01845 if (DI) 01846 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); 01847 01848 return TemplateArgumentLoc(); 01849 } 01850 01851 if (NonTypeTemplateParmDecl *NonTypeParm 01852 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 01853 if (!NonTypeParm->hasDefaultArgument()) 01854 return TemplateArgumentLoc(); 01855 01856 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template, 01857 TemplateLoc, 01858 RAngleLoc, 01859 NonTypeParm, 01860 Converted); 01861 if (Arg.isInvalid()) 01862 return TemplateArgumentLoc(); 01863 01864 Expr *ArgE = Arg.takeAs<Expr>(); 01865 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); 01866 } 01867 01868 TemplateTemplateParmDecl *TempTempParm 01869 = cast<TemplateTemplateParmDecl>(Param); 01870 if (!TempTempParm->hasDefaultArgument()) 01871 return TemplateArgumentLoc(); 01872 01873 TemplateName TName = SubstDefaultTemplateArgument(*this, Template, 01874 TemplateLoc, 01875 RAngleLoc, 01876 TempTempParm, 01877 Converted); 01878 if (TName.isNull()) 01879 return TemplateArgumentLoc(); 01880 01881 return TemplateArgumentLoc(TemplateArgument(TName), 01882 TempTempParm->getDefaultArgument().getTemplateQualifierRange(), 01883 TempTempParm->getDefaultArgument().getTemplateNameLoc()); 01884 } 01885 01886 /// \brief Check that the given template argument corresponds to the given 01887 /// template parameter. 01888 bool Sema::CheckTemplateArgument(NamedDecl *Param, 01889 const TemplateArgumentLoc &Arg, 01890 TemplateDecl *Template, 01891 SourceLocation TemplateLoc, 01892 SourceLocation RAngleLoc, 01893 TemplateArgumentListBuilder &Converted) { 01894 // Check template type parameters. 01895 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 01896 return CheckTemplateTypeArgument(TTP, Arg, Converted); 01897 01898 // Check non-type template parameters. 01899 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { 01900 // Do substitution on the type of the non-type template parameter 01901 // with the template arguments we've seen thus far. 01902 QualType NTTPType = NTTP->getType(); 01903 if (NTTPType->isDependentType()) { 01904 // Do substitution on the type of the non-type template parameter. 01905 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 01906 NTTP, Converted.getFlatArguments(), 01907 Converted.flatSize(), 01908 SourceRange(TemplateLoc, RAngleLoc)); 01909 01910 TemplateArgumentList TemplateArgs(Context, Converted, 01911 /*TakeArgs=*/false); 01912 NTTPType = SubstType(NTTPType, 01913 MultiLevelTemplateArgumentList(TemplateArgs), 01914 NTTP->getLocation(), 01915 NTTP->getDeclName()); 01916 // If that worked, check the non-type template parameter type 01917 // for validity. 01918 if (!NTTPType.isNull()) 01919 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 01920 NTTP->getLocation()); 01921 if (NTTPType.isNull()) 01922 return true; 01923 } 01924 01925 switch (Arg.getArgument().getKind()) { 01926 case TemplateArgument::Null: 01927 assert(false && "Should never see a NULL template argument here"); 01928 return true; 01929 01930 case TemplateArgument::Expression: { 01931 Expr *E = Arg.getArgument().getAsExpr(); 01932 TemplateArgument Result; 01933 if (CheckTemplateArgument(NTTP, NTTPType, E, Result)) 01934 return true; 01935 01936 Converted.Append(Result); 01937 break; 01938 } 01939 01940 case TemplateArgument::Declaration: 01941 case TemplateArgument::Integral: 01942 // We've already checked this template argument, so just copy 01943 // it to the list of converted arguments. 01944 Converted.Append(Arg.getArgument()); 01945 break; 01946 01947 case TemplateArgument::Template: 01948 // We were given a template template argument. It may not be ill-formed; 01949 // see below. 01950 if (DependentTemplateName *DTN 01951 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) { 01952 // We have a template argument such as \c T::template X, which we 01953 // parsed as a template template argument. However, since we now 01954 // know that we need a non-type template argument, convert this 01955 // template name into an expression. 01956 Expr *E = DependentScopeDeclRefExpr::Create(Context, 01957 DTN->getQualifier(), 01958 Arg.getTemplateQualifierRange(), 01959 DTN->getIdentifier(), 01960 Arg.getTemplateNameLoc()); 01961 01962 TemplateArgument Result; 01963 if (CheckTemplateArgument(NTTP, NTTPType, E, Result)) 01964 return true; 01965 01966 Converted.Append(Result); 01967 break; 01968 } 01969 01970 // We have a template argument that actually does refer to a class 01971 // template, template alias, or template template parameter, and 01972 // therefore cannot be a non-type template argument. 01973 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) 01974 << Arg.getSourceRange(); 01975 01976 Diag(Param->getLocation(), diag::note_template_param_here); 01977 return true; 01978 01979 case TemplateArgument::Type: { 01980 // We have a non-type template parameter but the template 01981 // argument is a type. 01982 01983 // C++ [temp.arg]p2: 01984 // In a template-argument, an ambiguity between a type-id and 01985 // an expression is resolved to a type-id, regardless of the 01986 // form of the corresponding template-parameter. 01987 // 01988 // We warn specifically about this case, since it can be rather 01989 // confusing for users. 01990 QualType T = Arg.getArgument().getAsType(); 01991 SourceRange SR = Arg.getSourceRange(); 01992 if (T->isFunctionType()) 01993 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; 01994 else 01995 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; 01996 Diag(Param->getLocation(), diag::note_template_param_here); 01997 return true; 01998 } 01999 02000 case TemplateArgument::Pack: 02001 llvm_unreachable("Caller must expand template argument packs"); 02002 break; 02003 } 02004 02005 return false; 02006 } 02007 02008 02009 // Check template template parameters. 02010 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); 02011 02012 // Substitute into the template parameter list of the template 02013 // template parameter, since previously-supplied template arguments 02014 // may appear within the template template parameter. 02015 { 02016 // Set up a template instantiation context. 02017 LocalInstantiationScope Scope(*this); 02018 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 02019 TempParm, Converted.getFlatArguments(), 02020 Converted.flatSize(), 02021 SourceRange(TemplateLoc, RAngleLoc)); 02022 02023 TemplateArgumentList TemplateArgs(Context, Converted, 02024 /*TakeArgs=*/false); 02025 TempParm = cast_or_null<TemplateTemplateParmDecl>( 02026 SubstDecl(TempParm, CurContext, 02027 MultiLevelTemplateArgumentList(TemplateArgs))); 02028 if (!TempParm) 02029 return true; 02030 02031 // FIXME: TempParam is leaked. 02032 } 02033 02034 switch (Arg.getArgument().getKind()) { 02035 case TemplateArgument::Null: 02036 assert(false && "Should never see a NULL template argument here"); 02037 return true; 02038 02039 case TemplateArgument::Template: 02040 if (CheckTemplateArgument(TempParm, Arg)) 02041 return true; 02042 02043 Converted.Append(Arg.getArgument()); 02044 break; 02045 02046 case TemplateArgument::Expression: 02047 case TemplateArgument::Type: 02048 // We have a template template parameter but the template 02049 // argument does not refer to a template. 02050 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template); 02051 return true; 02052 02053 case TemplateArgument::Declaration: 02054 llvm_unreachable( 02055 "Declaration argument with template template parameter"); 02056 break; 02057 case TemplateArgument::Integral: 02058 llvm_unreachable( 02059 "Integral argument with template template parameter"); 02060 break; 02061 02062 case TemplateArgument::Pack: 02063 llvm_unreachable("Caller must expand template argument packs"); 02064 break; 02065 } 02066 02067 return false; 02068 } 02069 02070 /// \brief Check that the given template argument list is well-formed 02071 /// for specializing the given template. 02072 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template, 02073 SourceLocation TemplateLoc, 02074 const TemplateArgumentListInfo &TemplateArgs, 02075 bool PartialTemplateArgs, 02076 TemplateArgumentListBuilder &Converted) { 02077 TemplateParameterList *Params = Template->getTemplateParameters(); 02078 unsigned NumParams = Params->size(); 02079 unsigned NumArgs = TemplateArgs.size(); 02080 bool Invalid = false; 02081 02082 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc(); 02083 02084 bool HasParameterPack = 02085 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack(); 02086 02087 if ((NumArgs > NumParams && !HasParameterPack) || 02088 (NumArgs < Params->getMinRequiredArguments() && 02089 !PartialTemplateArgs)) { 02090 // FIXME: point at either the first arg beyond what we can handle, 02091 // or the '>', depending on whether we have too many or too few 02092 // arguments. 02093 SourceRange Range; 02094 if (NumArgs > NumParams) 02095 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc); 02096 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 02097 << (NumArgs > NumParams) 02098 << (isa<ClassTemplateDecl>(Template)? 0 : 02099 isa<FunctionTemplateDecl>(Template)? 1 : 02100 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 02101 << Template << Range; 02102 Diag(Template->getLocation(), diag::note_template_decl_here) 02103 << Params->getSourceRange(); 02104 Invalid = true; 02105 } 02106 02107 // C++ [temp.arg]p1: 02108 // [...] The type and form of each template-argument specified in 02109 // a template-id shall match the type and form specified for the 02110 // corresponding parameter declared by the template in its 02111 // template-parameter-list. 02112 unsigned ArgIdx = 0; 02113 for (TemplateParameterList::iterator Param = Params->begin(), 02114 ParamEnd = Params->end(); 02115 Param != ParamEnd; ++Param, ++ArgIdx) { 02116 if (ArgIdx > NumArgs && PartialTemplateArgs) 02117 break; 02118 02119 // If we have a template parameter pack, check every remaining template 02120 // argument against that template parameter pack. 02121 if ((*Param)->isTemplateParameterPack()) { 02122 Converted.BeginPack(); 02123 for (; ArgIdx < NumArgs; ++ArgIdx) { 02124 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 02125 TemplateLoc, RAngleLoc, Converted)) { 02126 Invalid = true; 02127 break; 02128 } 02129 } 02130 Converted.EndPack(); 02131 continue; 02132 } 02133 02134 if (ArgIdx < NumArgs) { 02135 // Check the template argument we were given. 02136 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 02137 TemplateLoc, RAngleLoc, Converted)) 02138 return true; 02139 02140 continue; 02141 } 02142 02143 // We have a default template argument that we will use. 02144 TemplateArgumentLoc Arg; 02145 02146 // Retrieve the default template argument from the template 02147 // parameter. For each kind of template parameter, we substitute the 02148 // template arguments provided thus far and any "outer" template arguments 02149 // (when the template parameter was part of a nested template) into 02150 // the default argument. 02151 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 02152 if (!TTP->hasDefaultArgument()) { 02153 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 02154 break; 02155 } 02156 02157 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this, 02158 Template, 02159 TemplateLoc, 02160 RAngleLoc, 02161 TTP, 02162 Converted); 02163 if (!ArgType) 02164 return true; 02165 02166 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), 02167 ArgType); 02168 } else if (NonTypeTemplateParmDecl *NTTP 02169 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 02170 if (!NTTP->hasDefaultArgument()) { 02171 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 02172 break; 02173 } 02174 02175 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template, 02176 TemplateLoc, 02177 RAngleLoc, 02178 NTTP, 02179 Converted); 02180 if (E.isInvalid()) 02181 return true; 02182 02183 Expr *Ex = E.takeAs<Expr>(); 02184 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); 02185 } else { 02186 TemplateTemplateParmDecl *TempParm 02187 = cast<TemplateTemplateParmDecl>(*Param); 02188 02189 if (!TempParm->hasDefaultArgument()) { 02190 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 02191 break; 02192 } 02193 02194 TemplateName Name = SubstDefaultTemplateArgument(*this, Template, 02195 TemplateLoc, 02196 RAngleLoc, 02197 TempParm, 02198 Converted); 02199 if (Name.isNull()) 02200 return true; 02201 02202 Arg = TemplateArgumentLoc(TemplateArgument(Name), 02203 TempParm->getDefaultArgument().getTemplateQualifierRange(), 02204 TempParm->getDefaultArgument().getTemplateNameLoc()); 02205 } 02206 02207 // Introduce an instantiation record that describes where we are using 02208 // the default template argument. 02209 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param, 02210 Converted.getFlatArguments(), 02211 Converted.flatSize(), 02212 SourceRange(TemplateLoc, RAngleLoc)); 02213 02214 // Check the default template argument. 02215 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, 02216 RAngleLoc, Converted)) 02217 return true; 02218 } 02219 02220 return Invalid; 02221 } 02222 02223 /// \brief Check a template argument against its corresponding 02224 /// template type parameter. 02225 /// 02226 /// This routine implements the semantics of C++ [temp.arg.type]. It 02227 /// returns true if an error occurred, and false otherwise. 02228 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 02229 TypeSourceInfo *ArgInfo) { 02230 assert(ArgInfo && "invalid TypeSourceInfo"); 02231 QualType Arg = ArgInfo->getType(); 02232 02233 // C++ [temp.arg.type]p2: 02234 // A local type, a type with no linkage, an unnamed type or a type 02235 // compounded from any of these types shall not be used as a 02236 // template-argument for a template type-parameter. 02237 // 02238 // FIXME: Perform the recursive and no-linkage type checks. 02239 const TagType *Tag = 0; 02240 if (const EnumType *EnumT = Arg->getAs<EnumType>()) 02241 Tag = EnumT; 02242 else if (const RecordType *RecordT = Arg->getAs<RecordType>()) 02243 Tag = RecordT; 02244 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) { 02245 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange(); 02246 return Diag(SR.getBegin(), diag::err_template_arg_local_type) 02247 << QualType(Tag, 0) << SR; 02248 } else if (Tag && !Tag->getDecl()->getDeclName() && 02249 !Tag->getDecl()->getTypedefForAnonDecl()) { 02250 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange(); 02251 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR; 02252 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here); 02253 return true; 02254 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) { 02255 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange(); 02256 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR; 02257 } 02258 02259 return false; 02260 } 02261 02262 /// \brief Checks whether the given template argument is the address 02263 /// of an object or function according to C++ [temp.arg.nontype]p1. 02264 bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg, 02265 NamedDecl *&Entity) { 02266 bool Invalid = false; 02267 02268 // See through any implicit casts we added to fix the type. 02269 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 02270 Arg = Cast->getSubExpr(); 02271 02272 // C++0x allows nullptr, and there's no further checking to be done for that. 02273 if (Arg->getType()->isNullPtrType()) 02274 return false; 02275 02276 // C++ [temp.arg.nontype]p1: 02277 // 02278 // A template-argument for a non-type, non-template 02279 // template-parameter shall be one of: [...] 02280 // 02281 // -- the address of an object or function with external 02282 // linkage, including function templates and function 02283 // template-ids but excluding non-static class members, 02284 // expressed as & id-expression where the & is optional if 02285 // the name refers to a function or array, or if the 02286 // corresponding template-parameter is a reference; or 02287 DeclRefExpr *DRE = 0; 02288 02289 // Ignore (and complain about) any excess parentheses. 02290 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 02291 if (!Invalid) { 02292 Diag(Arg->getSourceRange().getBegin(), 02293 diag::err_template_arg_extra_parens) 02294 << Arg->getSourceRange(); 02295 Invalid = true; 02296 } 02297 02298 Arg = Parens->getSubExpr(); 02299 } 02300 02301 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 02302 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 02303 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 02304 } else 02305 DRE = dyn_cast<DeclRefExpr>(Arg); 02306 02307 if (!DRE) 02308 return Diag(Arg->getSourceRange().getBegin(), 02309 diag::err_template_arg_not_decl_ref) 02310 << Arg->getSourceRange(); 02311 02312 // Stop checking the precise nature of the argument if it is value dependent, 02313 // it should be checked when instantiated. 02314 if (Arg->isValueDependent()) 02315 return false; 02316 02317 if (!isa<ValueDecl>(DRE->getDecl())) 02318 return Diag(Arg->getSourceRange().getBegin(), 02319 diag::err_template_arg_not_object_or_func_form) 02320 << Arg->getSourceRange(); 02321 02322 // Cannot refer to non-static data members 02323 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) 02324 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field) 02325 << Field << Arg->getSourceRange(); 02326 02327 // Cannot refer to non-static member functions 02328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl())) 02329 if (!Method->isStatic()) 02330 return Diag(Arg->getSourceRange().getBegin(), 02331 diag::err_template_arg_method) 02332 << Method << Arg->getSourceRange(); 02333 02334 // Functions must have external linkage. 02335 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) { 02336 if (!isExternalLinkage(Func->getLinkage())) { 02337 Diag(Arg->getSourceRange().getBegin(), 02338 diag::err_template_arg_function_not_extern) 02339 << Func << Arg->getSourceRange(); 02340 Diag(Func->getLocation(), diag::note_template_arg_internal_object) 02341 << true; 02342 return true; 02343 } 02344 02345 // Okay: we've named a function with external linkage. 02346 Entity = Func; 02347 return Invalid; 02348 } 02349 02350 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 02351 if (!isExternalLinkage(Var->getLinkage())) { 02352 Diag(Arg->getSourceRange().getBegin(), 02353 diag::err_template_arg_object_not_extern) 02354 << Var << Arg->getSourceRange(); 02355 Diag(Var->getLocation(), diag::note_template_arg_internal_object) 02356 << true; 02357 return true; 02358 } 02359 02360 // Okay: we've named an object with external linkage 02361 Entity = Var; 02362 return Invalid; 02363 } 02364 02365 // We found something else, but we don't know specifically what it is. 02366 Diag(Arg->getSourceRange().getBegin(), 02367 diag::err_template_arg_not_object_or_func) 02368 << Arg->getSourceRange(); 02369 Diag(DRE->getDecl()->getLocation(), 02370 diag::note_template_arg_refers_here); 02371 return true; 02372 } 02373 02374 /// \brief Checks whether the given template argument is a pointer to 02375 /// member constant according to C++ [temp.arg.nontype]p1. 02376 bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, 02377 TemplateArgument &Converted) { 02378 bool Invalid = false; 02379 02380 // See through any implicit casts we added to fix the type. 02381 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 02382 Arg = Cast->getSubExpr(); 02383 02384 // C++0x allows nullptr, and there's no further checking to be done for that. 02385 if (Arg->getType()->isNullPtrType()) 02386 return false; 02387 02388 // C++ [temp.arg.nontype]p1: 02389 // 02390 // A template-argument for a non-type, non-template 02391 // template-parameter shall be one of: [...] 02392 // 02393 // -- a pointer to member expressed as described in 5.3.1. 02394 DeclRefExpr *DRE = 0; 02395 02396 // Ignore (and complain about) any excess parentheses. 02397 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 02398 if (!Invalid) { 02399 Diag(Arg->getSourceRange().getBegin(), 02400 diag::err_template_arg_extra_parens) 02401 << Arg->getSourceRange(); 02402 Invalid = true; 02403 } 02404 02405 Arg = Parens->getSubExpr(); 02406 } 02407 02408 // A pointer-to-member constant written &Class::member. 02409 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 02410 if (UnOp->getOpcode() == UnaryOperator::AddrOf) { 02411 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 02412 if (DRE && !DRE->getQualifier()) 02413 DRE = 0; 02414 } 02415 } 02416 // A constant of pointer-to-member type. 02417 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { 02418 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) { 02419 if (VD->getType()->isMemberPointerType()) { 02420 if (isa<NonTypeTemplateParmDecl>(VD) || 02421 (isa<VarDecl>(VD) && 02422 Context.getCanonicalType(VD->getType()).isConstQualified())) { 02423 if (Arg->isTypeDependent() || Arg->isValueDependent()) 02424 Converted = TemplateArgument(Arg->Retain()); 02425 else 02426 Converted = TemplateArgument(VD->getCanonicalDecl()); 02427 return Invalid; 02428 } 02429 } 02430 } 02431 02432 DRE = 0; 02433 } 02434 02435 if (!DRE) 02436 return Diag(Arg->getSourceRange().getBegin(), 02437 diag::err_template_arg_not_pointer_to_member_form) 02438 << Arg->getSourceRange(); 02439 02440 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) { 02441 assert((isa<FieldDecl>(DRE->getDecl()) || 02442 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && 02443 "Only non-static member pointers can make it here"); 02444 02445 // Okay: this is the address of a non-static member, and therefore 02446 // a member pointer constant. 02447 if (Arg->isTypeDependent() || Arg->isValueDependent()) 02448 Converted = TemplateArgument(Arg->Retain()); 02449 else 02450 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl()); 02451 return Invalid; 02452 } 02453 02454 // We found something else, but we don't know specifically what it is. 02455 Diag(Arg->getSourceRange().getBegin(), 02456 diag::err_template_arg_not_pointer_to_member_form) 02457 << Arg->getSourceRange(); 02458 Diag(DRE->getDecl()->getLocation(), 02459 diag::note_template_arg_refers_here); 02460 return true; 02461 } 02462 02463 /// \brief Check a template argument against its corresponding 02464 /// non-type template parameter. 02465 /// 02466 /// This routine implements the semantics of C++ [temp.arg.nontype]. 02467 /// It returns true if an error occurred, and false otherwise. \p 02468 /// InstantiatedParamType is the type of the non-type template 02469 /// parameter after it has been instantiated. 02470 /// 02471 /// If no error was detected, Converted receives the converted template argument. 02472 bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 02473 QualType InstantiatedParamType, Expr *&Arg, 02474 TemplateArgument &Converted) { 02475 SourceLocation StartLoc = Arg->getSourceRange().getBegin(); 02476 02477 // If either the parameter has a dependent type or the argument is 02478 // type-dependent, there's nothing we can check now. 02479 // FIXME: Add template argument to Converted! 02480 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) { 02481 // FIXME: Produce a cloned, canonical expression? 02482 Converted = TemplateArgument(Arg); 02483 return false; 02484 } 02485 02486 // C++ [temp.arg.nontype]p5: 02487 // The following conversions are performed on each expression used 02488 // as a non-type template-argument. If a non-type 02489 // template-argument cannot be converted to the type of the 02490 // corresponding template-parameter then the program is 02491 // ill-formed. 02492 // 02493 // -- for a non-type template-parameter of integral or 02494 // enumeration type, integral promotions (4.5) and integral 02495 // conversions (4.7) are applied. 02496 QualType ParamType = InstantiatedParamType; 02497 QualType ArgType = Arg->getType(); 02498 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) { 02499 // C++ [temp.arg.nontype]p1: 02500 // A template-argument for a non-type, non-template 02501 // template-parameter shall be one of: 02502 // 02503 // -- an integral constant-expression of integral or enumeration 02504 // type; or 02505 // -- the name of a non-type template-parameter; or 02506 SourceLocation NonConstantLoc; 02507 llvm::APSInt Value; 02508 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) { 02509 Diag(Arg->getSourceRange().getBegin(), 02510 diag::err_template_arg_not_integral_or_enumeral) 02511 << ArgType << Arg->getSourceRange(); 02512 Diag(Param->getLocation(), diag::note_template_param_here); 02513 return true; 02514 } else if (!Arg->isValueDependent() && 02515 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) { 02516 Diag(NonConstantLoc, diag::err_template_arg_not_ice) 02517 << ArgType << Arg->getSourceRange(); 02518 return true; 02519 } 02520 02521 // FIXME: We need some way to more easily get the unqualified form 02522 // of the types without going all the way to the 02523 // canonical type. 02524 if (Context.getCanonicalType(ParamType).getCVRQualifiers()) 02525 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType(); 02526 if (Context.getCanonicalType(ArgType).getCVRQualifiers()) 02527 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType(); 02528 02529 // Try to convert the argument to the parameter's type. 02530 if (Context.hasSameType(ParamType, ArgType)) { 02531 // Okay: no conversion necessary 02532 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 02533 !ParamType->isEnumeralType()) { 02534 // This is an integral promotion or conversion. 02535 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast); 02536 } else { 02537 // We can't perform this conversion. 02538 Diag(Arg->getSourceRange().getBegin(), 02539 diag::err_template_arg_not_convertible) 02540 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 02541 Diag(Param->getLocation(), diag::note_template_param_here); 02542 return true; 02543 } 02544 02545 QualType IntegerType = Context.getCanonicalType(ParamType); 02546 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 02547 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); 02548 02549 if (!Arg->isValueDependent()) { 02550 // Check that an unsigned parameter does not receive a negative 02551 // value. 02552 if (IntegerType->isUnsignedIntegerType() 02553 && (Value.isSigned() && Value.isNegative())) { 02554 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative) 02555 << Value.toString(10) << Param->getType() 02556 << Arg->getSourceRange(); 02557 Diag(Param->getLocation(), diag::note_template_param_here); 02558 return true; 02559 } 02560 02561 // Check that we don't overflow the template parameter type. 02562 unsigned AllowedBits = Context.getTypeSize(IntegerType); 02563 unsigned RequiredBits; 02564 if (IntegerType->isUnsignedIntegerType()) 02565 RequiredBits = Value.getActiveBits(); 02566 else if (Value.isUnsigned()) 02567 RequiredBits = Value.getActiveBits() + 1; 02568 else 02569 RequiredBits = Value.getMinSignedBits(); 02570 if (RequiredBits > AllowedBits) { 02571 Diag(Arg->getSourceRange().getBegin(), 02572 diag::err_template_arg_too_large) 02573 << Value.toString(10) << Param->getType() 02574 << Arg->getSourceRange(); 02575 Diag(Param->getLocation(), diag::note_template_param_here); 02576 return true; 02577 } 02578 02579 if (Value.getBitWidth() != AllowedBits) 02580 Value.extOrTrunc(AllowedBits); 02581 Value.setIsSigned(IntegerType->isSignedIntegerType()); 02582 } 02583 02584 // Add the value of this argument to the list of converted 02585 // arguments. We use the bitwidth and signedness of the template 02586 // parameter. 02587 if (Arg->isValueDependent()) { 02588 // The argument is value-dependent. Create a new 02589 // TemplateArgument with the converted expression. 02590 Converted = TemplateArgument(Arg); 02591 return false; 02592 } 02593 02594 Converted = TemplateArgument(Value, 02595 ParamType->isEnumeralType() ? ParamType 02596 : IntegerType); 02597 return false; 02598 } 02599 02600 // Handle pointer-to-function, reference-to-function, and 02601 // pointer-to-member-function all in (roughly) the same way. 02602 if (// -- For a non-type template-parameter of type pointer to 02603 // function, only the function-to-pointer conversion (4.3) is 02604 // applied. If the template-argument represents a set of 02605 // overloaded functions (or a pointer to such), the matching 02606 // function is selected from the set (13.4). 02607 // In C++0x, any std::nullptr_t value can be converted. 02608 (ParamType->isPointerType() && 02609 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) || 02610 // -- For a non-type template-parameter of type reference to 02611 // function, no conversions apply. If the template-argument 02612 // represents a set of overloaded functions, the matching 02613 // function is selected from the set (13.4). 02614 (ParamType->isReferenceType() && 02615 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 02616 // -- For a non-type template-parameter of type pointer to 02617 // member function, no conversions apply. If the 02618 // template-argument represents a set of overloaded member 02619 // functions, the matching member function is selected from 02620 // the set (13.4). 02621 // Again, C++0x allows a std::nullptr_t value. 02622 (ParamType->isMemberPointerType() && 02623 ParamType->getAs<MemberPointerType>()->getPointeeType() 02624 ->isFunctionType())) { 02625 if (Context.hasSameUnqualifiedType(ArgType, 02626 ParamType.getNonReferenceType())) { 02627 // We don't have to do anything: the types already match. 02628 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() || 02629 ParamType->isMemberPointerType())) { 02630 ArgType = ParamType; 02631 if (ParamType->isMemberPointerType()) 02632 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer); 02633 else 02634 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast); 02635 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) { 02636 ArgType = Context.getPointerType(ArgType); 02637 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay); 02638 } else if (FunctionDecl *Fn 02639 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) { 02640 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 02641 return true; 02642 02643 Arg = FixOverloadedFunctionReference(Arg, Fn); 02644 ArgType = Arg->getType(); 02645 if (ArgType->isFunctionType() && ParamType->isPointerType()) { 02646 ArgType = Context.getPointerType(Arg->getType()); 02647 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay); 02648 } 02649 } 02650 02651 if (!Context.hasSameUnqualifiedType(ArgType, 02652 ParamType.getNonReferenceType())) { 02653 // We can't perform this conversion. 02654 Diag(Arg->getSourceRange().getBegin(), 02655 diag::err_template_arg_not_convertible) 02656 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 02657 Diag(Param->getLocation(), diag::note_template_param_here); 02658 return true; 02659 } 02660 02661 if (ParamType->isMemberPointerType()) 02662 return CheckTemplateArgumentPointerToMember(Arg, Converted); 02663 02664 NamedDecl *Entity = 0; 02665 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 02666 return true; 02667 02668 if (Arg->isValueDependent()) { 02669 Converted = TemplateArgument(Arg); 02670 } else { 02671 if (Entity) 02672 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 02673 Converted = TemplateArgument(Entity); 02674 } 02675 return false; 02676 } 02677 02678 if (ParamType->isPointerType()) { 02679 // -- for a non-type template-parameter of type pointer to 02680 // object, qualification conversions (4.4) and the 02681 // array-to-pointer conversion (4.2) are applied. 02682 // C++0x also allows a value of std::nullptr_t. 02683 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() && 02684 "Only object pointers allowed here"); 02685 02686 if (ArgType->isNullPtrType()) { 02687 ArgType = ParamType; 02688 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast); 02689 } else if (ArgType->isArrayType()) { 02690 ArgType = Context.getArrayDecayedType(ArgType); 02691 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay); 02692 } 02693 02694 if (IsQualificationConversion(ArgType, ParamType)) { 02695 ArgType = ParamType; 02696 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp); 02697 } 02698 02699 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) { 02700 // We can't perform this conversion. 02701 Diag(Arg->getSourceRange().getBegin(), 02702 diag::err_template_arg_not_convertible) 02703 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 02704 Diag(Param->getLocation(), diag::note_template_param_here); 02705 return true; 02706 } 02707 02708 NamedDecl *Entity = 0; 02709 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 02710 return true; 02711 02712 if (Arg->isValueDependent()) { 02713 Converted = TemplateArgument(Arg); 02714 } else { 02715 if (Entity) 02716 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 02717 Converted = TemplateArgument(Entity); 02718 } 02719 return false; 02720 } 02721 02722 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 02723 // -- For a non-type template-parameter of type reference to 02724 // object, no conversions apply. The type referred to by the 02725 // reference may be more cv-qualified than the (otherwise 02726 // identical) type of the template-argument. The 02727 // template-parameter is bound directly to the 02728 // template-argument, which must be an lvalue. 02729 assert(ParamRefType->getPointeeType()->isObjectType() && 02730 "Only object references allowed here"); 02731 02732 QualType ReferredType = ParamRefType->getPointeeType(); 02733 if (!Context.hasSameUnqualifiedType(ReferredType, ArgType)) { 02734 Diag(Arg->getSourceRange().getBegin(), 02735 diag::err_template_arg_no_ref_bind) 02736 << InstantiatedParamType << Arg->getType() 02737 << Arg->getSourceRange(); 02738 Diag(Param->getLocation(), diag::note_template_param_here); 02739 return true; 02740 } 02741 02742 unsigned ParamQuals 02743 = Context.getCanonicalType(ReferredType).getCVRQualifiers(); 02744 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers(); 02745 02746 if ((ParamQuals | ArgQuals) != ParamQuals) { 02747 Diag(Arg->getSourceRange().getBegin(), 02748 diag::err_template_arg_ref_bind_ignores_quals) 02749 << InstantiatedParamType << Arg->getType() 02750 << Arg->getSourceRange(); 02751 Diag(Param->getLocation(), diag::note_template_param_here); 02752 return true; 02753 } 02754 02755 NamedDecl *Entity = 0; 02756 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 02757 return true; 02758 02759 if (Arg->isValueDependent()) { 02760 Converted = TemplateArgument(Arg); 02761 } else { 02762 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 02763 Converted = TemplateArgument(Entity); 02764 } 02765 return false; 02766 } 02767 02768 // -- For a non-type template-parameter of type pointer to data 02769 // member, qualification conversions (4.4) are applied. 02770 // C++0x allows std::nullptr_t values. 02771 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 02772 02773 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) { 02774 // Types match exactly: nothing more to do here. 02775 } else if (ArgType->isNullPtrType()) { 02776 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer); 02777 } else if (IsQualificationConversion(ArgType, ParamType)) { 02778 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp); 02779 } else { 02780 // We can't perform this conversion. 02781 Diag(Arg->getSourceRange().getBegin(), 02782 diag::err_template_arg_not_convertible) 02783 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 02784 Diag(Param->getLocation(), diag::note_template_param_here); 02785 return true; 02786 } 02787 02788 return CheckTemplateArgumentPointerToMember(Arg, Converted); 02789 } 02790 02791 /// \brief Check a template argument against its corresponding 02792 /// template template parameter. 02793 /// 02794 /// This routine implements the semantics of C++ [temp.arg.template]. 02795 /// It returns true if an error occurred, and false otherwise. 02796 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, 02797 const TemplateArgumentLoc &Arg) { 02798 TemplateName Name = Arg.getArgument().getAsTemplate(); 02799 TemplateDecl *Template = Name.getAsTemplateDecl(); 02800 if (!Template) { 02801 // Any dependent template name is fine. 02802 assert(Name.isDependent() && "Non-dependent template isn't a declaration?"); 02803 return false; 02804 } 02805 02806 // C++ [temp.arg.template]p1: 02807 // A template-argument for a template template-parameter shall be 02808 // the name of a class template, expressed as id-expression. Only 02809 // primary class templates are considered when matching the 02810 // template template argument with the corresponding parameter; 02811 // partial specializations are not considered even if their 02812 // parameter lists match that of the template template parameter. 02813 // 02814 // Note that we also allow template template parameters here, which 02815 // will happen when we are dealing with, e.g., class template 02816 // partial specializations. 02817 if (!isa<ClassTemplateDecl>(Template) && 02818 !isa<TemplateTemplateParmDecl>(Template)) { 02819 assert(isa<FunctionTemplateDecl>(Template) && 02820 "Only function templates are possible here"); 02821 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template); 02822 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 02823 << Template; 02824 } 02825 02826 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 02827 Param->getTemplateParameters(), 02828 true, 02829 TPL_TemplateTemplateArgumentMatch, 02830 Arg.getLocation()); 02831 } 02832 02833 /// \brief Determine whether the given template parameter lists are 02834 /// equivalent. 02835 /// 02836 /// \param New The new template parameter list, typically written in the 02837 /// source code as part of a new template declaration. 02838 /// 02839 /// \param Old The old template parameter list, typically found via 02840 /// name lookup of the template declared with this template parameter 02841 /// list. 02842 /// 02843 /// \param Complain If true, this routine will produce a diagnostic if 02844 /// the template parameter lists are not equivalent. 02845 /// 02846 /// \param Kind describes how we are to match the template parameter lists. 02847 /// 02848 /// \param TemplateArgLoc If this source location is valid, then we 02849 /// are actually checking the template parameter list of a template 02850 /// argument (New) against the template parameter list of its 02851 /// corresponding template template parameter (Old). We produce 02852 /// slightly different diagnostics in this scenario. 02853 /// 02854 /// \returns True if the template parameter lists are equal, false 02855 /// otherwise. 02856 bool 02857 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 02858 TemplateParameterList *Old, 02859 bool Complain, 02860 TemplateParameterListEqualKind Kind, 02861 SourceLocation TemplateArgLoc) { 02862 if (Old->size() != New->size()) { 02863 if (Complain) { 02864 unsigned NextDiag = diag::err_template_param_list_different_arity; 02865 if (TemplateArgLoc.isValid()) { 02866 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 02867 NextDiag = diag::note_template_param_list_different_arity; 02868 } 02869 Diag(New->getTemplateLoc(), NextDiag) 02870 << (New->size() > Old->size()) 02871 << (Kind != TPL_TemplateMatch) 02872 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 02873 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 02874 << (Kind != TPL_TemplateMatch) 02875 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 02876 } 02877 02878 return false; 02879 } 02880 02881 for (TemplateParameterList::iterator OldParm = Old->begin(), 02882 OldParmEnd = Old->end(), NewParm = New->begin(); 02883 OldParm != OldParmEnd; ++OldParm, ++NewParm) { 02884 if ((*OldParm)->getKind() != (*NewParm)->getKind()) { 02885 if (Complain) { 02886 unsigned NextDiag = diag::err_template_param_different_kind; 02887 if (TemplateArgLoc.isValid()) { 02888 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 02889 NextDiag = diag::note_template_param_different_kind; 02890 } 02891 Diag((*NewParm)->getLocation(), NextDiag) 02892 << (Kind != TPL_TemplateMatch); 02893 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration) 02894 << (Kind != TPL_TemplateMatch); 02895 } 02896 return false; 02897 } 02898 02899 if (isa<TemplateTypeParmDecl>(*OldParm)) { 02900 // Okay; all template type parameters are equivalent (since we 02901 // know we're at the same index). 02902 } else if (NonTypeTemplateParmDecl *OldNTTP 02903 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) { 02904 // The types of non-type template parameters must agree. 02905 NonTypeTemplateParmDecl *NewNTTP 02906 = cast<NonTypeTemplateParmDecl>(*NewParm); 02907 02908 // If we are matching a template template argument to a template 02909 // template parameter and one of the non-type template parameter types 02910 // is dependent, then we must wait until template instantiation time 02911 // to actually compare the arguments. 02912 if (Kind == TPL_TemplateTemplateArgumentMatch && 02913 (OldNTTP->getType()->isDependentType() || 02914 NewNTTP->getType()->isDependentType())) 02915 continue; 02916 02917 if (Context.getCanonicalType(OldNTTP->getType()) != 02918 Context.getCanonicalType(NewNTTP->getType())) { 02919 if (Complain) { 02920 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 02921 if (TemplateArgLoc.isValid()) { 02922 Diag(TemplateArgLoc, 02923 diag::err_template_arg_template_params_mismatch); 02924 NextDiag = diag::note_template_nontype_parm_different_type; 02925 } 02926 Diag(NewNTTP->getLocation(), NextDiag) 02927 << NewNTTP->getType() 02928 << (Kind != TPL_TemplateMatch); 02929 Diag(OldNTTP->getLocation(), 02930 diag::note_template_nontype_parm_prev_declaration) 02931 << OldNTTP->getType(); 02932 } 02933 return false; 02934 } 02935 } else { 02936 // The template parameter lists of template template 02937 // parameters must agree. 02938 assert(isa<TemplateTemplateParmDecl>(*OldParm) && 02939 "Only template template parameters handled here"); 02940 TemplateTemplateParmDecl *OldTTP 02941 = cast<TemplateTemplateParmDecl>(*OldParm); 02942 TemplateTemplateParmDecl *NewTTP 02943 = cast<TemplateTemplateParmDecl>(*NewParm); 02944 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 02945 OldTTP->getTemplateParameters(), 02946 Complain, 02947 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind), 02948 TemplateArgLoc)) 02949 return false; 02950 } 02951 } 02952 02953 return true; 02954 } 02955 02956 /// \brief Check whether a template can be declared within this scope. 02957 /// 02958 /// If the template declaration is valid in this scope, returns 02959 /// false. Otherwise, issues a diagnostic and returns true. 02960 bool 02961 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 02962 // Find the nearest enclosing declaration scope. 02963 while ((S->getFlags() & Scope::DeclScope) == 0 || 02964 (S->getFlags() & Scope::TemplateParamScope) != 0) 02965 S = S->getParent(); 02966 02967 // C++ [temp]p2: 02968 // A template-declaration can appear only as a namespace scope or 02969 // class scope declaration. 02970 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 02971 if (Ctx && isa<LinkageSpecDecl>(Ctx) && 02972 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx) 02973 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 02974 << TemplateParams->getSourceRange(); 02975 02976 while (Ctx && isa<LinkageSpecDecl>(Ctx)) 02977 Ctx = Ctx->getParent(); 02978 02979 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord())) 02980 return false; 02981 02982 return Diag(TemplateParams->getTemplateLoc(), 02983 diag::err_template_outside_namespace_or_class_scope) 02984 << TemplateParams->getSourceRange(); 02985 } 02986 02987 /// \brief Determine what kind of template specialization the given declaration 02988 /// is. 02989 static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) { 02990 if (!D) 02991 return TSK_Undeclared; 02992 02993 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 02994 return Record->getTemplateSpecializationKind(); 02995 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 02996 return Function->getTemplateSpecializationKind(); 02997 if (VarDecl *Var = dyn_cast<VarDecl>(D)) 02998 return Var->getTemplateSpecializationKind(); 02999 03000 return TSK_Undeclared; 03001 } 03002 03003 /// \brief Check whether a specialization is well-formed in the current 03004 /// context. 03005 /// 03006 /// This routine determines whether a template specialization can be declared 03007 /// in the current context (C++ [temp.expl.spec]p2). 03008 /// 03009 /// \param S the semantic analysis object for which this check is being 03010 /// performed. 03011 /// 03012 /// \param Specialized the entity being specialized or instantiated, which 03013 /// may be a kind of template (class template, function template, etc.) or 03014 /// a member of a class template (member function, static data member, 03015 /// member class). 03016 /// 03017 /// \param PrevDecl the previous declaration of this entity, if any. 03018 /// 03019 /// \param Loc the location of the explicit specialization or instantiation of 03020 /// this entity. 03021 /// 03022 /// \param IsPartialSpecialization whether this is a partial specialization of 03023 /// a class template. 03024 /// 03025 /// \returns true if there was an error that we cannot recover from, false 03026 /// otherwise. 03027 static bool CheckTemplateSpecializationScope(Sema &S, 03028 NamedDecl *Specialized, 03029 NamedDecl *PrevDecl, 03030 SourceLocation Loc, 03031 bool IsPartialSpecialization) { 03032 // Keep these "kind" numbers in sync with the %select statements in the 03033 // various diagnostics emitted by this routine. 03034 int EntityKind = 0; 03035 bool isTemplateSpecialization = false; 03036 if (isa<ClassTemplateDecl>(Specialized)) { 03037 EntityKind = IsPartialSpecialization? 1 : 0; 03038 isTemplateSpecialization = true; 03039 } else if (isa<FunctionTemplateDecl>(Specialized)) { 03040 EntityKind = 2; 03041 isTemplateSpecialization = true; 03042 } else if (isa<CXXMethodDecl>(Specialized)) 03043 EntityKind = 3; 03044 else if (isa<VarDecl>(Specialized)) 03045 EntityKind = 4; 03046 else if (isa<RecordDecl>(Specialized)) 03047 EntityKind = 5; 03048 else { 03049 S.Diag(Loc, diag::err_template_spec_unknown_kind); 03050 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 03051 return true; 03052 } 03053 03054 // C++ [temp.expl.spec]p2: 03055 // An explicit specialization shall be declared in the namespace 03056 // of which the template is a member, or, for member templates, in 03057 // the namespace of which the enclosing class or enclosing class 03058 // template is a member. An explicit specialization of a member 03059 // function, member class or static data member of a class 03060 // template shall be declared in the namespace of which the class 03061 // template is a member. Such a declaration may also be a 03062 // definition. If the declaration is not a definition, the 03063 // specialization may be defined later in the name- space in which 03064 // the explicit specialization was declared, or in a namespace 03065 // that encloses the one in which the explicit specialization was 03066 // declared. 03067 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) { 03068 S.Diag(Loc, diag::err_template_spec_decl_function_scope) 03069 << Specialized; 03070 return true; 03071 } 03072 03073 if (S.CurContext->isRecord() && !IsPartialSpecialization) { 03074 S.Diag(Loc, diag::err_template_spec_decl_class_scope) 03075 << Specialized; 03076 return true; 03077 } 03078 03079 // C++ [temp.class.spec]p6: 03080 // A class template partial specialization may be declared or redeclared 03081 // in any namespace scope in which its definition may be defined (14.5.1 03082 // and 14.5.2). 03083 bool ComplainedAboutScope = false; 03084 DeclContext *SpecializedContext 03085 = Specialized->getDeclContext()->getEnclosingNamespaceContext(); 03086 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext(); 03087 if ((!PrevDecl || 03088 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared || 03089 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){ 03090 // There is no prior declaration of this entity, so this 03091 // specialization must be in the same context as the template 03092 // itself. 03093 if (!DC->Equals(SpecializedContext)) { 03094 if (isa<TranslationUnitDecl>(SpecializedContext)) 03095 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global) 03096 << EntityKind << Specialized; 03097 else if (isa<NamespaceDecl>(SpecializedContext)) 03098 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope) 03099 << EntityKind << Specialized 03100 << cast<NamedDecl>(SpecializedContext); 03101 03102 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 03103 ComplainedAboutScope = true; 03104 } 03105 } 03106 03107 // Make sure that this redeclaration (or definition) occurs in an enclosing 03108 // namespace. 03109 // Note that HandleDeclarator() performs this check for explicit 03110 // specializations of function templates, static data members, and member 03111 // functions, so we skip the check here for those kinds of entities. 03112 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though. 03113 // Should we refactor that check, so that it occurs later? 03114 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) && 03115 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) || 03116 isa<FunctionDecl>(Specialized))) { 03117 if (isa<TranslationUnitDecl>(SpecializedContext)) 03118 S.Diag(Loc, diag::err_template_spec_redecl_global_scope) 03119 << EntityKind << Specialized; 03120 else if (isa<NamespaceDecl>(SpecializedContext)) 03121 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope) 03122 << EntityKind << Specialized 03123 << cast<NamedDecl>(SpecializedContext); 03124 03125 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 03126 } 03127 03128 // FIXME: check for specialization-after-instantiation errors and such. 03129 03130 return false; 03131 } 03132 03133 /// \brief Check the non-type template arguments of a class template 03134 /// partial specialization according to C++ [temp.class.spec]p9. 03135 /// 03136 /// \param TemplateParams the template parameters of the primary class 03137 /// template. 03138 /// 03139 /// \param TemplateArg the template arguments of the class template 03140 /// partial specialization. 03141 /// 03142 /// \param MirrorsPrimaryTemplate will be set true if the class 03143 /// template partial specialization arguments are identical to the 03144 /// implicit template arguments of the primary template. This is not 03145 /// necessarily an error (C++0x), and it is left to the caller to diagnose 03146 /// this condition when it is an error. 03147 /// 03148 /// \returns true if there was an error, false otherwise. 03149 bool Sema::CheckClassTemplatePartialSpecializationArgs( 03150 TemplateParameterList *TemplateParams, 03151 const TemplateArgumentListBuilder &TemplateArgs, 03152 bool &MirrorsPrimaryTemplate) { 03153 // FIXME: the interface to this function will have to change to 03154 // accommodate variadic templates. 03155 MirrorsPrimaryTemplate = true; 03156 03157 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments(); 03158 03159 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 03160 // Determine whether the template argument list of the partial 03161 // specialization is identical to the implicit argument list of 03162 // the primary template. The caller may need to diagnostic this as 03163 // an error per C++ [temp.class.spec]p9b3. 03164 if (MirrorsPrimaryTemplate) { 03165 if (TemplateTypeParmDecl *TTP 03166 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) { 03167 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) != 03168 Context.getCanonicalType(ArgList[I].getAsType())) 03169 MirrorsPrimaryTemplate = false; 03170 } else if (TemplateTemplateParmDecl *TTP 03171 = dyn_cast<TemplateTemplateParmDecl>( 03172 TemplateParams->getParam(I))) { 03173 TemplateName Name = ArgList[I].getAsTemplate(); 03174 TemplateTemplateParmDecl *ArgDecl 03175 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()); 03176 if (!ArgDecl || 03177 ArgDecl->getIndex() != TTP->getIndex() || 03178 ArgDecl->getDepth() != TTP->getDepth()) 03179 MirrorsPrimaryTemplate = false; 03180 } 03181 } 03182 03183 NonTypeTemplateParmDecl *Param 03184 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 03185 if (!Param) { 03186 continue; 03187 } 03188 03189 Expr *ArgExpr = ArgList[I].getAsExpr(); 03190 if (!ArgExpr) { 03191 MirrorsPrimaryTemplate = false; 03192 continue; 03193 } 03194 03195 // C++ [temp.class.spec]p8: 03196 // A non-type argument is non-specialized if it is the name of a 03197 // non-type parameter. All other non-type arguments are 03198 // specialized. 03199 // 03200 // Below, we check the two conditions that only apply to 03201 // specialized non-type arguments, so skip any non-specialized 03202 // arguments. 03203 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 03204 if (NonTypeTemplateParmDecl *NTTP 03205 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) { 03206 if (MirrorsPrimaryTemplate && 03207 (Param->getIndex() != NTTP->getIndex() || 03208 Param->getDepth() != NTTP->getDepth())) 03209 MirrorsPrimaryTemplate = false; 03210 03211 continue; 03212 } 03213 03214 // C++ [temp.class.spec]p9: 03215 // Within the argument list of a class template partial 03216 // specialization, the following restrictions apply: 03217 // -- A partially specialized non-type argument expression 03218 // shall not involve a template parameter of the partial 03219 // specialization except when the argument expression is a 03220 // simple identifier. 03221 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) { 03222 Diag(ArgExpr->getLocStart(), 03223 diag::err_dependent_non_type_arg_in_partial_spec) 03224 << ArgExpr->getSourceRange(); 03225 return true; 03226 } 03227 03228 // -- The type of a template parameter corresponding to a 03229 // specialized non-type argument shall not be dependent on a 03230 // parameter of the specialization. 03231 if (Param->getType()->isDependentType()) { 03232 Diag(ArgExpr->getLocStart(), 03233 diag::err_dependent_typed_non_type_arg_in_partial_spec) 03234 << Param->getType() 03235 << ArgExpr->getSourceRange(); 03236 Diag(Param->getLocation(), diag::note_template_param_here); 03237 return true; 03238 } 03239 03240 MirrorsPrimaryTemplate = false; 03241 } 03242 03243 return false; 03244 } 03245 03246 /// \brief Retrieve the previous declaration of the given declaration. 03247 static NamedDecl *getPreviousDecl(NamedDecl *ND) { 03248 if (VarDecl *VD = dyn_cast<VarDecl>(ND)) 03249 return VD->getPreviousDeclaration(); 03250 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 03251 return FD->getPreviousDeclaration(); 03252 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) 03253 return TD->getPreviousDeclaration(); 03254 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 03255 return TD->getPreviousDeclaration(); 03256 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 03257 return FTD->getPreviousDeclaration(); 03258 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND)) 03259 return CTD->getPreviousDeclaration(); 03260 return 0; 03261 } 03262 03263 Sema::DeclResult 03264 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, 03265 TagUseKind TUK, 03266 SourceLocation KWLoc, 03267 const CXXScopeSpec &SS, 03268 TemplateTy TemplateD, 03269 SourceLocation TemplateNameLoc, 03270 SourceLocation LAngleLoc, 03271 ASTTemplateArgsPtr TemplateArgsIn, 03272 SourceLocation RAngleLoc, 03273 AttributeList *Attr, 03274 MultiTemplateParamsArg TemplateParameterLists) { 03275 assert(TUK != TUK_Reference && "References are not specializations"); 03276 03277 // Find the class template we're specializing 03278 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 03279 ClassTemplateDecl *ClassTemplate 03280 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl()); 03281 03282 if (!ClassTemplate) { 03283 Diag(TemplateNameLoc, diag::err_not_class_template_specialization) 03284 << (Name.getAsTemplateDecl() && 03285 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); 03286 return true; 03287 } 03288 03289 bool isExplicitSpecialization = false; 03290 bool isPartialSpecialization = false; 03291 03292 // Check the validity of the template headers that introduce this 03293 // template. 03294 // FIXME: We probably shouldn't complain about these headers for 03295 // friend declarations. 03296 TemplateParameterList *TemplateParams 03297 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS, 03298 (TemplateParameterList**)TemplateParameterLists.get(), 03299 TemplateParameterLists.size(), 03300 isExplicitSpecialization); 03301 if (TemplateParams && TemplateParams->size() > 0) { 03302 isPartialSpecialization = true; 03303 03304 // C++ [temp.class.spec]p10: 03305 // The template parameter list of a specialization shall not 03306 // contain default template argument values. 03307 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 03308 Decl *Param = TemplateParams->getParam(I); 03309 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 03310 if (TTP->hasDefaultArgument()) { 03311 Diag(TTP->getDefaultArgumentLoc(), 03312 diag::err_default_arg_in_partial_spec); 03313 TTP->removeDefaultArgument(); 03314 } 03315 } else if (NonTypeTemplateParmDecl *NTTP 03316 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 03317 if (Expr *DefArg = NTTP->getDefaultArgument()) { 03318 Diag(NTTP->getDefaultArgumentLoc(), 03319 diag::err_default_arg_in_partial_spec) 03320 << DefArg->getSourceRange(); 03321 NTTP->setDefaultArgument(0); 03322 DefArg->Destroy(Context); 03323 } 03324 } else { 03325 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 03326 if (TTP->hasDefaultArgument()) { 03327 Diag(TTP->getDefaultArgument().getLocation(), 03328 diag::err_default_arg_in_partial_spec) 03329 << TTP->getDefaultArgument().getSourceRange(); 03330 TTP->setDefaultArgument(TemplateArgumentLoc()); 03331 } 03332 } 03333 } 03334 } else if (TemplateParams) { 03335 if (TUK == TUK_Friend) 03336 Diag(KWLoc, diag::err_template_spec_friend) 03337 << CodeModificationHint::CreateRemoval( 03338 SourceRange(TemplateParams->getTemplateLoc(), 03339 TemplateParams->getRAngleLoc())) 03340 << SourceRange(LAngleLoc, RAngleLoc); 03341 else 03342 isExplicitSpecialization = true; 03343 } else if (TUK != TUK_Friend) { 03344 Diag(KWLoc, diag::err_template_spec_needs_header) 03345 << CodeModificationHint::CreateInsertion(KWLoc, "template<> "); 03346 isExplicitSpecialization = true; 03347 } 03348 03349 // Check that the specialization uses the same tag kind as the 03350 // original template. 03351 TagDecl::TagKind Kind; 03352 switch (TagSpec) { 03353 default: assert(0 && "Unknown tag type!"); 03354 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 03355 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 03356 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 03357 } 03358 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 03359 Kind, KWLoc, 03360 *ClassTemplate->getIdentifier())) { 03361 Diag(KWLoc, diag::err_use_with_wrong_tag) 03362 << ClassTemplate 03363 << CodeModificationHint::CreateReplacement(KWLoc, 03364 ClassTemplate->getTemplatedDecl()->getKindName()); 03365 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 03366 diag::note_previous_use); 03367 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 03368 } 03369 03370 // Translate the parser's template argument list in our AST format. 03371 TemplateArgumentListInfo TemplateArgs; 03372 TemplateArgs.setLAngleLoc(LAngleLoc); 03373 TemplateArgs.setRAngleLoc(RAngleLoc); 03374 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 03375 03376 // Check that the template argument list is well-formed for this 03377 // template. 03378 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 03379 TemplateArgs.size()); 03380 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 03381 TemplateArgs, false, Converted)) 03382 return true; 03383 03384 assert((Converted.structuredSize() == 03385 ClassTemplate->getTemplateParameters()->size()) && 03386 "Converted template argument list is too short!"); 03387 03388 // Find the class template (partial) specialization declaration that 03389 // corresponds to these arguments. 03390 llvm::FoldingSetNodeID ID; 03391 if (isPartialSpecialization) { 03392 bool MirrorsPrimaryTemplate; 03393 if (CheckClassTemplatePartialSpecializationArgs( 03394 ClassTemplate->getTemplateParameters(), 03395 Converted, MirrorsPrimaryTemplate)) 03396 return true; 03397 03398 if (MirrorsPrimaryTemplate) { 03399 // C++ [temp.class.spec]p9b3: 03400 // 03401 // -- The argument list of the specialization shall not be identical 03402 // to the implicit argument list of the primary template. 03403 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 03404 << (TUK == TUK_Definition) 03405 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc, 03406 RAngleLoc)); 03407 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, 03408 ClassTemplate->getIdentifier(), 03409 TemplateNameLoc, 03410 Attr, 03411 TemplateParams, 03412 AS_none); 03413 } 03414 03415 // FIXME: Diagnose friend partial specializations 03416 03417 if (!Name.isDependent() && 03418 !TemplateSpecializationType::anyDependentTemplateArguments( 03419 TemplateArgs.getArgumentArray(), 03420 TemplateArgs.size())) { 03421 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 03422 << ClassTemplate->getDeclName(); 03423 isPartialSpecialization = false; 03424 } else { 03425 // FIXME: Template parameter list matters, too 03426 ClassTemplatePartialSpecializationDecl::Profile(ID, 03427 Converted.getFlatArguments(), 03428 Converted.flatSize(), 03429 Context); 03430 } 03431 } 03432 03433 if (!isPartialSpecialization) 03434 ClassTemplateSpecializationDecl::Profile(ID, 03435 Converted.getFlatArguments(), 03436 Converted.flatSize(), 03437 Context); 03438 void *InsertPos = 0; 03439 ClassTemplateSpecializationDecl *PrevDecl = 0; 03440 03441 if (isPartialSpecialization) 03442 PrevDecl 03443 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 03444 InsertPos); 03445 else 03446 PrevDecl 03447 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 03448 03449 ClassTemplateSpecializationDecl *Specialization = 0; 03450 03451 // Check whether we can declare a class template specialization in 03452 // the current scope. 03453 if (TUK != TUK_Friend && 03454 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 03455 TemplateNameLoc, 03456 isPartialSpecialization)) 03457 return true; 03458 03459 // The canonical type 03460 QualType CanonType; 03461 if (PrevDecl && 03462 (PrevDecl->getSpecializationKind() == TSK_Undeclared || 03463 TUK == TUK_Friend)) { 03464 // Since the only prior class template specialization with these 03465 // arguments was referenced but not declared, or we're only 03466 // referencing this specialization as a friend, reuse that 03467 // declaration node as our own, updating its source location to 03468 // reflect our new declaration. 03469 Specialization = PrevDecl; 03470 Specialization->setLocation(TemplateNameLoc); 03471 PrevDecl = 0; 03472 CanonType = Context.getTypeDeclType(Specialization); 03473 } else if (isPartialSpecialization) { 03474 // Build the canonical type that describes the converted template 03475 // arguments of the class template partial specialization. 03476 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 03477 CanonType = Context.getTemplateSpecializationType(CanonTemplate, 03478 Converted.getFlatArguments(), 03479 Converted.flatSize()); 03480 03481 // Create a new class template partial specialization declaration node. 03482 ClassTemplatePartialSpecializationDecl *PrevPartial 03483 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 03484 ClassTemplatePartialSpecializationDecl *Partial 03485 = ClassTemplatePartialSpecializationDecl::Create(Context, 03486 ClassTemplate->getDeclContext(), 03487 TemplateNameLoc, 03488 TemplateParams, 03489 ClassTemplate, 03490 Converted, 03491 TemplateArgs, 03492 CanonType, 03493 PrevPartial); 03494 03495 if (PrevPartial) { 03496 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial); 03497 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial); 03498 } else { 03499 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos); 03500 } 03501 Specialization = Partial; 03502 03503 // If we are providing an explicit specialization of a member class 03504 // template specialization, make a note of that. 03505 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 03506 PrevPartial->setMemberSpecialization(); 03507 03508 // Check that all of the template parameters of the class template 03509 // partial specialization are deducible from the template 03510 // arguments. If not, this class template partial specialization 03511 // will never be used. 03512 llvm::SmallVector<bool, 8> DeducibleParams; 03513 DeducibleParams.resize(TemplateParams->size()); 03514 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 03515 TemplateParams->getDepth(), 03516 DeducibleParams); 03517 unsigned NumNonDeducible = 0; 03518 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) 03519 if (!DeducibleParams[I]) 03520 ++NumNonDeducible; 03521 03522 if (NumNonDeducible) { 03523 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible) 03524 << (NumNonDeducible > 1) 03525 << SourceRange(TemplateNameLoc, RAngleLoc); 03526 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 03527 if (!DeducibleParams[I]) { 03528 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I)); 03529 if (Param->getDeclName()) 03530 Diag(Param->getLocation(), 03531 diag::note_partial_spec_unused_parameter) 03532 << Param->getDeclName(); 03533 else 03534 Diag(Param->getLocation(), 03535 diag::note_partial_spec_unused_parameter) 03536 << std::string("<anonymous>"); 03537 } 03538 } 03539 } 03540 } else { 03541 // Create a new class template specialization declaration node for 03542 // this explicit specialization or friend declaration. 03543 Specialization 03544 = ClassTemplateSpecializationDecl::Create(Context, 03545 ClassTemplate->getDeclContext(), 03546 TemplateNameLoc, 03547 ClassTemplate, 03548 Converted, 03549 PrevDecl); 03550 03551 if (PrevDecl) { 03552 ClassTemplate->getSpecializations().RemoveNode(PrevDecl); 03553 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization); 03554 } else { 03555 ClassTemplate->getSpecializations().InsertNode(Specialization, 03556 InsertPos); 03557 } 03558 03559 CanonType = Context.getTypeDeclType(Specialization); 03560 } 03561 03562 // C++ [temp.expl.spec]p6: 03563 // If a template, a member template or the member of a class template is 03564 // explicitly specialized then that specialization shall be declared 03565 // before the first use of that specialization that would cause an implicit 03566 // instantiation to take place, in every translation unit in which such a 03567 // use occurs; no diagnostic is required. 03568 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 03569 bool Okay = false; 03570 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) { 03571 // Is there any previous explicit specialization declaration? 03572 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 03573 Okay = true; 03574 break; 03575 } 03576 } 03577 03578 if (!Okay) { 03579 SourceRange Range(TemplateNameLoc, RAngleLoc); 03580 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 03581 << Context.getTypeDeclType(Specialization) << Range; 03582 03583 Diag(PrevDecl->getPointOfInstantiation(), 03584 diag::note_instantiation_required_here) 03585 << (PrevDecl->getTemplateSpecializationKind() 03586 != TSK_ImplicitInstantiation); 03587 return true; 03588 } 03589 } 03590 03591 // If this is not a friend, note that this is an explicit specialization. 03592 if (TUK != TUK_Friend) 03593 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 03594 03595 // Check that this isn't a redefinition of this specialization. 03596 if (TUK == TUK_Definition) { 03597 if (RecordDecl *Def = Specialization->getDefinition()) { 03598 SourceRange Range(TemplateNameLoc, RAngleLoc); 03599 Diag(TemplateNameLoc, diag::err_redefinition) 03600 << Context.getTypeDeclType(Specialization) << Range; 03601 Diag(Def->getLocation(), diag::note_previous_definition); 03602 Specialization->setInvalidDecl(); 03603 return true; 03604 } 03605 } 03606 03607 // Build the fully-sugared type for this class template 03608 // specialization as the user wrote in the specialization 03609 // itself. This means that we'll pretty-print the type retrieved 03610 // from the specialization's declaration the way that the user 03611 // actually wrote the specialization, rather than formatting the 03612 // name based on the "canonical" representation used to store the 03613 // template arguments in the specialization. 03614 TypeSourceInfo *WrittenTy 03615 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 03616 TemplateArgs, CanonType); 03617 if (TUK != TUK_Friend) 03618 Specialization->setTypeAsWritten(WrittenTy); 03619 TemplateArgsIn.release(); 03620 03621 // C++ [temp.expl.spec]p9: 03622 // A template explicit specialization is in the scope of the 03623 // namespace in which the template was defined. 03624 // 03625 // We actually implement this paragraph where we set the semantic 03626 // context (in the creation of the ClassTemplateSpecializationDecl), 03627 // but we also maintain the lexical context where the actual 03628 // definition occurs. 03629 Specialization->setLexicalDeclContext(CurContext); 03630 03631 // We may be starting the definition of this specialization. 03632 if (TUK == TUK_Definition) 03633 Specialization->startDefinition(); 03634 03635 if (TUK == TUK_Friend) { 03636 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 03637 TemplateNameLoc, 03638 WrittenTy->getType().getTypePtr(), 03639 /*FIXME:*/KWLoc); 03640 Friend->setAccess(AS_public); 03641 CurContext->addDecl(Friend); 03642 } else { 03643 // Add the specialization into its lexical context, so that it can 03644 // be seen when iterating through the list of declarations in that 03645 // context. However, specializations are not found by name lookup. 03646 CurContext->addDecl(Specialization); 03647 } 03648 return DeclPtrTy::make(Specialization); 03649 } 03650 03651 Sema::DeclPtrTy 03652 Sema::ActOnTemplateDeclarator(Scope *S, 03653 MultiTemplateParamsArg TemplateParameterLists, 03654 Declarator &D) { 03655 return HandleDeclarator(S, D, move(TemplateParameterLists), false); 03656 } 03657 03658 Sema::DeclPtrTy 03659 Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 03660 MultiTemplateParamsArg TemplateParameterLists, 03661 Declarator &D) { 03662 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 03663 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 03664 "Not a function declarator!"); 03665 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 03666 03667 if (FTI.hasPrototype) { 03668 // FIXME: Diagnose arguments without names in C. 03669 } 03670 03671 Scope *ParentScope = FnBodyScope->getParent(); 03672 03673 DeclPtrTy DP = HandleDeclarator(ParentScope, D, 03674 move(TemplateParameterLists), 03675 /*IsFunctionDefinition=*/true); 03676 if (FunctionTemplateDecl *FunctionTemplate 03677 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>())) 03678 return ActOnStartOfFunctionDef(FnBodyScope, 03679 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl())); 03680 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>())) 03681 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function)); 03682 return DeclPtrTy(); 03683 } 03684 03685 /// \brief Strips various properties off an implicit instantiation 03686 /// that has just been explicitly specialized. 03687 static void StripImplicitInstantiation(NamedDecl *D) { 03688 D->invalidateAttrs(); 03689 03690 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 03691 FD->setInlineSpecified(false); 03692 } 03693 } 03694 03695 /// \brief Diagnose cases where we have an explicit template specialization 03696 /// before/after an explicit template instantiation, producing diagnostics 03697 /// for those cases where they are required and determining whether the 03698 /// new specialization/instantiation will have any effect. 03699 /// 03700 /// \param NewLoc the location of the new explicit specialization or 03701 /// instantiation. 03702 /// 03703 /// \param NewTSK the kind of the new explicit specialization or instantiation. 03704 /// 03705 /// \param PrevDecl the previous declaration of the entity. 03706 /// 03707 /// \param PrevTSK the kind of the old explicit specialization or instantiatin. 03708 /// 03709 /// \param PrevPointOfInstantiation if valid, indicates where the previus 03710 /// declaration was instantiated (either implicitly or explicitly). 03711 /// 03712 /// \param SuppressNew will be set to true to indicate that the new 03713 /// specialization or instantiation has no effect and should be ignored. 03714 /// 03715 /// \returns true if there was an error that should prevent the introduction of 03716 /// the new declaration into the AST, false otherwise. 03717 bool 03718 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 03719 TemplateSpecializationKind NewTSK, 03720 NamedDecl *PrevDecl, 03721 TemplateSpecializationKind PrevTSK, 03722 SourceLocation PrevPointOfInstantiation, 03723 bool &SuppressNew) { 03724 SuppressNew = false; 03725 03726 switch (NewTSK) { 03727 case TSK_Undeclared: 03728 case TSK_ImplicitInstantiation: 03729 assert(false && "Don't check implicit instantiations here"); 03730 return false; 03731 03732 case TSK_ExplicitSpecialization: 03733 switch (PrevTSK) { 03734 case TSK_Undeclared: 03735 case TSK_ExplicitSpecialization: 03736 // Okay, we're just specializing something that is either already 03737 // explicitly specialized or has merely been mentioned without any 03738 // instantiation. 03739 return false; 03740 03741 case TSK_ImplicitInstantiation: 03742 if (PrevPointOfInstantiation.isInvalid()) { 03743 // The declaration itself has not actually been instantiated, so it is 03744 // still okay to specialize it. 03745 StripImplicitInstantiation(PrevDecl); 03746 return false; 03747 } 03748 // Fall through 03749 03750 case TSK_ExplicitInstantiationDeclaration: 03751 case TSK_ExplicitInstantiationDefinition: 03752 assert((PrevTSK == TSK_ImplicitInstantiation || 03753 PrevPointOfInstantiation.isValid()) && 03754 "Explicit instantiation without point of instantiation?"); 03755 03756 // C++ [temp.expl.spec]p6: 03757 // If a template, a member template or the member of a class template 03758 // is explicitly specialized then that specialization shall be declared 03759 // before the first use of that specialization that would cause an 03760 // implicit instantiation to take place, in every translation unit in 03761 // which such a use occurs; no diagnostic is required. 03762 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) { 03763 // Is there any previous explicit specialization declaration? 03764 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) 03765 return false; 03766 } 03767 03768 Diag(NewLoc, diag::err_specialization_after_instantiation) 03769 << PrevDecl; 03770 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) 03771 << (PrevTSK != TSK_ImplicitInstantiation); 03772 03773 return true; 03774 } 03775 break; 03776 03777 case TSK_ExplicitInstantiationDeclaration: 03778 switch (PrevTSK) { 03779 case TSK_ExplicitInstantiationDeclaration: 03780 // This explicit instantiation declaration is redundant (that's okay). 03781 SuppressNew = true; 03782 return false; 03783 03784 case TSK_Undeclared: 03785 case TSK_ImplicitInstantiation: 03786 // We're explicitly instantiating something that may have already been 03787 // implicitly instantiated; that's fine. 03788 return false; 03789 03790 case TSK_ExplicitSpecialization: 03791 // C++0x [temp.explicit]p4: 03792 // For a given set of template parameters, if an explicit instantiation 03793 // of a template appears after a declaration of an explicit 03794 // specialization for that template, the explicit instantiation has no 03795 // effect. 03796 SuppressNew = true; 03797 return false; 03798 03799 case TSK_ExplicitInstantiationDefinition: 03800 // C++0x [temp.explicit]p10: 03801 // If an entity is the subject of both an explicit instantiation 03802 // declaration and an explicit instantiation definition in the same 03803 // translation unit, the definition shall follow the declaration. 03804 Diag(NewLoc, 03805 diag::err_explicit_instantiation_declaration_after_definition); 03806 Diag(PrevPointOfInstantiation, 03807 diag::note_explicit_instantiation_definition_here); 03808 assert(PrevPointOfInstantiation.isValid() && 03809 "Explicit instantiation without point of instantiation?"); 03810 SuppressNew = true; 03811 return false; 03812 } 03813 break; 03814 03815 case TSK_ExplicitInstantiationDefinition: 03816 switch (PrevTSK) { 03817 case TSK_Undeclared: 03818 case TSK_ImplicitInstantiation: 03819 // We're explicitly instantiating something that may have already been 03820 // implicitly instantiated; that's fine. 03821 return false; 03822 03823 case TSK_ExplicitSpecialization: 03824 // C++ DR 259, C++0x [temp.explicit]p4: 03825 // For a given set of template parameters, if an explicit 03826 // instantiation of a template appears after a declaration of 03827 // an explicit specialization for that template, the explicit 03828 // instantiation has no effect. 03829 // 03830 // In C++98/03 mode, we only give an extension warning here, because it 03831 // is not not harmful to try to explicitly instantiate something that 03832 // has been explicitly specialized. 03833 if (!getLangOptions().CPlusPlus0x) { 03834 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization) 03835 << PrevDecl; 03836 Diag(PrevDecl->getLocation(), 03837 diag::note_previous_template_specialization); 03838 } 03839 SuppressNew = true; 03840 return false; 03841 03842 case TSK_ExplicitInstantiationDeclaration: 03843 // We're explicity instantiating a definition for something for which we 03844 // were previously asked to suppress instantiations. That's fine. 03845 return false; 03846 03847 case TSK_ExplicitInstantiationDefinition: 03848 // C++0x [temp.spec]p5: 03849 // For a given template and a given set of template-arguments, 03850 // - an explicit instantiation definition shall appear at most once 03851 // in a program, 03852 Diag(NewLoc, diag::err_explicit_instantiation_duplicate) 03853 << PrevDecl; 03854 Diag(PrevPointOfInstantiation, 03855 diag::note_previous_explicit_instantiation); 03856 SuppressNew = true; 03857 return false; 03858 } 03859 break; 03860 } 03861 03862 assert(false && "Missing specialization/instantiation case?"); 03863 03864 return false; 03865 } 03866 03867 /// \brief Perform semantic analysis for the given function template 03868 /// specialization. 03869 /// 03870 /// This routine performs all of the semantic analysis required for an 03871 /// explicit function template specialization. On successful completion, 03872 /// the function declaration \p FD will become a function template 03873 /// specialization. 03874 /// 03875 /// \param FD the function declaration, which will be updated to become a 03876 /// function template specialization. 03877 /// 03878 /// \param HasExplicitTemplateArgs whether any template arguments were 03879 /// explicitly provided. 03880 /// 03881 /// \param LAngleLoc the location of the left angle bracket ('<'), if 03882 /// template arguments were explicitly provided. 03883 /// 03884 /// \param ExplicitTemplateArgs the explicitly-provided template arguments, 03885 /// if any. 03886 /// 03887 /// \param NumExplicitTemplateArgs the number of explicitly-provided template 03888 /// arguments. This number may be zero even when HasExplicitTemplateArgs is 03889 /// true as in, e.g., \c void sort<>(char*, char*); 03890 /// 03891 /// \param RAngleLoc the location of the right angle bracket ('>'), if 03892 /// template arguments were explicitly provided. 03893 /// 03894 /// \param PrevDecl the set of declarations that 03895 bool 03896 Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD, 03897 const TemplateArgumentListInfo *ExplicitTemplateArgs, 03898 LookupResult &Previous) { 03899 // The set of function template specializations that could match this 03900 // explicit function template specialization. 03901 UnresolvedSet<8> Candidates; 03902 03903 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext(); 03904 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 03905 I != E; ++I) { 03906 NamedDecl *Ovl = (*I)->getUnderlyingDecl(); 03907 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) { 03908 // Only consider templates found within the same semantic lookup scope as 03909 // FD. 03910 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext())) 03911 continue; 03912 03913 // C++ [temp.expl.spec]p11: 03914 // A trailing template-argument can be left unspecified in the 03915 // template-id naming an explicit function template specialization 03916 // provided it can be deduced from the function argument type. 03917 // Perform template argument deduction to determine whether we may be 03918 // specializing this template. 03919 // FIXME: It is somewhat wasteful to build 03920 TemplateDeductionInfo Info(Context, FD->getLocation()); 03921 FunctionDecl *Specialization = 0; 03922 if (TemplateDeductionResult TDK 03923 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs, 03924 FD->getType(), 03925 Specialization, 03926 Info)) { 03927 // FIXME: Template argument deduction failed; record why it failed, so 03928 // that we can provide nifty diagnostics. 03929 (void)TDK; 03930 continue; 03931 } 03932 03933 // Record this candidate. 03934 Candidates.addDecl(Specialization, I.getAccess()); 03935 } 03936 } 03937 03938 // Find the most specialized function template. 03939 UnresolvedSetIterator Result 03940 = getMostSpecialized(Candidates.begin(), Candidates.end(), 03941 TPOC_Other, FD->getLocation(), 03942 PartialDiagnostic(diag::err_function_template_spec_no_match) 03943 << FD->getDeclName(), 03944 PartialDiagnostic(diag::err_function_template_spec_ambiguous) 03945 << FD->getDeclName() << (ExplicitTemplateArgs != 0), 03946 PartialDiagnostic(diag::note_function_template_spec_matched)); 03947 if (Result == Candidates.end()) 03948 return true; 03949 03950 // Ignore access information; it doesn't figure into redeclaration checking. 03951 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 03952 03953 // FIXME: Check if the prior specialization has a point of instantiation. 03954 // If so, we have run afoul of . 03955 03956 // Check the scope of this explicit specialization. 03957 if (CheckTemplateSpecializationScope(*this, 03958 Specialization->getPrimaryTemplate(), 03959 Specialization, FD->getLocation(), 03960 false)) 03961 return true; 03962 03963 // C++ [temp.expl.spec]p6: 03964 // If a template, a member template or the member of a class template is 03965 // explicitly specialized then that specialization shall be declared 03966 // before the first use of that specialization that would cause an implicit 03967 // instantiation to take place, in every translation unit in which such a 03968 // use occurs; no diagnostic is required. 03969 FunctionTemplateSpecializationInfo *SpecInfo 03970 = Specialization->getTemplateSpecializationInfo(); 03971 assert(SpecInfo && "Function template specialization info missing?"); 03972 03973 bool SuppressNew = false; 03974 if (CheckSpecializationInstantiationRedecl(FD->getLocation(), 03975 TSK_ExplicitSpecialization, 03976 Specialization, 03977 SpecInfo->getTemplateSpecializationKind(), 03978 SpecInfo->getPointOfInstantiation(), 03979 SuppressNew)) 03980 return true; 03981 03982 // Mark the prior declaration as an explicit specialization, so that later 03983 // clients know that this is an explicit specialization. 03984 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 03985 03986 // Turn the given function declaration into a function template 03987 // specialization, with the template arguments from the previous 03988 // specialization. 03989 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(), 03990 new (Context) TemplateArgumentList( 03991 *Specialization->getTemplateSpecializationArgs()), 03992 /*InsertPos=*/0, 03993 TSK_ExplicitSpecialization); 03994 03995 // The "previous declaration" for this function template specialization is 03996 // the prior function template specialization. 03997 Previous.clear(); 03998 Previous.addDecl(Specialization); 03999 return false; 04000 } 04001 04002 /// \brief Perform semantic analysis for the given non-template member 04003 /// specialization. 04004 /// 04005 /// This routine performs all of the semantic analysis required for an 04006 /// explicit member function specialization. On successful completion, 04007 /// the function declaration \p FD will become a member function 04008 /// specialization. 04009 /// 04010 /// \param Member the member declaration, which will be updated to become a 04011 /// specialization. 04012 /// 04013 /// \param Previous the set of declarations, one of which may be specialized 04014 /// by this function specialization; the set will be modified to contain the 04015 /// redeclared member. 04016 bool 04017 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { 04018 assert(!isa<TemplateDecl>(Member) && "Only for non-template members"); 04019 04020 // Try to find the member we are instantiating. 04021 NamedDecl *Instantiation = 0; 04022 NamedDecl *InstantiatedFrom = 0; 04023 MemberSpecializationInfo *MSInfo = 0; 04024 04025 if (Previous.empty()) { 04026 // Nowhere to look anyway. 04027 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) { 04028 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 04029 I != E; ++I) { 04030 NamedDecl *D = (*I)->getUnderlyingDecl(); 04031 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 04032 if (Context.hasSameType(Function->getType(), Method->getType())) { 04033 Instantiation = Method; 04034 InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); 04035 MSInfo = Method->getMemberSpecializationInfo(); 04036 break; 04037 } 04038 } 04039 } 04040 } else if (isa<VarDecl>(Member)) { 04041 VarDecl *PrevVar; 04042 if (Previous.isSingleResult() && 04043 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl()))) 04044 if (PrevVar->isStaticDataMember()) { 04045 Instantiation = PrevVar; 04046 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); 04047 MSInfo = PrevVar->getMemberSpecializationInfo(); 04048 } 04049 } else if (isa<RecordDecl>(Member)) { 04050 CXXRecordDecl *PrevRecord; 04051 if (Previous.isSingleResult() && 04052 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) { 04053 Instantiation = PrevRecord; 04054 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); 04055 MSInfo = PrevRecord->getMemberSpecializationInfo(); 04056 } 04057 } 04058 04059 if (!Instantiation) { 04060 // There is no previous declaration that matches. Since member 04061 // specializations are always out-of-line, the caller will complain about 04062 // this mismatch later. 04063 return false; 04064 } 04065 04066 // Make sure that this is a specialization of a member. 04067 if (!InstantiatedFrom) { 04068 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) 04069 << Member; 04070 Diag(Instantiation->getLocation(), diag::note_specialized_decl); 04071 return true; 04072 } 04073 04074 // C++ [temp.expl.spec]p6: 04075 // If a template, a member template or the member of a class template is 04076 // explicitly specialized then that spe- cialization shall be declared 04077 // before the first use of that specialization that would cause an implicit 04078 // instantiation to take place, in every translation unit in which such a 04079 // use occurs; no diagnostic is required. 04080 assert(MSInfo && "Member specialization info missing?"); 04081 04082 bool SuppressNew = false; 04083 if (CheckSpecializationInstantiationRedecl(Member->getLocation(), 04084 TSK_ExplicitSpecialization, 04085 Instantiation, 04086 MSInfo->getTemplateSpecializationKind(), 04087 MSInfo->getPointOfInstantiation(), 04088 SuppressNew)) 04089 return true; 04090 04091 // Check the scope of this explicit specialization. 04092 if (CheckTemplateSpecializationScope(*this, 04093 InstantiatedFrom, 04094 Instantiation, Member->getLocation(), 04095 false)) 04096 return true; 04097 04098 // Note that this is an explicit instantiation of a member. 04099 // the original declaration to note that it is an explicit specialization 04100 // (if it was previously an implicit instantiation). This latter step 04101 // makes bookkeeping easier. 04102 if (isa<FunctionDecl>(Member)) { 04103 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); 04104 if (InstantiationFunction->getTemplateSpecializationKind() == 04105 TSK_ImplicitInstantiation) { 04106 InstantiationFunction->setTemplateSpecializationKind( 04107 TSK_ExplicitSpecialization); 04108 InstantiationFunction->setLocation(Member->getLocation()); 04109 } 04110 04111 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction( 04112 cast<CXXMethodDecl>(InstantiatedFrom), 04113 TSK_ExplicitSpecialization); 04114 } else if (isa<VarDecl>(Member)) { 04115 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation); 04116 if (InstantiationVar->getTemplateSpecializationKind() == 04117 TSK_ImplicitInstantiation) { 04118 InstantiationVar->setTemplateSpecializationKind( 04119 TSK_ExplicitSpecialization); 04120 InstantiationVar->setLocation(Member->getLocation()); 04121 } 04122 04123 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member), 04124 cast<VarDecl>(InstantiatedFrom), 04125 TSK_ExplicitSpecialization); 04126 } else { 04127 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain"); 04128 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation); 04129 if (InstantiationClass->getTemplateSpecializationKind() == 04130 TSK_ImplicitInstantiation) { 04131 InstantiationClass->setTemplateSpecializationKind( 04132 TSK_ExplicitSpecialization); 04133 InstantiationClass->setLocation(Member->getLocation()); 04134 } 04135 04136 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 04137 cast<CXXRecordDecl>(InstantiatedFrom), 04138 TSK_ExplicitSpecialization); 04139 } 04140 04141 // Save the caller the trouble of having to figure out which declaration 04142 // this specialization matches. 04143 Previous.clear(); 04144 Previous.addDecl(Instantiation); 04145 return false; 04146 } 04147 04148 /// \brief Check the scope of an explicit instantiation. 04149 static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, 04150 SourceLocation InstLoc, 04151 bool WasQualifiedName) { 04152 DeclContext *ExpectedContext 04153 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext(); 04154 DeclContext *CurContext = S.CurContext->getLookupContext(); 04155 04156 // C++0x [temp.explicit]p2: 04157 // An explicit instantiation shall appear in an enclosing namespace of its 04158 // template. 04159 // 04160 // This is DR275, which we do not retroactively apply to C++98/03. 04161 if (S.getLangOptions().CPlusPlus0x && 04162 !CurContext->Encloses(ExpectedContext)) { 04163 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext)) 04164 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope) 04165 << D << NS; 04166 else 04167 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global) 04168 << D; 04169 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 04170 return; 04171 } 04172 04173 // C++0x [temp.explicit]p2: 04174 // If the name declared in the explicit instantiation is an unqualified 04175 // name, the explicit instantiation shall appear in the namespace where 04176 // its template is declared or, if that namespace is inline (7.3.1), any 04177 // namespace from its enclosing namespace set. 04178 if (WasQualifiedName) 04179 return; 04180 04181 if (CurContext->Equals(ExpectedContext)) 04182 return; 04183 04184 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace) 04185 << D << ExpectedContext; 04186 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 04187 } 04188 04189 /// \brief Determine whether the given scope specifier has a template-id in it. 04190 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { 04191 if (!SS.isSet()) 04192 return false; 04193 04194 // C++0x [temp.explicit]p2: 04195 // If the explicit instantiation is for a member function, a member class 04196 // or a static data member of a class template specialization, the name of 04197 // the class template specialization in the qualified-id for the member 04198 // name shall be a simple-template-id. 04199 // 04200 // C++98 has the same restriction, just worded differently. 04201 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 04202 NNS; NNS = NNS->getPrefix()) 04203 if (Type *T = NNS->getAsType()) 04204 if (isa<TemplateSpecializationType>(T)) 04205 return true; 04206 04207 return false; 04208 } 04209 04210 // Explicit instantiation of a class template specialization 04211 // FIXME: Implement extern template semantics 04212 Sema::DeclResult 04213 Sema::ActOnExplicitInstantiation(Scope *S, 04214 SourceLocation ExternLoc, 04215 SourceLocation TemplateLoc, 04216 unsigned TagSpec, 04217 SourceLocation KWLoc, 04218 const CXXScopeSpec &SS, 04219 TemplateTy TemplateD, 04220 SourceLocation TemplateNameLoc, 04221 SourceLocation LAngleLoc, 04222 ASTTemplateArgsPtr TemplateArgsIn, 04223 SourceLocation RAngleLoc, 04224 AttributeList *Attr) { 04225 // Find the class template we're specializing 04226 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 04227 ClassTemplateDecl *ClassTemplate 04228 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); 04229 04230 // Check that the specialization uses the same tag kind as the 04231 // original template. 04232 TagDecl::TagKind Kind; 04233 switch (TagSpec) { 04234 default: assert(0 && "Unknown tag type!"); 04235 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 04236 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 04237 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 04238 } 04239 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 04240 Kind, KWLoc, 04241 *ClassTemplate->getIdentifier())) { 04242 Diag(KWLoc, diag::err_use_with_wrong_tag) 04243 << ClassTemplate 04244 << CodeModificationHint::CreateReplacement(KWLoc, 04245 ClassTemplate->getTemplatedDecl()->getKindName()); 04246 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 04247 diag::note_previous_use); 04248 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 04249 } 04250 04251 // C++0x [temp.explicit]p2: 04252 // There are two forms of explicit instantiation: an explicit instantiation 04253 // definition and an explicit instantiation declaration. An explicit 04254 // instantiation declaration begins with the extern keyword. [...] 04255 TemplateSpecializationKind TSK 04256 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 04257 : TSK_ExplicitInstantiationDeclaration; 04258 04259 // Translate the parser's template argument list in our AST format. 04260 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 04261 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 04262 04263 // Check that the template argument list is well-formed for this 04264 // template. 04265 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 04266 TemplateArgs.size()); 04267 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 04268 TemplateArgs, false, Converted)) 04269 return true; 04270 04271 assert((Converted.structuredSize() == 04272 ClassTemplate->getTemplateParameters()->size()) && 04273 "Converted template argument list is too short!"); 04274 04275 // Find the class template specialization declaration that 04276 // corresponds to these arguments. 04277 llvm::FoldingSetNodeID ID; 04278 ClassTemplateSpecializationDecl::Profile(ID, 04279 Converted.getFlatArguments(), 04280 Converted.flatSize(), 04281 Context); 04282 void *InsertPos = 0; 04283 ClassTemplateSpecializationDecl *PrevDecl 04284 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 04285 04286 // C++0x [temp.explicit]p2: 04287 // [...] An explicit instantiation shall appear in an enclosing 04288 // namespace of its template. [...] 04289 // 04290 // This is C++ DR 275. 04291 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc, 04292 SS.isSet()); 04293 04294 ClassTemplateSpecializationDecl *Specialization = 0; 04295 04296 bool ReusedDecl = false; 04297 if (PrevDecl) { 04298 bool SuppressNew = false; 04299 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, 04300 PrevDecl, 04301 PrevDecl->getSpecializationKind(), 04302 PrevDecl->getPointOfInstantiation(), 04303 SuppressNew)) 04304 return DeclPtrTy::make(PrevDecl); 04305 04306 if (SuppressNew) 04307 return DeclPtrTy::make(PrevDecl); 04308 04309 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation || 04310 PrevDecl->getSpecializationKind() == TSK_Undeclared) { 04311 // Since the only prior class template specialization with these 04312 // arguments was referenced but not declared, reuse that 04313 // declaration node as our own, updating its source location to 04314 // reflect our new declaration. 04315 Specialization = PrevDecl; 04316 Specialization->setLocation(TemplateNameLoc); 04317 PrevDecl = 0; 04318 ReusedDecl = true; 04319 } 04320 } 04321 04322 if (!Specialization) { 04323 // Create a new class template specialization declaration node for 04324 // this explicit specialization. 04325 Specialization 04326 = ClassTemplateSpecializationDecl::Create(Context, 04327 ClassTemplate->getDeclContext(), 04328 TemplateNameLoc, 04329 ClassTemplate, 04330 Converted, PrevDecl); 04331 04332 if (PrevDecl) { 04333 // Remove the previous declaration from the folding set, since we want 04334 // to introduce a new declaration. 04335 ClassTemplate->getSpecializations().RemoveNode(PrevDecl); 04336 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 04337 } 04338 04339 // Insert the new specialization. 04340 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos); 04341 } 04342 04343 // Build the fully-sugared type for this explicit instantiation as 04344 // the user wrote in the explicit instantiation itself. This means 04345 // that we'll pretty-print the type retrieved from the 04346 // specialization's declaration the way that the user actually wrote 04347 // the explicit instantiation, rather than formatting the name based 04348 // on the "canonical" representation used to store the template 04349 // arguments in the specialization. 04350 TypeSourceInfo *WrittenTy 04351 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 04352 TemplateArgs, 04353 Context.getTypeDeclType(Specialization)); 04354 Specialization->setTypeAsWritten(WrittenTy); 04355 TemplateArgsIn.release(); 04356 04357 if (!ReusedDecl) { 04358 // Add the explicit instantiation into its lexical context. However, 04359 // since explicit instantiations are never found by name lookup, we 04360 // just put it into the declaration context directly. 04361 Specialization->setLexicalDeclContext(CurContext); 04362 CurContext->addDecl(Specialization); 04363 } 04364 04365 // C++ [temp.explicit]p3: 04366 // A definition of a class template or class member template 04367 // shall be in scope at the point of the explicit instantiation of 04368 // the class template or class member template. 04369 // 04370 // This check comes when we actually try to perform the 04371 // instantiation. 04372 ClassTemplateSpecializationDecl *Def 04373 = cast_or_null<ClassTemplateSpecializationDecl>( 04374 Specialization->getDefinition()); 04375 if (!Def) 04376 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK); 04377 04378 // Instantiate the members of this class template specialization. 04379 Def = cast_or_null<ClassTemplateSpecializationDecl>( 04380 Specialization->getDefinition()); 04381 if (Def) 04382 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK); 04383 04384 return DeclPtrTy::make(Specialization); 04385 } 04386 04387 // Explicit instantiation of a member class of a class template. 04388 Sema::DeclResult 04389 Sema::ActOnExplicitInstantiation(Scope *S, 04390 SourceLocation ExternLoc, 04391 SourceLocation TemplateLoc, 04392 unsigned TagSpec, 04393 SourceLocation KWLoc, 04394 const CXXScopeSpec &SS, 04395 IdentifierInfo *Name, 04396 SourceLocation NameLoc, 04397 AttributeList *Attr) { 04398 04399 bool Owned = false; 04400 bool IsDependent = false; 04401 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference, 04402 KWLoc, SS, Name, NameLoc, Attr, AS_none, 04403 MultiTemplateParamsArg(*this, 0, 0), 04404 Owned, IsDependent); 04405 assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); 04406 04407 if (!TagD) 04408 return true; 04409 04410 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 04411 if (Tag->isEnum()) { 04412 Diag(TemplateLoc, diag::err_explicit_instantiation_enum) 04413 << Context.getTypeDeclType(Tag); 04414 return true; 04415 } 04416 04417 if (Tag->isInvalidDecl()) 04418 return true; 04419 04420 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 04421 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 04422 if (!Pattern) { 04423 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 04424 << Context.getTypeDeclType(Record); 04425 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 04426 return true; 04427 } 04428 04429 // C++0x [temp.explicit]p2: 04430 // If the explicit instantiation is for a class or member class, the 04431 // elaborated-type-specifier in the declaration shall include a 04432 // simple-template-id. 04433 // 04434 // C++98 has the same restriction, just worded differently. 04435 if (!ScopeSpecifierHasTemplateId(SS)) 04436 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id) 04437 << Record << SS.getRange(); 04438 04439 // C++0x [temp.explicit]p2: 04440 // There are two forms of explicit instantiation: an explicit instantiation 04441 // definition and an explicit instantiation declaration. An explicit 04442 // instantiation declaration begins with the extern keyword. [...] 04443 TemplateSpecializationKind TSK 04444 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 04445 : TSK_ExplicitInstantiationDeclaration; 04446 04447 // C++0x [temp.explicit]p2: 04448 // [...] An explicit instantiation shall appear in an enclosing 04449 // namespace of its template. [...] 04450 // 04451 // This is C++ DR 275. 04452 CheckExplicitInstantiationScope(*this, Record, NameLoc, true); 04453 04454 // Verify that it is okay to explicitly instantiate here. 04455 CXXRecordDecl *PrevDecl 04456 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration()); 04457 if (!PrevDecl && Record->getDefinition()) 04458 PrevDecl = Record; 04459 if (PrevDecl) { 04460 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); 04461 bool SuppressNew = false; 04462 assert(MSInfo && "No member specialization information?"); 04463 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, 04464 PrevDecl, 04465 MSInfo->getTemplateSpecializationKind(), 04466 MSInfo->getPointOfInstantiation(), 04467 SuppressNew)) 04468 return true; 04469 if (SuppressNew) 04470 return TagD; 04471 } 04472 04473 CXXRecordDecl *RecordDef 04474 = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 04475 if (!RecordDef) { 04476 // C++ [temp.explicit]p3: 04477 // A definition of a member class of a class template shall be in scope 04478 // at the point of an explicit instantiation of the member class. 04479 CXXRecordDecl *Def 04480 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 04481 if (!Def) { 04482 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) 04483 << 0 << Record->getDeclName() << Record->getDeclContext(); 04484 Diag(Pattern->getLocation(), diag::note_forward_declaration) 04485 << Pattern; 04486 return true; 04487 } else { 04488 if (InstantiateClass(NameLoc, Record, Def, 04489 getTemplateInstantiationArgs(Record), 04490 TSK)) 04491 return true; 04492 04493 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 04494 if (!RecordDef) 04495 return true; 04496 } 04497 } 04498 04499 // Instantiate all of the members of the class. 04500 InstantiateClassMembers(NameLoc, RecordDef, 04501 getTemplateInstantiationArgs(Record), TSK); 04502 04503 // FIXME: We don't have any representation for explicit instantiations of 04504 // member classes. Such a representation is not needed for compilation, but it 04505 // should be available for clients that want to see all of the declarations in 04506 // the source code. 04507 return TagD; 04508 } 04509 04510 Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S, 04511 SourceLocation ExternLoc, 04512 SourceLocation TemplateLoc, 04513 Declarator &D) { 04514 // Explicit instantiations always require a name. 04515 DeclarationName Name = GetNameForDeclarator(D); 04516 if (!Name) { 04517 if (!D.isInvalidType()) 04518 Diag(D.getDeclSpec().getSourceRange().getBegin(), 04519 diag::err_explicit_instantiation_requires_name) 04520 << D.getDeclSpec().getSourceRange() 04521 << D.getSourceRange(); 04522 04523 return true; 04524 } 04525 04526 // The scope passed in may not be a decl scope. Zip up the scope tree until 04527 // we find one that is. 04528 while ((S->getFlags() & Scope::DeclScope) == 0 || 04529 (S->getFlags() & Scope::TemplateParamScope) != 0) 04530 S = S->getParent(); 04531 04532 // Determine the type of the declaration. 04533 QualType R = GetTypeForDeclarator(D, S, 0); 04534 if (R.isNull()) 04535 return true; 04536 04537 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 04538 // Cannot explicitly instantiate a typedef. 04539 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) 04540 << Name; 04541 return true; 04542 } 04543 04544 // C++0x [temp.explicit]p1: 04545 // [...] An explicit instantiation of a function template shall not use the 04546 // inline or constexpr specifiers. 04547 // Presumably, this also applies to member functions of class templates as 04548 // well. 04549 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x) 04550 Diag(D.getDeclSpec().getInlineSpecLoc(), 04551 diag::err_explicit_instantiation_inline) 04552 <<CodeModificationHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 04553 04554 // FIXME: check for constexpr specifier. 04555 04556 // C++0x [temp.explicit]p2: 04557 // There are two forms of explicit instantiation: an explicit instantiation 04558 // definition and an explicit instantiation declaration. An explicit 04559 // instantiation declaration begins with the extern keyword. [...] 04560 TemplateSpecializationKind TSK 04561 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 04562 : TSK_ExplicitInstantiationDeclaration; 04563 04564 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName); 04565 LookupParsedName(Previous, S, &D.getCXXScopeSpec()); 04566 04567 if (!R->isFunctionType()) { 04568 // C++ [temp.explicit]p1: 04569 // A [...] static data member of a class template can be explicitly 04570 // instantiated from the member definition associated with its class 04571 // template. 04572 if (Previous.isAmbiguous()) 04573 return true; 04574 04575 VarDecl *Prev = Previous.getAsSingle<VarDecl>(); 04576 if (!Prev || !Prev->isStaticDataMember()) { 04577 // We expect to see a data data member here. 04578 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) 04579 << Name; 04580 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 04581 P != PEnd; ++P) 04582 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); 04583 return true; 04584 } 04585 04586 if (!Prev->getInstantiatedFromStaticDataMember()) { 04587 // FIXME: Check for explicit specialization? 04588 Diag(D.getIdentifierLoc(), 04589 diag::err_explicit_instantiation_data_member_not_instantiated) 04590 << Prev; 04591 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); 04592 // FIXME: Can we provide a note showing where this was declared? 04593 return true; 04594 } 04595 04596 // C++0x [temp.explicit]p2: 04597 // If the explicit instantiation is for a member function, a member class 04598 // or a static data member of a class template specialization, the name of 04599 // the class template specialization in the qualified-id for the member 04600 // name shall be a simple-template-id. 04601 // 04602 // C++98 has the same restriction, just worded differently. 04603 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 04604 Diag(D.getIdentifierLoc(), 04605 diag::err_explicit_instantiation_without_qualified_id) 04606 << Prev << D.getCXXScopeSpec().getRange(); 04607 04608 // Check the scope of this explicit instantiation. 04609 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true); 04610 04611 // Verify that it is okay to explicitly instantiate here. 04612 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo(); 04613 assert(MSInfo && "Missing static data member specialization info?"); 04614 bool SuppressNew = false; 04615 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, 04616 MSInfo->getTemplateSpecializationKind(), 04617 MSInfo->getPointOfInstantiation(), 04618 SuppressNew)) 04619 return true; 04620 if (SuppressNew) 04621 return DeclPtrTy(); 04622 04623 // Instantiate static data member. 04624 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 04625 if (TSK == TSK_ExplicitInstantiationDefinition) 04626 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false, 04627 /*DefinitionRequired=*/true); 04628 04629 // FIXME: Create an ExplicitInstantiation node? 04630 return DeclPtrTy(); 04631 } 04632 04633 // If the declarator is a template-id, translate the parser's template 04634 // argument list into our AST format. 04635 bool HasExplicitTemplateArgs = false; 04636 TemplateArgumentListInfo TemplateArgs; 04637 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 04638 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 04639 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 04640 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 04641 ASTTemplateArgsPtr TemplateArgsPtr(*this, 04642 TemplateId->getTemplateArgs(), 04643 TemplateId->NumArgs); 04644 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 04645 HasExplicitTemplateArgs = true; 04646 TemplateArgsPtr.release(); 04647 } 04648 04649 // C++ [temp.explicit]p1: 04650 // A [...] function [...] can be explicitly instantiated from its template. 04651 // A member function [...] of a class template can be explicitly 04652 // instantiated from the member definition associated with its class 04653 // template. 04654 UnresolvedSet<8> Matches; 04655 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 04656 P != PEnd; ++P) { 04657 NamedDecl *Prev = *P; 04658 if (!HasExplicitTemplateArgs) { 04659 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { 04660 if (Context.hasSameUnqualifiedType(Method->getType(), R)) { 04661 Matches.clear(); 04662 04663 Matches.addDecl(Method, P.getAccess()); 04664 if (Method->getTemplateSpecializationKind() == TSK_Undeclared) 04665 break; 04666 } 04667 } 04668 } 04669 04670 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); 04671 if (!FunTmpl) 04672 continue; 04673 04674 TemplateDeductionInfo Info(Context, D.getIdentifierLoc()); 04675 FunctionDecl *Specialization = 0; 04676 if (TemplateDeductionResult TDK 04677 = DeduceTemplateArguments(FunTmpl, 04678 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 04679 R, Specialization, Info)) { 04680 // FIXME: Keep track of almost-matches? 04681 (void)TDK; 04682 continue; 04683 } 04684 04685 Matches.addDecl(Specialization, P.getAccess()); 04686 } 04687 04688 // Find the most specialized function template specialization. 04689 UnresolvedSetIterator Result 04690 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 04691 D.getIdentifierLoc(), 04692 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name, 04693 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name, 04694 PartialDiagnostic(diag::note_explicit_instantiation_candidate)); 04695 04696 if (Result == Matches.end()) 04697 return true; 04698 04699 // Ignore access control bits, we don't need them for redeclaration checking. 04700 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 04701 04702 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { 04703 Diag(D.getIdentifierLoc(), 04704 diag::err_explicit_instantiation_member_function_not_instantiated) 04705 << Specialization 04706 << (Specialization->getTemplateSpecializationKind() == 04707 TSK_ExplicitSpecialization); 04708 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); 04709 return true; 04710 } 04711 04712 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration(); 04713 if (!PrevDecl && Specialization->isThisDeclarationADefinition()) 04714 PrevDecl = Specialization; 04715 04716 if (PrevDecl) { 04717 bool SuppressNew = false; 04718 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, 04719 PrevDecl, 04720 PrevDecl->getTemplateSpecializationKind(), 04721 PrevDecl->getPointOfInstantiation(), 04722 SuppressNew)) 04723 return true; 04724 04725 // FIXME: We may still want to build some representation of this 04726 // explicit specialization. 04727 if (SuppressNew) 04728 return DeclPtrTy(); 04729 } 04730 04731 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 04732 04733 if (TSK == TSK_ExplicitInstantiationDefinition) 04734 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization, 04735 false, /*DefinitionRequired=*/true); 04736 04737 // C++0x [temp.explicit]p2: 04738 // If the explicit instantiation is for a member function, a member class 04739 // or a static data member of a class template specialization, the name of 04740 // the class template specialization in the qualified-id for the member 04741 // name shall be a simple-template-id. 04742 // 04743 // C++98 has the same restriction, just worded differently. 04744 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); 04745 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl && 04746 D.getCXXScopeSpec().isSet() && 04747 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 04748 Diag(D.getIdentifierLoc(), 04749 diag::err_explicit_instantiation_without_qualified_id) 04750 << Specialization << D.getCXXScopeSpec().getRange(); 04751 04752 CheckExplicitInstantiationScope(*this, 04753 FunTmpl? (NamedDecl *)FunTmpl 04754 : Specialization->getInstantiatedFromMemberFunction(), 04755 D.getIdentifierLoc(), 04756 D.getCXXScopeSpec().isSet()); 04757 04758 // FIXME: Create some kind of ExplicitInstantiationDecl here. 04759 return DeclPtrTy(); 04760 } 04761 04762 Sema::TypeResult 04763 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 04764 const CXXScopeSpec &SS, IdentifierInfo *Name, 04765 SourceLocation TagLoc, SourceLocation NameLoc) { 04766 // This has to hold, because SS is expected to be defined. 04767 assert(Name && "Expected a name in a dependent tag"); 04768 04769 NestedNameSpecifier *NNS 04770 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 04771 if (!NNS) 04772 return true; 04773 04774 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc)); 04775 if (T.isNull()) 04776 return true; 04777 04778 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec); 04779 QualType ElabType = Context.getElaboratedType(T, TagKind); 04780 04781 return ElabType.getAsOpaquePtr(); 04782 } 04783 04784 Sema::TypeResult 04785 Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, 04786 const IdentifierInfo &II, SourceLocation IdLoc) { 04787 NestedNameSpecifier *NNS 04788 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 04789 if (!NNS) 04790 return true; 04791 04792 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc)); 04793 if (T.isNull()) 04794 return true; 04795 return T.getAsOpaquePtr(); 04796 } 04797 04798 Sema::TypeResult 04799 Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, 04800 SourceLocation TemplateLoc, TypeTy *Ty) { 04801 QualType T = GetTypeFromParser(Ty); 04802 NestedNameSpecifier *NNS 04803 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 04804 const TemplateSpecializationType *TemplateId 04805 = T->getAs<TemplateSpecializationType>(); 04806 assert(TemplateId && "Expected a template specialization type"); 04807 04808 if (computeDeclContext(SS, false)) { 04809 // If we can compute a declaration context, then the "typename" 04810 // keyword was superfluous. Just build a QualifiedNameType to keep 04811 // track of the nested-name-specifier. 04812 04813 // FIXME: Note that the QualifiedNameType had the "typename" keyword! 04814 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr(); 04815 } 04816 04817 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr(); 04818 } 04819 04820 /// \brief Build the type that describes a C++ typename specifier, 04821 /// e.g., "typename T::type". 04822 QualType 04823 Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II, 04824 SourceRange Range) { 04825 CXXRecordDecl *CurrentInstantiation = 0; 04826 if (NNS->isDependent()) { 04827 CurrentInstantiation = getCurrentInstantiationOf(NNS); 04828 04829 // If the nested-name-specifier does not refer to the current 04830 // instantiation, then build a typename type. 04831 if (!CurrentInstantiation) 04832 return Context.getTypenameType(NNS, &II); 04833 04834 // The nested-name-specifier refers to the current instantiation, so the 04835 // "typename" keyword itself is superfluous. In C++03, the program is 04836 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such 04837 // extraneous "typename" keywords, and we retroactively apply this DR to 04838 // C++03 code. 04839 } 04840 04841 DeclContext *Ctx = 0; 04842 04843 if (CurrentInstantiation) 04844 Ctx = CurrentInstantiation; 04845 else { 04846 CXXScopeSpec SS; 04847 SS.setScopeRep(NNS); 04848 SS.setRange(Range); 04849 if (RequireCompleteDeclContext(SS)) 04850 return QualType(); 04851 04852 Ctx = computeDeclContext(SS); 04853 } 04854 assert(Ctx && "No declaration context?"); 04855 04856 DeclarationName Name(&II); 04857 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName); 04858 LookupQualifiedName(Result, Ctx); 04859 unsigned DiagID = 0; 04860 Decl *Referenced = 0; 04861 switch (Result.getResultKind()) { 04862 case LookupResult::NotFound: 04863 DiagID = diag::err_typename_nested_not_found; 04864 break; 04865 04866 case LookupResult::NotFoundInCurrentInstantiation: 04867 // Okay, it's a member of an unknown instantiation. 04868 return Context.getTypenameType(NNS, &II); 04869 04870 case LookupResult::Found: 04871 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) { 04872 // We found a type. Build a QualifiedNameType, since the 04873 // typename-specifier was just sugar. FIXME: Tell 04874 // QualifiedNameType that it has a "typename" prefix. 04875 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type)); 04876 } 04877 04878 DiagID = diag::err_typename_nested_not_type; 04879 Referenced = Result.getFoundDecl(); 04880 break; 04881 04882 case LookupResult::FoundUnresolvedValue: 04883 llvm_unreachable("unresolved using decl in non-dependent context"); 04884 return QualType(); 04885 04886 case LookupResult::FoundOverloaded: 04887 DiagID = diag::err_typename_nested_not_type; 04888 Referenced = *Result.begin(); 04889 break; 04890 04891 case LookupResult::Ambiguous: 04892 return QualType(); 04893 } 04894 04895 // If we get here, it's because name lookup did not find a 04896 // type. Emit an appropriate diagnostic and return an error. 04897 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx; 04898 if (Referenced) 04899 Diag(Referenced->getLocation(), diag::note_typename_refers_here) 04900 << Name; 04901 return QualType(); 04902 } 04903 04904 namespace { 04905 // See Sema::RebuildTypeInCurrentInstantiation 04906 class CurrentInstantiationRebuilder 04907 : public TreeTransform<CurrentInstantiationRebuilder> { 04908 SourceLocation Loc; 04909 DeclarationName Entity; 04910 04911 public: 04912 CurrentInstantiationRebuilder(Sema &SemaRef, 04913 SourceLocation Loc, 04914 DeclarationName Entity) 04915 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), 04916 Loc(Loc), Entity(Entity) { } 04917 04918 /// \brief Determine whether the given type \p T has already been 04919 /// transformed. 04920 /// 04921 /// For the purposes of type reconstruction, a type has already been 04922 /// transformed if it is NULL or if it is not dependent. 04923 bool AlreadyTransformed(QualType T) { 04924 return T.isNull() || !T->isDependentType(); 04925 } 04926 04927 /// \brief Returns the location of the entity whose type is being 04928 /// rebuilt. 04929 SourceLocation getBaseLocation() { return Loc; } 04930 04931 /// \brief Returns the name of the entity whose type is being rebuilt. 04932 DeclarationName getBaseEntity() { return Entity; } 04933 04934 /// \brief Sets the "base" location and entity when that 04935 /// information is known based on another transformation. 04936 void setBase(SourceLocation Loc, DeclarationName Entity) { 04937 this->Loc = Loc; 04938 this->Entity = Entity; 04939 } 04940 04941 /// \brief Transforms an expression by returning the expression itself 04942 /// (an identity function). 04943 /// 04944 /// FIXME: This is completely unsafe; we will need to actually clone the 04945 /// expressions. 04946 Sema::OwningExprResult TransformExpr(Expr *E) { 04947 return getSema().Owned(E); 04948 } 04949 04950 /// \brief Transforms a typename type by determining whether the type now 04951 /// refers to a member of the current instantiation, and then 04952 /// type-checking and building a QualifiedNameType (when possible). 04953 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL, 04954 QualType ObjectType); 04955 }; 04956 } 04957 04958 QualType 04959 CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB, 04960 TypenameTypeLoc TL, 04961 QualType ObjectType) { 04962 TypenameType *T = TL.getTypePtr(); 04963 04964 NestedNameSpecifier *NNS 04965 = TransformNestedNameSpecifier(T->getQualifier(), 04966 /*FIXME:*/SourceRange(getBaseLocation()), 04967 ObjectType); 04968 if (!NNS) 04969 return QualType(); 04970 04971 // If the nested-name-specifier did not change, and we cannot compute the 04972 // context corresponding to the nested-name-specifier, then this 04973 // typename type will not change; exit early. 04974 CXXScopeSpec SS; 04975 SS.setRange(SourceRange(getBaseLocation())); 04976 SS.setScopeRep(NNS); 04977 04978 QualType Result; 04979 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0) 04980 Result = QualType(T, 0); 04981 04982 // Rebuild the typename type, which will probably turn into a 04983 // QualifiedNameType. 04984 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) { 04985 QualType NewTemplateId 04986 = TransformType(QualType(TemplateId, 0)); 04987 if (NewTemplateId.isNull()) 04988 return QualType(); 04989 04990 if (NNS == T->getQualifier() && 04991 NewTemplateId == QualType(TemplateId, 0)) 04992 Result = QualType(T, 0); 04993 else 04994 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId); 04995 } else 04996 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(), 04997 SourceRange(TL.getNameLoc())); 04998 04999 if (Result.isNull()) 05000 return QualType(); 05001 05002 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result); 05003 NewTL.setNameLoc(TL.getNameLoc()); 05004 return Result; 05005 } 05006 05007 /// \brief Rebuilds a type within the context of the current instantiation. 05008 /// 05009 /// The type \p T is part of the type of an out-of-line member definition of 05010 /// a class template (or class template partial specialization) that was parsed 05011 /// and constructed before we entered the scope of the class template (or 05012 /// partial specialization thereof). This routine will rebuild that type now 05013 /// that we have entered the declarator's scope, which may produce different 05014 /// canonical types, e.g., 05015 /// 05016 /// \code 05017 /// template<typename T> 05018 /// struct X { 05019 /// typedef T* pointer; 05020 /// pointer data(); 05021 /// }; 05022 /// 05023 /// template<typename T> 05024 /// typename X<T>::pointer X<T>::data() { ... } 05025 /// \endcode 05026 /// 05027 /// Here, the type "typename X<T>::pointer" will be created as a TypenameType, 05028 /// since we do not know that we can look into X<T> when we parsed the type. 05029 /// This function will rebuild the type, performing the lookup of "pointer" 05030 /// in X<T> and returning a QualifiedNameType whose canonical type is the same 05031 /// as the canonical type of T*, allowing the return types of the out-of-line 05032 /// definition and the declaration to match. 05033 QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc, 05034 DeclarationName Name) { 05035 if (T.isNull() || !T->isDependentType()) 05036 return T; 05037 05038 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); 05039 return Rebuilder.TransformType(T); 05040 } 05041 05042 /// \brief Produces a formatted string that describes the binding of 05043 /// template parameters to template arguments. 05044 std::string 05045 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 05046 const TemplateArgumentList &Args) { 05047 // FIXME: For variadic templates, we'll need to get the structured list. 05048 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(), 05049 Args.flat_size()); 05050 } 05051 05052 std::string 05053 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 05054 const TemplateArgument *Args, 05055 unsigned NumArgs) { 05056 std::string Result; 05057 05058 if (!Params || Params->size() == 0 || NumArgs == 0) 05059 return Result; 05060 05061 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 05062 if (I >= NumArgs) 05063 break; 05064 05065 if (I == 0) 05066 Result += "[with "; 05067 else 05068 Result += ", "; 05069 05070 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { 05071 Result += Id->getName(); 05072 } else { 05073 Result += '$'; 05074 Result += llvm::utostr(I); 05075 } 05076 05077 Result += " = "; 05078 05079 switch (Args[I].getKind()) { 05080 case TemplateArgument::Null: 05081 Result += "<no value>"; 05082 break; 05083 05084 case TemplateArgument::Type: { 05085 std::string TypeStr; 05086 Args[I].getAsType().getAsStringInternal(TypeStr, 05087 Context.PrintingPolicy); 05088 Result += TypeStr; 05089 break; 05090 } 05091 05092 case TemplateArgument::Declaration: { 05093 bool Unnamed = true; 05094 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) { 05095 if (ND->getDeclName()) { 05096 Unnamed = false; 05097 Result += ND->getNameAsString(); 05098 } 05099 } 05100 05101 if (Unnamed) { 05102 Result += "<anonymous>"; 05103 } 05104 break; 05105 } 05106 05107 case TemplateArgument::Template: { 05108 std::string Str; 05109 llvm::raw_string_ostream OS(Str); 05110 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy); 05111 Result += OS.str(); 05112 break; 05113 } 05114 05115 case TemplateArgument::Integral: { 05116 Result += Args[I].getAsIntegral()->toString(10); 05117 break; 05118 } 05119 05120 case TemplateArgument::Expression: { 05121 assert(false && "No expressions in deduced template arguments!"); 05122 Result += "<expression>"; 05123 break; 05124 } 05125 05126 case TemplateArgument::Pack: 05127 // FIXME: Format template argument packs 05128 Result += "<template argument pack>"; 05129 break; 05130 } 05131 } 05132 05133 Result += ']'; 05134 return Result; 05135 }