scala / scala3

The Scala 3 compiler, also known as Dotty.
https://dotty.epfl.ch
Apache License 2.0
5.84k stars 1.05k forks source link

Type avoidance does not take type parameter bounds in account and can produce invalid types #6205

Open smarter opened 5 years ago

smarter commented 5 years ago

Given:

class Contra[-T >: Null]

object Test {
  def foo = {
    class A

    new Contra[A]
  }
}

The inferred type of foo is Contra[Nothing], but this isn't a legal type (and indeed writing it down would produce a Type argument Nothing does not conform to lower bound Null error). It seems that ApproximatingTypeMap#derivedAppliedType is missing logic to replace Ranges by types which are in bounds. Moreover, -Ycheck should be enhanced to detect this kind of bound violations.

odersky commented 4 years ago

This is now detected with #8462. We now get:

4 |  def foo =
  |         ^
  |Type argument Nothing does not conform to lower bound Null in inferred type Contra[Nothing]

It would be even better if we could avoid bad instantiations, so I leave this issue open. But it is not that easy to do so. In the particular example, we need to avoid class A, which leads to a range of Nothing .. A, which is immediately simplified to Nothing, since we are in a contravariant context. So then the type map would have to change inferred arguments bounds one level up when it gets to the applied type Contra[Nothing]. Furthermore, it would have to find a "solution" even in cases where we have F-bounds, which is impossible in general, so there would still have to be a path where we issue an error.

If the problem happens only rarely, I think it's acceptable to just tell the user that the instantiation is ill-formed and they should add an explicit type instead.

smarter commented 4 years ago

Furthermore, it would have to find a "solution" even in cases where we have F-bounds, which is impossible in general, so there would still have to be a path where we issue an error.

I think you can always use wildcard arguments as a fallback solution.