Skip to content

Commit 1eb1d93

Browse files
committed
Fix scala#1828: add warning when patternmatching on generics
1 parent 586113d commit 1eb1d93

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
@@ -148,8 +148,11 @@ class IsInstanceOfEvaluator extends MiniPhaseTransform { thisTransformer =>
148148

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

151-
if (valueClassesOrAny) tree
152-
else if (knownStatically)
151+
if (valueClassesOrAny) {
152+
if (selector eq defn.ObjectType)
153+
ctx.warning(i"abstract type pattern is unchecked since it is eliminated by erasure", tree.pos)
154+
tree
155+
} else if (knownStatically)
153156
handleStaticallyKnown(s, scrutinee, selector, inMatch, tree.pos)
154157
else if (falseIfUnrelated && scrutinee <:< selector)
155158
// 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
@@ -92,4 +92,19 @@ scala> { def f: Int = g; val x: Int = 1; def g: Int = 5; }
9292
| `g` is a forward reference extending over the definition of `x`
9393

9494
longer explanation available when compiling with `-explain`
95+
scala> def unsafeCast[S](a: Any) = a match { case s: S => s; case _ => ??? }
96+
-- Warning: <console> ----------------------------------------------------------
97+
4 |def unsafeCast[S](a: Any) = a match { case s: S => s; case _ => ??? }
98+
| ^
99+
| abstract type pattern is unchecked since it is eliminated by erasure
100+
def unsafeCast[S](a: Any): [S] => (a: Any)S
101+
scala> unsafeCast[String](1)
102+
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
103+
at .<init>(<console>:6)
104+
at .<clinit>(<console>)
105+
at RequestResult$.<init>(<console>:3)
106+
at RequestResult$.<clinit>(<console>)
107+
at RequestResult$result(<console>)
108+
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
109+
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.jav...
95110
scala> :quit

0 commit comments

Comments
 (0)