From 756e551b30461b548ea59e99562634775b7ebd74 Mon Sep 17 00:00:00 2001 From: Antoine Gourlay Date: Thu, 31 Jul 2014 17:52:13 +0200 Subject: SI-5691 lint warning when a type parameter shadows an existing type. This adds a new lint warning for when a class/method/type-member's type parameter shadows an existing type: `-Xlint:type-parameter-shadow`. It excludes type parameters of synthetic methods (the user can't rename or remove those anyway), otherwise, for example, every case class triggers the warning. Also fixes a test that contained wrong java sources (that didn't even compile...), discovered thanks to the warning. --- This kind of errors shows up every now and then on the mailing-list, on stackoverflow, etc. so maybe a warning would be useful. I was afraid this would yield too many warnings for libraries that are heavy on type parameters, but no: running this on scalaz and shapeless HEAD (`v7.1.0-RC1-41-g1cc0a96` and `v2.0.0-M1-225-g78426a0` respectively) yields 44 warnings. None of them are false positives; they usually come from: - scalaz loving using `A` as type parameter, even several levels deep of parametrized classes/methods - or calling a type parameter that will hold a map `Map`, or similar, thus shadowing an existing type --- .../scala/tools/nsc/typechecker/TypeDiagnostics.scala | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala') diff --git a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala index 7440f69e93..d18348f51e 100644 --- a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala +++ b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala @@ -600,6 +600,23 @@ trait TypeDiagnostics { ) } + // warn about class/method/type-members' type parameters that shadow types already in scope + def warnTypeParameterShadow(tparams: List[TypeDef], sym: Symbol): Unit = + if (settings.warnTypeParameterShadow && !isPastTyper && !sym.isSynthetic) { + def enclClassOrMethodOrTypeMember(c: Context): Context = + if (!c.owner.exists || c.owner.isClass || c.owner.isMethod || (c.owner.isType && !c.owner.isParameter)) c + else enclClassOrMethodOrTypeMember(c.outer) + + val tt = tparams.filter(_.name != typeNames.WILDCARD).foreach { tp => + // we don't care about type params shadowing other type params in the same declaration + enclClassOrMethodOrTypeMember(context).outer.lookupSymbol(tp.name, s => s != tp.symbol && s.hasRawInfo && reallyExists(s)) match { + case LookupSucceeded(_, sym2) => context.warning(tp.pos, + s"type parameter ${tp.name} defined in $sym shadows $sym2 defined in ${sym2.owner}. You may want to rename your type parameter, or possibly remove it.") + case _ => + } + } + } + /** Report a type error. * * @param pos The position where to report the error -- cgit v1.2.3