Add contract for 'use'

#KT-35216 Fixed
This commit is contained in:
Toshiaki Kameyama
2019-12-20 09:52:00 +09:00
committed by Ilya Gorbunov
parent 043eddb432
commit 941de655c4
5 changed files with 56 additions and 1 deletions
+2 -1
View File
@@ -82,7 +82,8 @@ compileKotlin {
"-Xallow-kotlin-package",
"-Xmultifile-parts-inherit",
"-Xnormalize-constructor-calls=enable",
"-module-name", project.name
"-module-name", project.name,
"-Xuse-experimental=kotlin.contracts.ExperimentalContracts",
]
}
@@ -19,6 +19,8 @@
@file:kotlin.jvm.JvmPackageName("kotlin.jdk7")
package kotlin
import kotlin.contracts.*
/**
* Executes the given [block] function on this resource and then closes it down correctly whether an exception
* is thrown or not.
@@ -32,6 +34,9 @@ package kotlin
@SinceKotlin("1.2")
@kotlin.internal.InlineOnly
public inline fun <T : AutoCloseable?, R> T.use(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
var exception: Throwable? = null
try {
return block(this)
@@ -0,0 +1,25 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin.jdk7.test
import org.junit.Test
import kotlin.test.assertEquals
class AutoCloseableContractsTest {
@Test
fun shouldHaveBlockExactlyOnceContract() {
class TestAutoCloseable : AutoCloseable {
override fun close() {
}
}
val i: Int
TestAutoCloseable().use {
i = 1
}
assertEquals(1, i)
}
}
@@ -7,6 +7,7 @@
package kotlin.io
import java.io.Closeable
import kotlin.contracts.*
import kotlin.internal.*
/**
@@ -19,6 +20,9 @@ import kotlin.internal.*
@InlineOnly
@RequireKotlin("1.2", versionKind = RequireKotlinVersionKind.COMPILER_VERSION, message = "Requires newer compiler version to be inlined correctly.")
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
var exception: Throwable? = null
try {
return block(this)
+20
View File
@@ -0,0 +1,20 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package test.io
import org.junit.Test
import kotlin.test.assertEquals
class CloseableTest {
@Test
fun shouldHaveBlockExactlyOnceContract() {
val i: Int
"".byteInputStream().use {
i = 1
}
assertEquals(1, i)
}
}