Skip to content

Commit

Permalink
Fix variance checking in refinements (#18053)
Browse files Browse the repository at this point in the history
Do variance checks for parameters in method types and poly types of
refinements.

Fixes #18035
  • Loading branch information
odersky authored Jul 3, 2023
2 parents 347a567 + 721b57e commit 0a21ecf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
10 changes: 7 additions & 3 deletions compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,6 @@ class VarianceChecker(using Context) {
case TypeAlias(alias) => this(status, alias)
case _ => foldOver(status, tp)
}
case tp: MethodOrPoly =>
this(status, tp.resultType) // params will be checked in their TypeDef or ValDef nodes.
case AnnotatedType(_, annot) if annot.symbol == defn.UncheckedVarianceAnnot =>
status
case tp: ClassInfo =>
Expand All @@ -144,10 +142,16 @@ class VarianceChecker(using Context) {
}
}

def checkInfo(info: Type): Option[VarianceError] = info match
case info: MethodOrPoly =>
checkInfo(info.resultType) // params will be checked in their TypeDef or ValDef nodes.
case _ =>
apply(None, info)

def validateDefinition(base: Symbol): Option[VarianceError] = {
val saved = this.base
this.base = base
try apply(None, base.info)
try checkInfo(base.info)
finally this.base = saved
}
}
Expand Down
15 changes: 15 additions & 0 deletions tests/neg/i18035.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import reflect.Selectable.reflectiveSelectable

class A[+Cov](f: Cov => Unit) {
def foo: { def apply(c: Cov): Unit } = // error
f
}

val aForString = new A[String](_.length)
// => val aForString: A[String]

val aForStringIsAForAny: A[Any] = aForString
// => val aForStringIsAForAny: A[Any]

val _ = aForStringIsAForAny.foo(123)
// => java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')

0 comments on commit 0a21ecf

Please sign in to comment.