Skip to content

Make the extension method nn inline. #10396

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions compiler/test/dotty/tools/backend/jvm/InlineBytecodeTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,30 @@ class InlineBytecodeTests extends DottyBytecodeTest {
}
}

@Test def inlineNn = {
val source =
s"""
|class Foo {
| def meth1(x: Int | Null): Int = x.nn
| def meth2(x: Int | Null): Int = scala.runtime.Scala3RunTime.nn(x)
|}
""".stripMargin

checkBCode(source) { dir =>
val clsIn = dir.lookupName("Foo.class", directory = false).input
val clsNode = loadClassNode(clsIn)
val meth1 = getMethod(clsNode, "meth1")
val meth2 = getMethod(clsNode, "meth2")

val instructions1 = instructionsFromMethod(meth1)
val instructions2 = instructionsFromMethod(meth2)

assert(instructions1 == instructions2,
"`nn` was not properly inlined in `meth1`\n" +
diffInstructions(instructions1, instructions2))
}
}

@Test def i4947 = {
val source = """class Foo {
| transparent inline def track[T](inline f: T): T = {
Expand Down
5 changes: 2 additions & 3 deletions library/src/dotty/DottyPredef.scala
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ object DottyPredef {
*
* Note that `.nn` performs a checked cast, so if invoked on a null value it'll throw an NPE.
*/
extension [T](x: T | Null) def nn: x.type & T =
if (x == null) throw new NullPointerException("tried to cast away nullability, but value is null")
else x.asInstanceOf[x.type & T]
extension [T](x: T | Null) inline def nn: x.type & T =
scala.runtime.Scala3RunTime.nn(x)
}
8 changes: 8 additions & 0 deletions library/src/scala/runtime/Scala3RunTime.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,12 @@ object Scala3RunTime:
def assertFailed(): Nothing =
throw new java.lang.AssertionError("assertion failed")

/** Called by the inline extension def `nn`.
*
* Extracted to minimize the bytecode size at call site.
*/
def nn[T](x: T | Null): x.type & T =
if (x == null) throw new NullPointerException("tried to cast away nullability, but value is null")
else x.asInstanceOf[x.type & T]

end Scala3RunTime