Skip to content

Commit fabe7bb

Browse files
Merge pull request #9419 from sjrd/scalajs-cast-null-nothing
Scala.js: Handle casts to `Null` and `Nothing`.
2 parents 192d387 + 4bcd059 commit fabe7bb

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2532,11 +2532,24 @@ class JSCodeGen()(using genCtx: Context) {
25322532
* asInstanceOf to a raw JS type is completely erased.
25332533
*/
25342534
value
2535+
} else if (sym == defn.NullClass) {
2536+
js.If(
2537+
js.BinaryOp(js.BinaryOp.===, value, js.Null()),
2538+
js.Null(),
2539+
genThrowClassCastException())(
2540+
jstpe.NullType)
2541+
} else if (sym == defn.NothingClass) {
2542+
js.Block(value, genThrowClassCastException())
25352543
} else {
25362544
js.AsInstanceOf(value, toIRType(to))
25372545
}
25382546
}
25392547

2548+
private def genThrowClassCastException()(implicit pos: Position): js.Tree = {
2549+
js.Throw(js.New(jsNames.ClassCastExceptionClass,
2550+
js.MethodIdent(jsNames.NoArgConstructorName), Nil))
2551+
}
2552+
25402553
/** Gen JS code for an isInstanceOf test (for reference types only) */
25412554
private def genIsInstanceOf(value: js.Tree, to: Type)(
25422555
implicit pos: SourcePosition): js.Tree = {
@@ -2556,6 +2569,9 @@ class JSCodeGen()(using genCtx: Context) {
25562569
jstpe.BooleanType)
25572570
}
25582571
} else {
2572+
// The Scala type system prevents x.isInstanceOf[Null] and ...[Nothing]
2573+
assert(sym != defn.NullClass && sym != defn.NothingClass,
2574+
s"Found a .isInstanceOf[$sym] at $pos")
25592575
js.IsInstanceOf(value, toIRType(to))
25602576
}
25612577
}

project/Build.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1064,7 +1064,7 @@ object Build {
10641064
++ (dir / "shared/src/test/require-jdk8/org/scalajs/testsuite/javalib/util" ** (("*.scala": FileFilter) -- "CollectionsOnCopyOnWriteArrayListTestOnJDK8.scala")).get
10651065
++ (dir / "shared/src/test/require-jdk7/org/scalajs/testsuite/javalib/io" ** "*.scala").get
10661066
++ (dir / "shared/src/test/require-jdk7/org/scalajs/testsuite/javalib/lang" ** "*.scala").get
1067-
++ (dir / "shared/src/test/require-jdk7/org/scalajs/testsuite/javalib/util" ** (("*.scala": FileFilter) -- "ObjectsTestOnJDK7.scala")).get
1067+
++ (dir / "shared/src/test/require-jdk7/org/scalajs/testsuite/javalib/util" ** "*.scala").get
10681068
)
10691069
}
10701070
)

0 commit comments

Comments
 (0)