Skip to content

Commit

Permalink
A tweak to type improvement (#21312)
Browse files Browse the repository at this point in the history
When we replace Nothing by a fresh type variable, we should not
accidentally instantiate that type variable to Any in case it is still
undetermined. We achieve this by giving the type variable a slightly
disguised version of Nothing which makes the compiler believe it has a
lower bound.

Fixes #21275
  • Loading branch information
odersky authored Aug 2, 2024
2 parents 6c4eace + 0205871 commit ceb359b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
10 changes: 9 additions & 1 deletion compiler/src/dotty/tools/dotc/typer/Inferencing.scala
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,15 @@ object Inferencing {
t match
case t: TypeRef =>
if t.symbol == defn.NothingClass then
newTypeVar(TypeBounds.empty, nestingLevel = tvar.nestingLevel)
val notExactlyNothing = LazyRef(_ => defn.NothingType)
val bounds = TypeBounds(notExactlyNothing, defn.AnyType)
// The new type variale has a slightly disguised lower bound Nothing.
// This foils the `isExactlyNothing` test in `hasLowerBound` and
// therefore makes the new type variable have a lower bound. That way,
// we favor in `apply` below instantiating from below to `Nothing` instead
// of from above to `Any`. That avoids a spurious flip of the original `Nothing`
// instance to `Any`. See i21275 for a test case.
newTypeVar(bounds, nestingLevel = tvar.nestingLevel)
else if t.symbol.is(ModuleClass) then
tryWidened(t.parents.filter(!_.isTransparent())
.foldLeft(defn.AnyType: Type)(TypeComparer.andType(_, _)))
Expand Down
10 changes: 10 additions & 0 deletions tests/pos/i21275.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Box[+O]:
def ++[O2 >: O](other: Box[O2]): Box[O2] = ???
object Box:
val empty: Box[Nothing] = ???

def test[T]: Box[T] =
List(Box.empty, Box.empty)
// .reduceOption[Box[T]](_ ++ _) // works
.reduceOption(_ ++ _) // fails
.getOrElse(Box.empty)

0 comments on commit ceb359b

Please sign in to comment.