Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,5 @@ enum class TsRuntimeFeatureLimitationReason {
ARRAY_LENGTH_CAPACITY,
ARRAY_LENGTH_GROWTH,
STRING_ITERATOR_UNSUPPORTED,
STRING_INDEX_PROPERTY_KEY,
}
20 changes: 18 additions & 2 deletions usvm-ts/src/main/kotlin/org/usvm/machine/expr/ReadString.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package org.usvm.machine.expr

import io.ksmt.expr.KBitVec16Value
import io.ksmt.expr.KFpRoundingMode
import io.ksmt.sort.KFp64Sort
import io.ksmt.utils.asExpr
import io.ksmt.utils.cast
import org.usvm.UExpr
import org.usvm.UHeapRef
import org.usvm.isFalse
import org.usvm.machine.TsRuntimeFeatureLimitationReason
import org.usvm.sizeSort
import org.usvm.util.mkStringBackingElementLValue
import org.usvm.util.stringCharacters
Expand All @@ -15,14 +17,13 @@ import org.usvm.util.stringLength

/** String indexing reads one UTF-16 code unit, or undefined for every non-index property number. */
internal fun TsExprResolver.readStringIndex(receiver: UHeapRef, index: UExpr<*>): UExpr<*>? = with(ctx) {
require(index.sort == fp64Sort) { "String indexing needs a numeric property key" }
val number = resolveStringIndexNumber(index) ?: return null

val lengthBound = scope.calcOnState { boundedStringBackingRefs[receiver] }
?: throw UnsupportedOperationException("String indexing needs modeled backing for $receiver")
val length = scope.calcOnState { stringLength(receiver) }
ensureLengthBounds(scope = scope, length = length, maxLength = lengthBound) ?: return null

val number = index.asExpr(fp64Sort)
val integer = mkFpRoundToIntegralExpr(
roundingMode = mkFpRoundingModeExpr(KFpRoundingMode.RoundTowardZero),
value = number,
Expand Down Expand Up @@ -62,3 +63,18 @@ internal fun TsExprResolver.readStringIndex(receiver: UHeapRef, index: UExpr<*>)

mkIte(isIndex, character, mkUndefinedValue())
}

private fun TsExprResolver.resolveStringIndexNumber(index: UExpr<*>): UExpr<KFp64Sort>? = with(ctx) {
if (index.sort == fp64Sort) return index.asExpr(fp64Sort)

val key = extractNumericArrayIndex(scope, index)
val reason = TsRuntimeFeatureLimitationReason.STRING_INDEX_PROPERTY_KEY
val detail = "String indexing requires a numeric runtime property key"
if (scope.checkSat(mkNot(key.isNumeric)) != null) {
reportRuntimeFeatureLimitation(reason, detail)
}
scope.fork(key.isNumeric, blockOnFalseState = {
terminateAsUnsupported(reason = "$reason: $detail")
}) ?: return null
key.value
}
60 changes: 53 additions & 7 deletions usvm-ts/src/test/kotlin/org/usvm/machine/TsStringIndexingTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import org.usvm.util.jsString
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

Expand All @@ -31,13 +32,7 @@ class TsStringIndexingTest : TsMethodTestRunner() {
override val tsOptions = TsOptions(maxArraySize = 4)

override val runner: (EtsMethod, UMachineOptions) -> List<TsTest> = { method, machineOptions ->
TsMachine(scene = scene, options = machineOptions, tsOptions = tsOptions).use { machine ->
val analysis = machine.analyzeWithOutcome(listOf(method))

assertEquals(TsAnalysisStopReason.EXHAUSTED, analysis.stopReason)
assertTrue(analysis.unsupportedPaths.isEmpty(), "${method.name}: ${analysis.unsupportedPaths}")
analysis.states.map { state -> TsTestResolver().resolve(method, state) }
}
runIndexingTests(method, machineOptions, tsOptions)
}

init {
Expand Down Expand Up @@ -115,6 +110,45 @@ class TsStringIndexingTest : TsMethodTestRunner() {
)
}

@Test
fun `boxed numeric array element indexes a string`() {
val runtime = tsOptions.copy(eraseTypeAssertions = true)
val cases = runIndexingTests(method("boxedNumericIndex"), options, runtime)
val expectedReturns = cases.map { assertIs<TsTestValue.TsNumber>(it.returnValue).number }.toSet()
assertTrue(expectedReturns.containsAll(setOf(1.0, 2.0)))

val script = buildString {
appendLine(source.readText())
for (test in cases) {
val expected = assertIs<TsTestValue.TsNumber>(test.returnValue).number
if (expected == 0.0) continue
val positions = assertIs<TsTestValue.TsArray<*>>(test.before.parameters.single())
val elements = positions.values.joinToString { value -> jsValue(value) }
val call = "new StringIndexing().boxedNumericIndex([$elements])"
appendLine("if ($call !== $expected) throw Error('boxedNumericIndex');")
}
}
assertNodeReplay(
source = script,
directory = directory,
name = "boxed-string-index",
timeoutMessage = "Boxed string index replay timed out",
)
}

@Test
fun `boxed nonnumeric string keys are reported as unsupported`() {
val runtime = tsOptions.copy(eraseTypeAssertions = true)
val analysis = TsMachine(scene = scene, options = options, tsOptions = runtime).use { machine ->
machine.analyzeWithMetadata(methods = listOf(method("boxedPossiblyUndefinedIndex")))
}

assertFalse(analysis.engineFailed)
assertTrue(analysis.states.isNotEmpty())
val limitationReported = analysis.unsupportedPaths.any { "STRING_INDEX_PROPERTY_KEY" in it }
assertTrue(limitationReported, analysis.unsupportedPaths.toString())
}

@Test
fun `symbolic string indexing preserves empty match and nonmatch branches`() {
discoverProperties<TsTestValue.TsString, TsTestValue.TsNumber>(
Expand Down Expand Up @@ -246,6 +280,18 @@ class TsStringIndexingTest : TsMethodTestRunner() {
)
}

private fun runIndexingTests(
method: EtsMethod,
machineOptions: UMachineOptions,
runtime: TsOptions,
): List<TsTest> = TsMachine(scene = scene, options = machineOptions, tsOptions = runtime).use { machine ->
val analysis = machine.analyzeWithOutcome(listOf(method))

assertEquals(TsAnalysisStopReason.EXHAUSTED, analysis.stopReason)
assertTrue(analysis.unsupportedPaths.isEmpty(), "${method.name}: ${analysis.unsupportedPaths}")
analysis.states.map { state -> TsTestResolver().resolve(method, state) }
}

private fun method(name: String): EtsMethod = getMethod(methodName = name, className = "StringIndexing")

private fun jsValue(value: TsTestValue): String = when (value) {
Expand Down
14 changes: 14 additions & 0 deletions usvm-ts/src/test/resources/models/StringIndexing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,20 @@ export class StringIndexing {
return 3;
}

boxedNumericIndex(positions: number[]): number {
if (positions === null || positions === undefined || positions.length === 0) return 0;
const index: number = positions[0];
const receiver: string[] = "ab" as unknown as string[];
return receiver[index] === "b" ? 1 : 2;
}

boxedPossiblyUndefinedIndex(positions: number[]): number {
if (positions === null || positions === undefined) return 0;
const index: number = positions[0];
const receiver: string[] = "ab" as unknown as string[];
return receiver[index] === "b" ? 1 : 2;
}

symbolicString(value: string): number {
if (value.length === 0) {
return value[0] === undefined ? 0 : -1;
Expand Down
Loading