Skip to content

Commit 0a21ecf

Browse files
authored
Fix variance checking in refinements (#18053)
Do variance checks for parameters in method types and poly types of refinements. Fixes #18035
2 parents 347a567 + 721b57e commit 0a21ecf

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

compiler/src/dotty/tools/dotc/typer/VarianceChecker.scala

+7-3
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,6 @@ class VarianceChecker(using Context) {
130130
case TypeAlias(alias) => this(status, alias)
131131
case _ => foldOver(status, tp)
132132
}
133-
case tp: MethodOrPoly =>
134-
this(status, tp.resultType) // params will be checked in their TypeDef or ValDef nodes.
135133
case AnnotatedType(_, annot) if annot.symbol == defn.UncheckedVarianceAnnot =>
136134
status
137135
case tp: ClassInfo =>
@@ -144,10 +142,16 @@ class VarianceChecker(using Context) {
144142
}
145143
}
146144

145+
def checkInfo(info: Type): Option[VarianceError] = info match
146+
case info: MethodOrPoly =>
147+
checkInfo(info.resultType) // params will be checked in their TypeDef or ValDef nodes.
148+
case _ =>
149+
apply(None, info)
150+
147151
def validateDefinition(base: Symbol): Option[VarianceError] = {
148152
val saved = this.base
149153
this.base = base
150-
try apply(None, base.info)
154+
try checkInfo(base.info)
151155
finally this.base = saved
152156
}
153157
}

tests/neg/i18035.scala

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import reflect.Selectable.reflectiveSelectable
2+
3+
class A[+Cov](f: Cov => Unit) {
4+
def foo: { def apply(c: Cov): Unit } = // error
5+
f
6+
}
7+
8+
val aForString = new A[String](_.length)
9+
// => val aForString: A[String]
10+
11+
val aForStringIsAForAny: A[Any] = aForString
12+
// => val aForStringIsAForAny: A[Any]
13+
14+
val _ = aForStringIsAForAny.foo(123)
15+
// => 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 commit comments

Comments
 (0)