Skip to content

Commit 3694aa9

Browse files
committed
Fix #1828: add warning when patternmatching on generics
1 parent 52c869c commit 3694aa9

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

compiler/src/dotty/tools/dotc/transform/IsInstanceOfEvaluator.scala

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,11 @@ class IsInstanceOfEvaluator extends MiniPhaseTransform { thisTransformer =>
147147

148148
val inMatch = s.qualifier.symbol is Case
149149

150-
if (valueClassesOrAny) tree
151-
else if (knownStatically)
150+
if (valueClassesOrAny) {
151+
if (selector eq defn.ObjectType)
152+
ctx.warning(i"abstract type pattern is unchecked since it is eliminated by erasure", tree.pos)
153+
tree
154+
} else if (knownStatically)
152155
handleStaticallyKnown(s, scrutinee, selector, inMatch, tree.pos)
153156
else if (falseIfUnrelated && scrutinee <:< selector)
154157
// scrutinee is a subtype of the selector, safe to rewrite

tests/repl/errmsgs.check

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,19 @@ scala> class Foo() { def bar: Int = 1 }; val foo = new Foo(); foo.barr
7878
4 |class Foo() { def bar: Int = 1 }; val foo = new Foo(); foo.barr
7979
| ^^^^^^^^
8080
| value `barr` is not a member of Foo(foo) - did you mean `foo.bar`?
81+
scala> def unsafeCast[S](a: Any) = a match { case s: S => s; case _ => ??? }
82+
-- Warning: <console> ----------------------------------------------------------
83+
4 |def unsafeCast[S](a: Any) = a match { case s: S => s; case _ => ??? }
84+
| ^
85+
| abstract type pattern is unchecked since it is eliminated by erasure
86+
def unsafeCast[S](a: Any): [S] => (a: Any)S
87+
scala> unsafeCast[String](1)
88+
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
89+
at .<init>(<console>:6)
90+
at .<clinit>(<console>)
91+
at RequestResult$.<init>(<console>:3)
92+
at RequestResult$.<clinit>(<console>)
93+
at RequestResult$result(<console>)
94+
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
95+
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.jav...
8196
scala> :quit

0 commit comments

Comments
 (0)