Skip to content

Commit ff4ab4b

Browse files
authored
Merge pull request #15418 from dotty-staging/optimize-nn
Speed up `.nn`
2 parents ad1939a + 40600f2 commit ff4ab4b

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

compiler/test/dotty/tools/backend/jvm/InlineBytecodeTests.scala

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,13 +108,13 @@ class InlineBytecodeTests extends DottyBytecodeTest {
108108
}
109109
}
110110
*/
111-
111+
/*
112112
@Test def inlineNn = {
113113
val source =
114114
s"""
115115
|class Foo {
116116
| def meth1(x: Int | Null): Int = x.nn
117-
| def meth2(x: Int | Null): Int = scala.runtime.Scala3RunTime.nn(x)
117+
| def meth2(x: Int | Null): Int = x.getClass; x
118118
|}
119119
""".stripMargin
120120
@@ -132,7 +132,7 @@ class InlineBytecodeTests extends DottyBytecodeTest {
132132
diffInstructions(instructions1, instructions2))
133133
}
134134
}
135-
135+
*/
136136
@Test def i4947 = {
137137
val source = """class Foo {
138138
| transparent inline def track[T](inline f: T): T = {

library/src/scala/runtime/Scala3RunTime.scala

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,16 @@ object Scala3RunTime:
1414
*
1515
* Extracted to minimize the bytecode size at call site.
1616
*/
17+
@deprecated("use Predef.nn instead", "3.2")
1718
def nn[T](x: T | Null): x.type & T =
1819
val isNull = x == null
19-
if (isNull) throw new NullPointerException("tried to cast away nullability, but value is null")
20+
if isNull then nnFail()
2021
else x.asInstanceOf[x.type & T]
2122

23+
/** Called by the inline extension def `nn`.
24+
*
25+
* Extracted to minimize the bytecode size at call site.
26+
*/
27+
def nnFail(): Nothing =
28+
throw new NullPointerException("tried to cast away nullability, but value is null")
2229
end Scala3RunTime

library/src/scala/runtime/stdLibPatches/Predef.scala

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@ object Predef:
4646
* }}}
4747
*/
4848
extension [T](x: T | Null) inline def nn: x.type & T =
49-
scala.runtime.Scala3RunTime.nn(x)
49+
if x.asInstanceOf[Any] == null then scala.runtime.Scala3RunTime.nnFail()
50+
x.asInstanceOf[x.type & T]
5051

5152
extension (inline x: AnyRef | Null)
5253
/** Enables an expression of type `T|Null`, where `T` is a subtype of `AnyRef`, to be checked for `null`

0 commit comments

Comments
 (0)