Implement new assert semantics in back-end

Previously, assert was just a regular function and its argument used to
be computed on each call (even if assertions are disabled on JVM).
This change adds support for 3 new behaviours of assert:
* always-enable (independently from -ea on JVM)
* always-disable (independently from -ea JVM)
* runtime/jvm (compile the calls like javac generates assert-operator)
* legacy (leave current eager semantics) - this already existed

Default behaviour is legacy for now.

The behavior is changed based on -Xassertions flag.
 #KT-7540: Fixed
This commit is contained in:
Ilmir Usmanov
2018-04-28 22:15:29 +03:00
parent 3f5a2c6427
commit f568149863
44 changed files with 2685 additions and 33 deletions
+76
View File
@@ -0,0 +1,76 @@
// IGNORE_BACKEND: JS
// KOTLIN_CONFIGURATION_FLAGS: ASSERTIONS_MODE=legacy
// WITH_RUNTIME
// FULL_JDK
import java.lang.reflect.Field
import java.lang.reflect.Modifier
fun setDesiredAssertionStatus(v: Boolean) {
@Suppress("INVISIBLE_REFERENCE")
val field = kotlin._Assertions.javaClass.getField("ENABLED")
val modifiers = Field::class.java.getDeclaredField("modifiers");
modifiers.isAccessible = true
modifiers.setInt(field, field.modifiers and Modifier.FINAL.inv())
field.set(null, v)
}
fun checkTrue(): Boolean {
var hit = false
val l = { hit = true; true }
assert(l())
return hit
}
fun checkTrueWithMessage(): Boolean {
var hit = false
val l = { hit = true; true }
assert(l()) { "BOOYA!" }
return hit
}
fun checkFalse(): Boolean {
var hit = false
val l = { hit = true; false }
assert(l())
return hit
}
fun checkFalseWithMessage(): Boolean {
var hit = false
val l = { hit = true; false }
assert(l()) { "BOOYA!" }
return hit
}
fun box(): String {
setDesiredAssertionStatus(false)
if (!checkTrue()) return "FAIL 0"
setDesiredAssertionStatus(true)
if (!checkTrue()) return "FAIL 1"
setDesiredAssertionStatus(false)
if (!checkTrueWithMessage()) return "FAIL 2"
setDesiredAssertionStatus(true)
if (!checkTrueWithMessage()) return "FAIL 3"
setDesiredAssertionStatus(false)
if (!checkFalse()) return "FAIL 4"
setDesiredAssertionStatus(true)
try {
checkFalse()
return "FAIL 5"
} catch (ignore: AssertionError) {
}
setDesiredAssertionStatus(false)
if (!checkFalseWithMessage()) return "FAIL 6"
setDesiredAssertionStatus(true)
try {
checkFalseWithMessage()
return "FAIL 7"
} catch (ignore: AssertionError) {
}
return "OK"
}