Skip to content
Draft
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
2 changes: 1 addition & 1 deletion buildSrc/src/main/kotlin/Dependencies.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ object Versions {
const val clikt = "5.0.0"
const val detekt = "1.23.7"
const val ini4j = "0.5.4"
const val jacodb = "4251d2023d"
const val jacodb = "a797c890"
const val juliet = "1.3.2"
const val junit = "5.9.3"
const val kotlin = "2.1.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,5 @@ enum class TsRuntimeFeatureLimitationReason {
ARRAY_LENGTH_CAPACITY,
ARRAY_LENGTH_GROWTH,
STRING_ITERATOR_UNSUPPORTED,
OBJECT_METHOD_RECEIVER,
}
19 changes: 16 additions & 3 deletions usvm-ts/src/main/kotlin/org/usvm/machine/expr/TsExprResolver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1302,6 +1302,11 @@ class TsExprResolver(
ref: UConcreteHeapRef,
operation: RuntimeConstructorOperation,
): Nothing? = with(ctx) {
val function = scope.calcOnState { associatedFunction[ref] }
val attemptsToConstructMethod = operation == RuntimeConstructorOperation.NEW &&
function?.method?.isObjectLiteralMethod == true
if (attemptsToConstructMethod) return throwTypeError()

val objectType = if (isAllocatedConcreteHeapRef(ref)) {
scope.calcOnState { memory.typeStreamOf(ref).singleOrNull() }
} else {
Expand All @@ -1320,10 +1325,8 @@ class TsExprResolver(
ancestor.methods.any { it.name == "%computed" || it.name == "Symbol.hasInstance" } ||
ancestor.fields.any { it.name == "%computed" || it.name == "Symbol.hasInstance" }
}
val isFunction = scope.calcOnState { associatedFunction[ref] != null }

val mayHandleInstanceof = operation == RuntimeConstructorOperation.INSTANCEOF && hasComputedMember
val isKnownNonConstructor = ordinaryObject && !mayHandleInstanceof && !isFunction
val isKnownNonConstructor = ordinaryObject && !mayHandleInstanceof && function == null
if (isKnownNonConstructor) return throwTypeError()
}

Expand Down Expand Up @@ -1409,6 +1412,16 @@ class TsExprResolver(

val explicitReceiver = expr.receiver
val boundInstance = callee.thisInstance
val needsSloppyGlobalReceiver = callee.method.isObjectLiteralMethod &&
callee.method.isStrictMode != true && explicitReceiver == null && boundInstance == null
if (needsSloppyGlobalReceiver) {
stopRuntimeFeatureLimitation(
reason = TsRuntimeFeatureLimitationReason.OBJECT_METHOD_RECEIVER,
detail = "A detached sloppy object method requires the JavaScript global receiver",
)
return null
}

val instance = if (boundInstance != null) {
boundInstance
} else if (explicitReceiver != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package org.usvm.samples.lang

import org.jacodb.ets.model.EtsScene
import org.jacodb.ets.utils.DEFAULT_ARK_CLASS_NAME
import org.junit.jupiter.api.Test
import org.usvm.api.TsTestValue
import org.usvm.machine.TsMachine
import org.usvm.machine.TsOptions
import org.usvm.machine.TsRuntimeFeatureLimitationReason
import org.usvm.machine.call.TsResidualCallPolicy
import org.usvm.util.TsMethodTestRunner
import org.usvm.util.eq
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class ObjectLiteralMethodBoundariesTest : TsMethodTestRunner() {
override val scene: EtsScene = loadScene("/samples/lang/ObjectLiteralMethodBoundaries.ts")

@Test
fun `a sloppy method uses its actual object receiver and reports missing global receiver on extraction`() {
val memberCall = getMethod(methodName = "callSloppyMember", className = DEFAULT_ARK_CLASS_NAME)

discoverProperties<TsTestValue.TsNumber>(
method = memberCall,
{ result -> result eq 3 },
invariants = arrayOf({ result -> result eq 3 }),
)
assertUnsupported(
methodName = "callSloppyDetached",
reason = TsRuntimeFeatureLimitationReason.OBJECT_METHOD_RECEIVER.name,
)
}

@Test
fun `a method with super is created and stops only if invoked`() {
val create = getMethod(methodName = "createMethodWithSuper", className = DEFAULT_ARK_CLASS_NAME)

discoverProperties<TsTestValue.TsBoolean>(
method = create,
{ result -> result.value },
invariants = arrayOf({ result -> result.value }),
)
assertUnsupported(methodName = "callMethodWithSuper", reason = "super.toString")
}

private fun assertUnsupported(methodName: String, reason: String) {
val entry = getMethod(methodName = methodName, className = DEFAULT_ARK_CLASS_NAME)
val options = options.copy(throwExceptionOnStepFailure = false)
val tsOptions = TsOptions(unknownCallFallback = TsResidualCallPolicy.FRESH_SYMBOLIC_RETURN)

val result = TsMachine(scene = scene, options = options, tsOptions = tsOptions).use { machine ->
machine.analyzeWithMetadata(methods = listOf(entry))
}

assertFalse(result.engineFailed)
assertTrue(result.states.isEmpty(), result.toString())
assertTrue(result.unsupportedPaths.any { reason in it }, result.unsupportedPaths.toString())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
package org.usvm.samples.lang

import org.jacodb.ets.model.EtsMethod
import org.jacodb.ets.model.EtsScene
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import org.usvm.StateCollectionStrategy
import org.usvm.UMachineOptions
import org.usvm.api.TsTest
import org.usvm.api.TsTestValue
import org.usvm.machine.TS_TYPE_ERROR_TYPE
import org.usvm.machine.TsAnalysisStopReason
import org.usvm.machine.TsMachine
import org.usvm.machine.call.TsCompatibilityUnknownCallDispatcher
import org.usvm.machine.state.TsMethodResult
import org.usvm.util.TsMethodTestRunner
import org.usvm.util.TsTestResolver
import org.usvm.util.assertNodeReplay
import org.usvm.util.eq
import org.usvm.util.getResourcePath
import java.nio.file.Path
import kotlin.io.path.readText
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.seconds

class ObjectLiteralMethodsTest : TsMethodTestRunner() {
@TempDir
lateinit var directory: Path

override val scene: EtsScene = loadScene(sourcePath)

init {
options = options.copy(
timeout = 33.seconds,
stateCollectionStrategy = StateCollectionStrategy.ALL,
stopOnCoverage = 0,
)
}

override val runner: (EtsMethod, UMachineOptions) -> List<TsTest> = { method, machineOptions ->
TsMachine(scene, machineOptions, tsOptions, unknownCallDispatcher = TsCompatibilityUnknownCallDispatcher)
.use { machine ->
val analysis = machine.analyzeWithMetadata(methods = listOf(method))
assertEquals(TsAnalysisStopReason.EXHAUSTED, analysis.stopReason, method.name)
assertFalse(analysis.engineFailed, method.name)
assertFalse(analysis.unsupportedCall, method.name)
assertTrue(analysis.unsupportedPaths.isEmpty(), analysis.unsupportedPaths.toString())

analysis.states.map { TsTestResolver().resolve(method, it) }
}
}

@Test
fun `stored methods are stable on one object and fresh on each evaluation`() {
assertTrueResult("identity")
}

@Test
fun `member calls use the current receiver and extracted calls get undefined this`() {
assertNumberResult("receiver", expected = 389)
assertNumberResult("replacingAnOwnMethod", expected = 58)
}

@Test
fun `method and arrow bodies share the enclosing mutable binding`() {
assertNumberResult("sharedCapture", expected = 777)
}

@Test
fun `method allocation preserves neighboring property evaluation order`() {
assertNumberResult("propertyOrder", expected = 12345)
}

@Test
fun `async bodies run only on invocation`() {
assertTrueResult("asyncDeclaration")
assertNumberResult("asyncInvocation", expected = 1)
}

@Test
fun `object methods throw TypeError when used as constructors`() {
val method = getMethod("notConstructable", className = "ObjectLiteralMethods")

val analysis = TsMachine(scene, options, tsOptions).use { machine ->
machine.analyzeWithMetadata(methods = listOf(method))
}

assertEquals(TsAnalysisStopReason.EXHAUSTED, analysis.stopReason)
assertFalse(analysis.engineFailed)
assertFalse(analysis.unsupportedCall)
assertTrue(analysis.unsupportedPaths.isEmpty(), analysis.unsupportedPaths.toString())
val result = assertIs<TsMethodResult.TsException>(analysis.states.single().methodResult)
assertEquals(TS_TYPE_ERROR_TYPE, result.type)
}

@Test
fun `computed keys spread and accessor keep explicit unsupported outcomes`() {
val expectedDiagnostics = mapOf(
"computedKeyOrder" to "Data property requires a constant string key",
"spreadOrder" to "copyDataProperties",
"accessor" to "defineAccessor",
)

for ((name, expected) in expectedDiagnostics) {
val method = getMethod(name, className = "ObjectLiteralMethods")
val analysis = TsMachine(scene, options, tsOptions).use { machine ->
machine.analyzeWithMetadata(methods = listOf(method))
}

assertEquals(TsAnalysisStopReason.EXHAUSTED, analysis.stopReason, name)
assertFalse(analysis.engineFailed, name)
assertTrue(analysis.states.isEmpty(), name)
val hasUnsupportedStatement = analysis.unsupportedPaths.any { expected in it }
assertTrue(hasUnsupportedStatement, "$name: ${analysis.unsupportedPaths}")
}
}

@Test
fun `native Node confirms method results and object evaluation order`() {
val assertions = """
const fixture = new ObjectLiteralMethods();
const expected = {
identity: true,
receiver: 389,
replacingAnOwnMethod: 58,
sharedCapture: 777,
propertyOrder: 12345,
computedKeyOrder: 123456,
spreadOrder: 1237,
accessor: 4,
asyncDeclaration: true,
asyncInvocation: 1,
};
for (const [name, result] of Object.entries(expected)) {
if (fixture[name]() !== result) throw Error(name);
}

let constructionError;
try {
fixture.notConstructable();
} catch (error) {
constructionError = error;
}
if (!(constructionError instanceof TypeError)) throw Error("notConstructable");
""".trimIndent()

assertNodeReplay(
source = getResourcePath(sourcePath).readText() + "\n" + assertions,
directory = directory,
name = "object-literal-methods",
timeoutMessage = "Native object literal method checks timed out",
)
}

private fun assertTrueResult(name: String) {
val method = getMethod(name, className = "ObjectLiteralMethods")
discoverProperties<TsTestValue.TsBoolean>(
method = method,
{ result -> result.value },
invariants = arrayOf({ result -> result.value }),
)
}

private fun assertNumberResult(name: String, expected: Int) {
val method = getMethod(name, className = "ObjectLiteralMethods")
discoverProperties<TsTestValue.TsNumber>(
method = method,
{ result -> result eq expected },
invariants = arrayOf({ result -> result eq expected }),
)
}

private companion object {
const val sourcePath = "/samples/lang/ObjectLiteralMethods.ts"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package org.usvm.samples.lang

import org.jacodb.ets.model.EtsScene
import org.jacodb.ets.utils.EtsIrProvider
import org.jacodb.ets.utils.loadEtsFileAutoConvert
import org.junit.jupiter.api.Test
import org.usvm.api.TsTestValue
import org.usvm.machine.TsMachine
import org.usvm.util.TsMethodTestRunner
import org.usvm.util.eq
import org.usvm.util.getResourcePath
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class SharedCaptureBindingsTest : TsMethodTestRunner() {
override val scene = EtsScene(
listOf(
loadEtsFileAutoConvert(
path = getResourcePath(res = "/samples/lang/SharedCaptureBindings.ts"),
provider = EtsIrProvider.TS_FRONTEND,
),
),
)

@Test
fun `parameters uninitialized lets and deferred self captures share cells across calls`() {
for (name in listOf("parameterCell", "uninitializedCell", "deferredSelfCapture")) {
val method = getMethod(methodName = name, className = "SharedCaptureBindings")

discoverProperties<TsTestValue.TsNumber>(
method = method,
{ result -> result.number == 2.0 },
invariants = arrayOf({ result -> result.number == 2.0 }),
)
}
}

@Test
fun `potential eager self-reference during lexical initialization stays unsupported`() {
val method = getMethod(methodName = "eagerSelfCapture", className = "SharedCaptureBindings")

val outcome = TsMachine(scene = scene, options = options, tsOptions = tsOptions).use { machine ->
machine.analyzeWithMetadata(methods = listOf(method))
}

assertFalse(outcome.engineFailed)
assertTrue(outcome.states.isEmpty())
assertTrue(outcome.unsupportedPaths.isNotEmpty())
}

@Test
fun `writes in the declaring method and in nested closures reach sibling closures`() {
val method = getMethod(methodName = "siblingsAndEnclosing", className = "SharedCaptureBindings")

discoverProperties<TsTestValue.TsNumber>(
method = method,
{ value -> value eq 466 },
invariants = arrayOf({ value -> value eq 466 }),
)
}

@Test
fun `separate invocations initialize independent bindings`() {
val method = getMethod(methodName = "separateInvocations", className = "SharedCaptureBindings")

discoverProperties<TsTestValue.TsNumber>(
method = method,
{ value -> value eq 313 },
invariants = arrayOf({ value -> value eq 313 }),
)
}

@Test
fun `each execution of a block creates a fresh binding for escaping closures`() {
val method = getMethod(methodName = "reenterBlock", className = "SharedCaptureBindings")

discoverProperties<TsTestValue.TsNumber>(
method = method,
{ value -> value eq 1011 },
invariants = arrayOf({ value -> value eq 1011 }),
)
}
}
Loading
Loading