From 43f37a58564971f70c034e63cecf88add94fe50a Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Wed, 2 Dec 2026 20:29:21 +0100 Subject: [PATCH 1/2] Construct typed inputs for bounded lifecycle entries --- .../org/usvm/machine/TsLifecycleScenarios.kt | 127 +++++++-- .../lifecycle/TsLifecycleInputMaterializer.kt | 49 ++++ .../lifecycle/TsLifecycleInputPlanner.kt | 248 ++++++++++++++++++ .../lifecycle/TsLifecycleMethodBuilder.kt | 13 +- .../lifecycle/TsLifecycleStringSeed.kt | 80 ++++++ .../lifecycle/AutomaticLifecycleTest.kt | 35 +++ .../TsLifecycleCapturedInputFactoryTest.kt | 76 ++++++ .../lifecycle/TsLifecycleInputPlannerTest.kt | 111 ++++++++ .../TsLifecycleNullableCallbackTest.kt | 40 +++ .../samples/lang/AutomaticLifecycle.ts | 30 +++ .../samples/lang/CapturedInputFactory.ts | 34 +++ .../samples/types/LifecycleInputPlanning.ts | 87 ++++++ 12 files changed, 901 insertions(+), 29 deletions(-) create mode 100644 usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputMaterializer.kt create mode 100644 usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlanner.kt create mode 100644 usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleStringSeed.kt create mode 100644 usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleCapturedInputFactoryTest.kt create mode 100644 usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlannerTest.kt create mode 100644 usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleNullableCallbackTest.kt create mode 100644 usvm-ts/src/test/resources/samples/lang/CapturedInputFactory.ts create mode 100644 usvm-ts/src/test/resources/samples/types/LifecycleInputPlanning.ts diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/TsLifecycleScenarios.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/TsLifecycleScenarios.kt index a1e506e02a..bc97aec443 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/TsLifecycleScenarios.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/TsLifecycleScenarios.kt @@ -5,6 +5,7 @@ import org.jacodb.ets.model.EtsClass import org.jacodb.ets.model.EtsClassCategory import org.jacodb.ets.model.EtsClassImpl import org.jacodb.ets.model.EtsClassSignature +import org.jacodb.ets.model.EtsClassValueRef import org.jacodb.ets.model.EtsField import org.jacodb.ets.model.EtsFieldSignature import org.jacodb.ets.model.EtsFile @@ -25,7 +26,10 @@ import org.jacodb.ets.model.EtsUnknownType import org.jacodb.ets.model.EtsVoidType import org.jacodb.ets.utils.CONSTRUCTOR_NAME import org.jacodb.ets.utils.callExpr +import org.usvm.machine.lifecycle.TsLifecycleInput +import org.usvm.machine.lifecycle.TsLifecycleInputPlanner import org.usvm.machine.lifecycle.TsLifecycleMethodBuilder +import org.usvm.machine.lifecycle.materialize import org.usvm.machine.types.initialInputType import org.usvm.util.canonicalizeExecutableOverloads @@ -79,13 +83,13 @@ fun buildTsLifecycleScenarios( val receiver = if (method.isStatic) { null } else { - construct(requireNotNull(constructor), args.take(receiverInputs.size)) + construct(requireNotNull(constructor), args.slice(to = receiverInputs.size)) } val pointer = callMethod(method, receiver, resultType = EtsUnknownType) { - args.subList(receiverInputs.size, factoryEnd) + args.slice(from = receiverInputs.size, to = factoryEnd) } ensureKnownCallable(pointer) - callPointer(pointer, type, args.drop(factoryEnd)) + callPointer(pointer, type, args.slice(from = factoryEnd)) } } plans += factories.take(MAX_RETURNED_FUNCTIONS) @@ -94,22 +98,17 @@ fun buildTsLifecycleScenarios( val fields = target.fields.mapNotNull { field -> field.callableFieldType()?.let { field to it } } for ((field, type) in fields.take(MAX_CALLABLE_FIELDS)) { plans += LifecyclePlan(name = "field.${field.name}", types = constructorTypes + type.inputTypes()) { args -> - val receiver = construct(constructor, args.take(constructorTypes.size)) + val receiver = construct(constructor, args.slice(to = constructorTypes.size)) val pointer = newLocal(field.type) assign(target = pointer, value = EtsInstanceFieldRef(receiver, field.signature, field.type)) ensureKnownCallable(pointer) - callPointer(pointer, type, args.drop(constructorTypes.size), receiver, field) + callPointer(pointer, type, args.slice(from = constructorTypes.size), receiver, field) } } val initializedMethods = methods.filter { !it.isStatic && it.returnedFunctionType() == null } for (method in initializedMethods.take(MAX_INITIALIZED_METHODS)) { - plans += directMethodPlan( - name = "instance.${method.name}", - method = method, - constructor = constructor, - constructorTypes = constructorTypes, - ) + plans += directMethodPlan(name = "instance.${method.name}", method, constructor, constructorTypes) } val first = initializedMethods.firstOrNull { it.returnType == EtsVoidType } @@ -119,25 +118,47 @@ fun buildTsLifecycleScenarios( } } + val planner = TsLifecycleInputPlanner(scene) + val calledMethods = methods.filter { it.returnedFunctionType() == null }.mapNotNull { method -> + if (!method.isStatic && constructor == null) return@mapNotNull null + directMethodPlan(name = method.name, method, constructor, constructorTypes) + } + val witnessCandidates = plans.filter { it.name.startsWith("return.") || it.name.startsWith("field.") } + calledMethods + val witnessPlans = witnessCandidates.filter { it.types.size <= MAX_ARGUMENTS }.mapNotNull { plan -> + val witness = preferredWitness(plan.types, planner) ?: return@mapNotNull null + plan.copy(name = "witness.${plan.name}", witness = witness) + }.sortedByDescending { it.witness?.second is TsLifecycleInput.Callback } + val selectedWitnesses = witnessPlans.take(MAX_WITNESS_METHODS) + plans += selectedWitnesses + val comparisonWitness = selectedWitnesses.firstNotNullOfOrNull { it.comparisonAlternative(planner) } + if (comparisonWitness != null) plans += comparisonWitness + val predicateWitness = selectedWitnesses.firstNotNullOfOrNull { it.booleanAlternative(planner) } + if (predicateWitness != null) plans += predicateWitness + val returnedCallableScenarios = linkedMapOf() val entries = plans.filter { it.types.size <= MAX_ARGUMENTS }.map { plan -> val builder = TsLifecycleMethodBuilder(owner, plan.name) - val arguments = plan.types.map(builder::argument) - val result = plan.execute(builder, arguments) - val entry = builder.finish(result) - plan.returnedFactoryCall?.let { returnedCallableScenarios[entry] = it.describe(entry) } - entry + val witnesses = listOfNotNull(plan.witness).toMap() + val args = LifecycleArguments(builder, plan.types, witnesses) + val result = plan.execute(builder, args) + val generated = builder.finish(result) + val factoryCall = plan.returnedFactoryCall + if (factoryCall != null && plan.witness == null) { + val entry = generated.first() + returnedCallableScenarios[entry] = factoryCall.describe(entry) + } + generated } if (entries.isEmpty()) return TsLifecycleScenarios(scene = scene, methods = emptyList()) val driverExists = scene.projectFiles.any { it.signature == driverFile } check(!driverExists) { "Lifecycle driver file already exists: $driverFile" } - val driver = EtsClassImpl(signature = owner, fields = emptyList(), methods = entries) + val driver = EtsClassImpl(signature = owner, fields = emptyList(), methods = entries.flatten()) val generated = EtsFile(signature = driverFile, classes = listOf(driver), namespaces = emptyList()) val extended = EtsScene(scene.projectFiles + generated, scene.sdkFiles, scene.projectName) return TsLifecycleScenarios( scene = extended, - methods = entries, + methods = entries.map { it.first() }, returnedCallableScenarios = returnedCallableScenarios, ) } @@ -145,9 +166,30 @@ fun buildTsLifecycleScenarios( private data class LifecyclePlan( val name: String, val types: List, + val witness: Pair? = null, + val directMethod: EtsMethod? = null, val returnedFactoryCall: ReturnedFactoryCall? = null, - val execute: TsLifecycleMethodBuilder.(List) -> EtsLocal, -) + val execute: TsLifecycleMethodBuilder.(LifecycleArguments) -> EtsLocal, +) { + fun booleanAlternative(planner: TsLifecycleInputPlanner): LifecyclePlan? { + val (argumentIndex, input) = witness ?: return null + val callback = input as? TsLifecycleInput.Callback ?: return null + val alternative = planner.booleanAlternative(callback) ?: return null + + return copy(name = "$name.true", witness = argumentIndex to alternative) + } + + fun comparisonAlternative(planner: TsLifecycleInputPlanner): LifecyclePlan? { + val method = directMethod ?: return null + val (argumentIndex, input) = witness ?: return null + val constructed = input as? TsLifecycleInput.Constructed ?: return null + val receiverArgumentCount = types.size - method.inputTypes().size + val parameter = method.parameters.getOrNull(argumentIndex - receiverArgumentCount) ?: return null + + val alternative = planner.comparisonAlternative(constructed, method, parameter.index) ?: return null + return copy(name = "$name.comparison", witness = argumentIndex to alternative) + } +} private data class ReturnedFactoryCall( val factory: EtsMethod, @@ -170,6 +212,26 @@ private data class ReturnedFactoryCall( } } +private class LifecycleArguments( + private val builder: TsLifecycleMethodBuilder, + types: List, + private val witnesses: Map, +) { + private val locals = types.mapIndexed { index, type -> + if (index in witnesses) null else builder.argument(type) + }.toMutableList() + + // Witness constructors can have effects. Emit them at the relevant call site after receiver selection. + fun slice(from: Int = 0, to: Int = locals.size): List = (from until to).map { index -> + val local = locals[index] + if (local != null) { + local + } else { + builder.materialize(witnesses.getValue(index)).also { locals[index] = it } + } + } +} + private fun EtsMethod.isExternalEntry(): Boolean = !isPrivate && !isProtected && !isAbstract && !isAccessor && !isDeclare && !name.startsWith('%') && !name.startsWith('#') && cfg.stmts.isNotEmpty() @@ -205,6 +267,18 @@ private fun inputTypes(parameters: List, typeParameters: Lis return parameters.lifecycleParameters().map { it.type.initialInputType(generics) } } +private fun preferredWitness(types: List, planner: TsLifecycleInputPlanner): Pair? { + val candidates = types.mapIndexedNotNull { index, type -> + when (val input = planner.plan(type)) { + is TsLifecycleInput.Callback, is TsLifecycleInput.Constructed -> index to input + is TsLifecycleInput.Literal -> if (input.value is EtsClassValueRef) index to input else null + null -> null + } + } + return candidates.firstOrNull { it.second is TsLifecycleInput.Callback } + ?: candidates.firstOrNull() +} + private fun directMethodPlan( name: String, method: EtsMethod, @@ -212,13 +286,13 @@ private fun directMethodPlan( constructorTypes: List, ): LifecyclePlan { val receiverTypes = if (method.isStatic) emptyList() else constructorTypes - return LifecyclePlan(name = name, types = receiverTypes + method.inputTypes()) { args -> + return LifecyclePlan(name = name, types = receiverTypes + method.inputTypes(), directMethod = method) { args -> val receiver = if (method.isStatic) { null } else { - construct(requireNotNull(constructor), args.take(receiverTypes.size)) + construct(requireNotNull(constructor), args.slice(to = receiverTypes.size)) } - callMethod(method, receiver) { args.drop(receiverTypes.size) } + callMethod(method, receiver) { args.slice(from = receiverTypes.size) } } } @@ -233,9 +307,9 @@ private fun sequencePlan( val firstEnd = constructorTypes.size + firstTypes.size return LifecyclePlan(name = name, types = constructorTypes + firstTypes + second.inputTypes()) { args -> - val receiver = construct(constructor, args.take(constructorTypes.size)) - callMethod(first, receiver) { args.subList(constructorTypes.size, firstEnd) } - callMethod(second, receiver) { args.drop(firstEnd) } + val receiver = construct(constructor, args.slice(to = constructorTypes.size)) + callMethod(first, receiver) { args.slice(from = constructorTypes.size, to = firstEnd) } + callMethod(second, receiver) { args.slice(from = firstEnd) } } } @@ -292,4 +366,5 @@ private fun TsLifecycleMethodBuilder.callPointer( private const val MAX_RETURNED_FUNCTIONS = 8 private const val MAX_CALLABLE_FIELDS = 8 private const val MAX_INITIALIZED_METHODS = 4 +private const val MAX_WITNESS_METHODS = 4 private const val MAX_ARGUMENTS = 12 diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputMaterializer.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputMaterializer.kt new file mode 100644 index 0000000000..d927085866 --- /dev/null +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputMaterializer.kt @@ -0,0 +1,49 @@ +package org.usvm.machine.lifecycle + +import org.jacodb.ets.model.BasicBlock +import org.jacodb.ets.model.EtsBlockCfg +import org.jacodb.ets.model.EtsLocal +import org.jacodb.ets.model.EtsMethodImpl +import org.jacodb.ets.model.EtsModifier +import org.jacodb.ets.model.EtsModifiers +import org.jacodb.ets.model.EtsReturnStmt +import org.jacodb.ets.model.EtsStmtLocation +import org.jacodb.ets.utils.NAMED_FUNCTION_REFERENCE_PREFIX + +internal fun TsLifecycleMethodBuilder.materialize(input: TsLifecycleInput): EtsLocal = when (input) { + is TsLifecycleInput.Literal -> { + val local = newLocal(input.value.type) + assign(target = local, value = input.value) + local + } + is TsLifecycleInput.Constructed -> { + val arguments = input.arguments.map { materialize(it) } + construct(constructor = input.constructor, arguments = arguments, type = input.type) + } + is TsLifecycleInput.Callback -> materializeCallback(input) +} + +private fun TsLifecycleMethodBuilder.materializeCallback(input: TsLifecycleInput.Callback): EtsLocal { + val signature = input.functionType.signature.copy(enclosingClass = owner, name = callbackName()) + val callback = EtsMethodImpl( + signature = signature, + typeParameters = input.functionType.typeParameters, + modifiers = EtsModifiers.of(EtsModifier.STATIC), + isStrictMode = true, + ) + val returnStatement = EtsReturnStmt( + location = EtsStmtLocation(method = callback, index = 0), + returnValue = input.returnOperand, + ) + callback.body.cfg = EtsBlockCfg( + blocks = listOf(BasicBlock(id = 0, statements = listOf(returnStatement))), + successors = mapOf(0 to emptyList()), + ) + registerCallback(callback) + + val referenceType = input.functionType.copy(signature = signature, isArrow = true) + val reference = EtsLocal(name = "$NAMED_FUNCTION_REFERENCE_PREFIX${signature.name}", type = referenceType) + val local = newLocal(input.functionType) + assign(target = local, value = reference) + return local +} diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlanner.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlanner.kt new file mode 100644 index 0000000000..53917cc289 --- /dev/null +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlanner.kt @@ -0,0 +1,248 @@ +package org.usvm.machine.lifecycle + +import org.jacodb.ets.model.EtsAliasType +import org.jacodb.ets.model.EtsArrayType +import org.jacodb.ets.model.EtsBooleanConstant +import org.jacodb.ets.model.EtsBooleanLiteralType +import org.jacodb.ets.model.EtsBooleanType +import org.jacodb.ets.model.EtsClass +import org.jacodb.ets.model.EtsClassCategory +import org.jacodb.ets.model.EtsClassSignature +import org.jacodb.ets.model.EtsClassType +import org.jacodb.ets.model.EtsClassValueRef +import org.jacodb.ets.model.EtsClassValueType +import org.jacodb.ets.model.EtsConstant +import org.jacodb.ets.model.EtsFunctionType +import org.jacodb.ets.model.EtsImmediate +import org.jacodb.ets.model.EtsMethod +import org.jacodb.ets.model.EtsMethodParameter +import org.jacodb.ets.model.EtsNullConstant +import org.jacodb.ets.model.EtsNullType +import org.jacodb.ets.model.EtsNumberConstant +import org.jacodb.ets.model.EtsNumberLiteralType +import org.jacodb.ets.model.EtsNumberType +import org.jacodb.ets.model.EtsParameterRef +import org.jacodb.ets.model.EtsRawStmt +import org.jacodb.ets.model.EtsScene +import org.jacodb.ets.model.EtsStringConstant +import org.jacodb.ets.model.EtsStringLiteralType +import org.jacodb.ets.model.EtsStringType +import org.jacodb.ets.model.EtsTupleType +import org.jacodb.ets.model.EtsType +import org.jacodb.ets.model.EtsUndefinedConstant +import org.jacodb.ets.model.EtsUndefinedType +import org.jacodb.ets.model.EtsUnionType +import org.jacodb.ets.model.EtsValue +import org.jacodb.ets.model.EtsVoidType +import org.jacodb.ets.utils.CONSTRUCTOR_NAME + +internal sealed interface TsLifecycleInput { + data class Literal(val value: EtsImmediate, val declaredType: EtsType = value.type) : TsLifecycleInput + + data class Constructed( + val type: EtsClassType, + val constructor: EtsMethod, + val arguments: List, + ) : TsLifecycleInput + + data class Callback(val functionType: EtsFunctionType, val returnOperand: EtsValue?) : TsLifecycleInput + +} + +/** Plans one source-level construction candidate. A constructor still runs its own validation at execution time. */ +internal class TsLifecycleInputPlanner(scene: EtsScene) { + private val classes = scene.projectClasses.groupBy { it.signature } + + fun plan(type: EtsType): TsLifecycleInput? = Search().plan(type, depth = 0, constructing = emptySet()) + + fun comparisonAlternative( + input: TsLifecycleInput.Constructed, + method: EtsMethod, + parameterIndex: Int, + ): TsLifecycleInput.Constructed? = input.withComparisonStringSeed(method, parameterIndex) + + fun booleanAlternative(input: TsLifecycleInput.Callback): TsLifecycleInput.Callback? { + if (input.returnOperand != EtsBooleanConstant.FALSE) return null + + val trueResult = Search().constantReturn(input.functionType.signature.returnType, depth = 0) { type -> + when (type) { + EtsBooleanType -> EtsBooleanConstant.TRUE + is EtsBooleanLiteralType -> EtsBooleanConstant.TRUE.takeIf { type.value } + else -> null + } + } ?: return null + return input.copy(returnOperand = trueResult) + } + + private inner class Search { + private var remainingVisits = MAX_TYPE_VISITS + + fun plan(type: EtsType, depth: Int, constructing: Set): TsLifecycleInput? { + if (!consumeTypeVisit(depth)) return null + + val literal = primitiveLiteral(type) + if (literal != null) return TsLifecycleInput.Literal(literal, declaredType = type) + + return when (type) { + is EtsAliasType -> plan(type.originalType, depth + 1, constructing) + is EtsUnionType -> { + val concrete = type.types.asSequence().filter { it != EtsNullType && it != EtsUndefinedType } + val nullish = type.types.asSequence().filter { it == EtsNullType || it == EtsUndefinedType } + (concrete + nullish).firstNotNullOfOrNull { plan(it, depth + 1, constructing) } + } + is EtsClassType -> construct(type, depth, constructing) + is EtsClassValueType -> classValue(type) + is EtsFunctionType -> callback(type, depth) + else -> null + } + } + + private fun construct( + type: EtsClassType, + depth: Int, + constructing: Set, + ): TsLifecycleInput.Constructed? { + if (type.signature in constructing) return null + + val clazz = sourceClass(type.signature) ?: return null + val constructor = publicConstructor(clazz) ?: return null + val hasMatchingArity = clazz.typeParameters.size == type.typeParameters.size + if (!hasMatchingArity || constructor.typeParameters.isNotEmpty()) return null + + val candidates = constructorArgumentTypes(constructor.parameters) + .filter { it.size <= MAX_CONSTRUCTOR_ARGUMENTS } + .take(MAX_REST_TUPLE_VARIANTS) + val active = constructing + type.signature + for (types in candidates) { + val arguments = planArguments(types, depth + 1, active) ?: continue + return TsLifecycleInput.Constructed(type, constructor, arguments) + } + return null + } + + private fun planArguments( + types: List, + depth: Int, + constructing: Set, + ): List? { + val result = mutableListOf() + for (type in types) { + val argument = plan(type, depth, constructing) ?: return null + result += argument + } + return result + } + + private fun callback(type: EtsFunctionType, depth: Int): TsLifecycleInput.Callback? { + val parameters = type.signature.parameters + val explicitReceiver = parameters.any { it.name == "this" } + if (explicitReceiver) return null + + val returnType = type.signature.returnType + if (returnType == EtsVoidType || returnType == EtsUndefinedType) { + return TsLifecycleInput.Callback(type, returnOperand = null) + } + + val requiredMatchingParameter = parameters.firstOrNull { + !it.isOptional && !it.isRest && it.type == returnType + } + val returnOperand = when { + requiredMatchingParameter != null -> EtsParameterRef(index = requiredMatchingParameter.index, type = returnType) + returnType is EtsUnionType || returnType is EtsAliasType -> constantReturn(returnType, depth + 1) + else -> primitiveLiteral(returnType) + } ?: return null + return TsLifecycleInput.Callback(type, returnOperand) + } + + fun constantReturn( + type: EtsType, + depth: Int, + literal: (EtsType) -> EtsConstant? = ::primitiveLiteral, + ): EtsConstant? { + if (!consumeTypeVisit(depth)) return null + + if (type is EtsAliasType) return constantReturn(type.originalType, depth + 1, literal) + if (type !is EtsUnionType) return literal(type) + + var nullishFallback: EtsConstant? = null + for (member in type.types) { + if (remainingVisits == 0) break + + val candidate = constantReturn(member, depth + 1, literal) ?: continue + val isNullish = candidate == EtsNullConstant || candidate == EtsUndefinedConstant + if (!isNullish) return candidate + if (nullishFallback == null) nullishFallback = candidate + } + return nullishFallback + } + + private fun consumeTypeVisit(depth: Int): Boolean { + if (depth >= MAX_TYPE_DEPTH || remainingVisits == 0) return false + + remainingVisits-- + return true + } + } + + private fun classValue(type: EtsClassValueType): TsLifecycleInput? { + val clazz = sourceClass(type.signature) ?: return null + publicConstructor(clazz) ?: return null + return TsLifecycleInput.Literal(EtsClassValueRef(type.signature)) + } + + private fun sourceClass(signature: EtsClassSignature): EtsClass? = + classes[signature]?.singleOrNull()?.takeIf { it.category == EtsClassCategory.CLASS } + + private fun publicConstructor(clazz: EtsClass): EtsMethod? { + if (clazz.isAbstract || clazz.isDeclare) return null + + val declarations = clazz.methods.filter { it.name == CONSTRUCTOR_NAME } + // Bodyless overload declarations need their own admissible-signature selection. + val constructor = declarations.singleOrNull() ?: return null + if (constructor.isPrivate || constructor.isProtected) return null + + val statements = constructor.cfg.stmts + val hasExecutableBody = statements.isNotEmpty() && statements.none { it is EtsRawStmt } + return constructor.takeIf { hasExecutableBody } + } + + private fun constructorArgumentTypes(parameters: List): Sequence> { + val rest = parameters.lastOrNull()?.takeIf { it.isRest } + if (rest == null) { + val required = parameters.dropLastWhile { it.isOptional } + return sequenceOf(required.map { it.type }) + } + + val fixed = parameters.dropLast(1) + return restArgumentTypes(rest.type).map { restTypes -> + val prefix = if (restTypes.isEmpty()) fixed.dropLastWhile { it.isOptional } else fixed + prefix.map { it.type } + restTypes + } + } + + private fun restArgumentTypes(type: EtsType): Sequence> = when (type) { + is EtsArrayType -> sequenceOf(emptyList()) + is EtsTupleType -> sequenceOf(type.types) + is EtsUnionType -> type.types.asSequence().filterIsInstance().map { it.types } + else -> emptySequence() + } + + private fun primitiveLiteral(type: EtsType): EtsConstant? = when (type) { + EtsBooleanType -> EtsBooleanConstant.FALSE + EtsNumberType -> EtsNumberConstant(value = 1.0) + EtsStringType -> EtsStringConstant(value = "x") + EtsNullType -> EtsNullConstant + EtsUndefinedType -> EtsUndefinedConstant + is EtsBooleanLiteralType -> EtsBooleanConstant(type.value) + is EtsNumberLiteralType -> EtsNumberConstant(type.value) + is EtsStringLiteralType -> EtsStringConstant(type.value) + else -> null + } + + private companion object { + const val MAX_TYPE_DEPTH = 6 + const val MAX_TYPE_VISITS = 48 + const val MAX_CONSTRUCTOR_ARGUMENTS = 4 + const val MAX_REST_TUPLE_VARIANTS = 4 + } +} diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleMethodBuilder.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleMethodBuilder.kt index 4a2c6dd761..be98075b00 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleMethodBuilder.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleMethodBuilder.kt @@ -26,12 +26,13 @@ import org.jacodb.ets.model.EtsType import org.jacodb.ets.model.EtsUnknownType internal class TsLifecycleMethodBuilder( - private val owner: EtsClassSignature, + val owner: EtsClassSignature, private val name: String, ) { private val parameters = mutableListOf() private val locals = mutableListOf() private val statements = mutableListOf<(EtsStmtLocation) -> EtsStmt>() + private val callbacks = mutableListOf() private var callableGuard: Int? = null fun newLocal(type: EtsType): EtsLocal = EtsLocal(name = "%${locals.size}", type = type).also(locals::add) @@ -74,7 +75,13 @@ internal class TsLifecycleMethodBuilder( callableGuard = statements.size } - fun finish(value: EtsLocal): EtsMethod { + fun registerCallback(method: EtsMethodImpl) { + callbacks += method + } + + fun callbackName(): String = "$name.callback${callbacks.size}" + + fun finish(value: EtsLocal): List { val signature = EtsMethodSignature( enclosingClass = owner, name = name, @@ -103,6 +110,6 @@ internal class TsLifecycleMethodBuilder( EtsBlockCfg(blocks, successors = mapOf(0 to listOf(1, 2), 1 to emptyList(), 2 to emptyList())) } method.body.locals = locals.toList() - return method + return listOf(method) + callbacks } } diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleStringSeed.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleStringSeed.kt new file mode 100644 index 0000000000..d830978f3c --- /dev/null +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleStringSeed.kt @@ -0,0 +1,80 @@ +package org.usvm.machine.lifecycle + +import org.jacodb.ets.model.EtsAssignStmt +import org.jacodb.ets.model.EtsEntity +import org.jacodb.ets.model.EtsInstanceFieldRef +import org.jacodb.ets.model.EtsLocal +import org.jacodb.ets.model.EtsMethod +import org.jacodb.ets.model.EtsParameterRef +import org.jacodb.ets.model.EtsStrictEqExpr +import org.jacodb.ets.model.EtsStringConstant +import org.jacodb.ets.model.EtsStringType +import org.jacodb.ets.utils.getOperands + +/** A nearby comparison suggests a candidate string; the constructor still decides whether it accepts it. */ +internal fun TsLifecycleInput.Constructed.withComparisonStringSeed( + method: EtsMethod, + parameterIndex: Int, +): TsLifecycleInput.Constructed? { + val definitions = method.cfg.stmts.filterIsInstance() + .mapNotNull { assignment -> + val local = assignment.lhv as? EtsLocal ?: return@mapNotNull null + local.name to assignment.rhv + }.groupBy(keySelector = { it.first }, valueTransform = { it.second }) + + return method.cfg.stmts.asSequence() + .flatMap { it.getOperands() } + .filterIsInstance() + .firstNotNullOfOrNull { comparison -> + val leftSeed = comparison.left as? EtsStringConstant + val rightSeed = comparison.right as? EtsStringConstant + val seed = leftSeed ?: rightSeed ?: return@firstNotNullOfOrNull null + if (seed.value.length > MAX_SEED_LENGTH) return@firstNotNullOfOrNull null + + val otherOperand = if (leftSeed == null) comparison.left else comparison.right + val refersToParameter = otherOperand.originatesAtParameter(parameterIndex, definitions, depth = 0) + if (!refersToParameter) return@firstNotNullOfOrNull null + withFirstBroadString(seed) + } +} + +private fun EtsEntity.originatesAtParameter( + parameterIndex: Int, + definitions: Map>, + depth: Int, +): Boolean { + if (depth >= MAX_OPERAND_DEPTH) return false + + return when (this) { + is EtsParameterRef -> index == parameterIndex + is EtsInstanceFieldRef -> instance.originatesAtParameter(parameterIndex, definitions, depth + 1) + is EtsLocal -> { + val definition = definitions[name]?.singleOrNull() ?: return false + definition.originatesAtParameter(parameterIndex, definitions, depth + 1) + } + else -> false + } +} + +private fun TsLifecycleInput.Constructed.withFirstBroadString( + seed: EtsStringConstant, +): TsLifecycleInput.Constructed? { + for ((index, argument) in arguments.withIndex()) { + val replacement = when (argument) { + is TsLifecycleInput.Constructed -> argument.withFirstBroadString(seed) + is TsLifecycleInput.Literal -> { + val replaceable = argument.declaredType == EtsStringType && argument.value != seed + if (replaceable) argument.copy(value = seed) else null + } + is TsLifecycleInput.Callback -> null + } ?: continue + + val updated = arguments.toMutableList() + updated[index] = replacement + return copy(arguments = updated) + } + return null +} + +private const val MAX_SEED_LENGTH = 32 +private const val MAX_OPERAND_DEPTH = 12 diff --git a/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/AutomaticLifecycleTest.kt b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/AutomaticLifecycleTest.kt index 39719a0997..4a94a24e5f 100644 --- a/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/AutomaticLifecycleTest.kt +++ b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/AutomaticLifecycleTest.kt @@ -79,5 +79,40 @@ class AutomaticLifecycleTest : TsMethodTestRunner() { assertEquals(expected = 1, actual = enteredMethods.count { it != null }) } + @Test + fun `an argument witness runs after construction of the method receiver`() { + val target = scene.projectClasses.single { it.name == "AutomaticOrder" } + val scenarios = buildTsLifecycleScenarios(scene = scene, target = target) + val entry = scenarios.methods.single { it.name == "witness.observe" } + + val values = TsMachine(scene = scenarios.scene, tsOptions = TsOptions()).use { machine -> + val analysis = machine.analyzeWithMetadata(methods = listOf(entry)) + assertFalse(analysis.engineFailed) + assertTrue(analysis.unsupportedPaths.isEmpty(), analysis.unsupportedPaths.toString()) + analysis.states.map { TsTestResolver().resolve(method = entry, state = it).returnValue } + } + + assertEquals(setOf(13.0), values.numericValues()) + } + + @Test + fun `a source comparison adds one candidate beside the default construction`() { + val target = scene.projectClasses.single { it.name == "AutomaticComparison" } + val scenarios = buildTsLifecycleScenarios(scene = scene, target = target) + + val values = TsMachine(scene = scenarios.scene, tsOptions = TsOptions()).use { machine -> + val analysis = machine.analyzeWithMetadata(methods = scenarios.methods) + assertFalse(analysis.engineFailed) + assertTrue(analysis.unsupportedPaths.isEmpty(), analysis.unsupportedPaths.toString()) + analysis.states.associate { state -> + val entry = state.entrypoint + val result = TsTestResolver().resolve(method = entry, state = state).returnValue + entry.name to (result as TsTestValue.TsNumber).number + } + } + + assertEquals(mapOf("witness.classify" to 0.0, "witness.classify.comparison" to 1.0), values) + } + private fun List.numericValues(): Set = map { (it as TsTestValue.TsNumber).number }.toSet() } diff --git a/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleCapturedInputFactoryTest.kt b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleCapturedInputFactoryTest.kt new file mode 100644 index 0000000000..650416db62 --- /dev/null +++ b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleCapturedInputFactoryTest.kt @@ -0,0 +1,76 @@ +package org.usvm.machine.lifecycle + +import org.jacodb.ets.model.EtsScene +import org.junit.jupiter.api.Test +import org.usvm.StateCollectionStrategy +import org.usvm.api.TsTestValue +import org.usvm.machine.TsMachine +import org.usvm.machine.buildTsLifecycleScenarios +import org.usvm.util.TsMethodTestRunner +import org.usvm.util.TsTestResolver +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import org.usvm.test.util.checkers.eq as exactly + +class TsLifecycleCapturedInputFactoryTest : TsMethodTestRunner() { + private val sourceScene = loadScene(resourcePath = "/samples/lang/CapturedInputFactory.ts") + private val factory = sourceScene.projectClasses.single { it.name == "CapturedInputFactory" } + private val scenarios = buildTsLifecycleScenarios(scene = sourceScene, target = factory) + override val scene: EtsScene = scenarios.scene + + init { + options = options.copy( + stateCollectionStrategy = StateCollectionStrategy.ALL, + stopOnCoverage = 0, + ) + } + + @Test + fun `calls update the captured counter without changing its input object`() { + val method = getMethod(methodName = "observe", className = "CapturedInputFactory") + val expected = listOf(22.0, 21.0, 21.0) + + checkMatches>( + method = method, + analysisResultNumberMatches = exactly(count = 1), + { result -> result.values.map { it.number } == expected }, + ) + } + + @Test + fun `factory witness constructs the input and invokes the returned closure`() { + val method = scenarios.methods.single { it.name == "witness.return.create" } + + checkMatches( + method = method, + analysisResultNumberMatches = exactly(count = 2), + { direction, result -> direction.number == -1.0 && result.number == 0.0 }, + { direction, result -> direction.number != -1.0 && result.number == 2.0 }, + ) + } + + @Test + fun `generated call passes separate numeric inputs to the factory and closure`() { + val primitiveFactory = sourceScene.projectClasses.single { it.name == "PrimitiveCaptureFactory" } + val primitiveScenarios = buildTsLifecycleScenarios(scene = sourceScene, target = primitiveFactory) + val method = primitiveScenarios.methods.single { it.name == "return.create" } + + val (analysis, tests) = TsMachine(scene = primitiveScenarios.scene, options = options, tsOptions = tsOptions).use { + val analysis = it.analyzeWithMetadata(methods = listOf(method)) + analysis to analysis.states.map { state -> TsTestResolver().resolve(method = method, state = state) } + } + + assertFalse(analysis.engineFailed) + assertFalse(analysis.unsupportedCall) + assertTrue(analysis.unsupportedPaths.isEmpty(), analysis.unsupportedPaths.toString()) + assertEquals(expected = 2, actual = method.parameters.size) + assertEquals(expected = 2, actual = tests.size) + assertEquals(setOf(0.0, 1.0), tests.map { (it.returnValue as TsTestValue.TsNumber).number }.toSet()) + for (test in tests) { + val (expected, value) = test.before.parameters.map { (it as TsTestValue.TsNumber).number } + val result = (test.returnValue as TsTestValue.TsNumber).number + assertEquals(expected = if (value == expected) 1.0 else 0.0, actual = result) + } + } +} diff --git a/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlannerTest.kt b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlannerTest.kt new file mode 100644 index 0000000000..c04ef187d5 --- /dev/null +++ b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlannerTest.kt @@ -0,0 +1,111 @@ +package org.usvm.machine.lifecycle + +import org.jacodb.ets.model.EtsBooleanConstant +import org.jacodb.ets.model.EtsClassValueRef +import org.jacodb.ets.model.EtsParameterRef +import org.jacodb.ets.model.EtsScene +import org.jacodb.ets.model.EtsStringConstant +import org.junit.jupiter.api.Test +import org.usvm.api.TsTestValue +import org.usvm.machine.buildTsLifecycleScenarios +import org.usvm.util.TsMethodTestRunner +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull + +class TsLifecycleInputPlannerTest : TsMethodTestRunner() { + private val sourceScene = loadScene(resourcePath = "/samples/types/LifecycleInputPlanning.ts") + private val target = sourceScene.projectClasses.single { it.name == "LifecycleInputPlanning" } + private val scenarios = buildTsLifecycleScenarios(sourceScene, target) + override val scene: EtsScene = scenarios.scene + private val planner = TsLifecycleInputPlanner(sourceScene) + + @Test + fun `plans public constructors through an admissible rest tuple`() { + val plan = planner.plan(parameterType("constructed")) + + val restChoice = assertIs(plan) + assertEquals("RestChoice", restChoice.constructor.signature.enclosingClass.name) + val atom = assertIs(restChoice.arguments.single()) + assertEquals("Atom", atom.constructor.signature.enclosingClass.name) + val argument = assertIs(atom.arguments.single()) + assertEquals(EtsStringConstant(value = "atom"), argument.value) + } + + @Test + fun `does not invent instances for unavailable constructors or recursive types`() { + val unavailable = listOf("privateConstructor", "abstractClass", "interfaceValue", "cycle") + + for (method in unavailable) { + assertNull(planner.plan(parameterType(method)), method) + } + } + + @Test + fun `uses an exact class reference and callbacks with explicit behavior`() { + val classValue = planner.plan(parameterType("classValue")) + val identity = planner.plan(parameterType("identity")) + val noOp = planner.plan(parameterType("noOp")) + val predicate = planner.plan(parameterType("predicate")) + val unsupportedReturn = planner.plan(parameterType("unsupportedReturn")) + + val reference = assertIs(classValue) + assertEquals("Atom", assertIs(reference.value).signature.name) + val parameter = assertIs(assertIs(identity).returnOperand) + assertEquals(0, parameter.index) + assertNull(assertIs(noOp).returnOperand) + assertEquals(EtsBooleanConstant.FALSE, assertIs(predicate).returnOperand) + assertNull(unsupportedReturn) + } + + @Test + fun `generated witnesses run constructors and callback bodies`() { + val constructed = witnessMethod("constructed") + val classValue = witnessMethod("classValue") + val identity = witnessMethod("identity") + val noOp = witnessMethod("noOp") + + for (method in listOf(constructed, classValue)) { + discoverProperties( + method = method, + { result -> result.value == "atom" }, + invariants = arrayOf({ result -> result.value == "atom" }), + ) + } + discoverProperties( + method = identity, + { result -> result.number == 37.0 }, + invariants = arrayOf({ result -> result.number == 37.0 }), + ) + discoverProperties( + method = noOp, + { result -> result.value }, + invariants = arrayOf({ result -> result.value }), + ) + } + + @Test + fun `strict comparison gives a second seed for a broad constructor string`() { + val compared = sourceMethod("stringSeed") + val fixed = sourceMethod("fixedLiteral") + val unrelated = sourceMethod("unrelatedSeed") + val original = assertIs(planner.plan(compared.parameters.single().type)) + val fixedInput = assertIs(planner.plan(fixed.parameters.single().type)) + + val seeded = planner.comparisonAlternative(original, compared, parameterIndex = 0) + val rejectedFixed = planner.comparisonAlternative(fixedInput, fixed, parameterIndex = 0) + val rejectedUnrelated = planner.comparisonAlternative(original, unrelated, parameterIndex = 0) + + val changedInput = assertIs(seeded) + assertEquals(EtsStringConstant(value = "branch"), assertIs(changedInput.arguments.single()).value) + assertEquals(EtsStringConstant(value = "x"), assertIs(original.arguments.single()).value) + assertNull(rejectedFixed) + assertNull(rejectedUnrelated) + } + + private fun witnessMethod(method: String) = scenarios.methods.single { it.name == "witness.$method" } + + private fun sourceMethod(method: String) = getMethod(method, className = "LifecycleInputPlanning") + + private fun parameterType(method: String) = sourceMethod(method).parameters.single().type +} diff --git a/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleNullableCallbackTest.kt b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleNullableCallbackTest.kt new file mode 100644 index 0000000000..efbaafe223 --- /dev/null +++ b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleNullableCallbackTest.kt @@ -0,0 +1,40 @@ +package org.usvm.machine.lifecycle + +import org.jacodb.ets.model.EtsScene +import org.junit.jupiter.api.Test +import org.usvm.api.TsTestValue +import org.usvm.machine.buildTsLifecycleScenarios +import org.usvm.util.TsMethodTestRunner +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class TsLifecycleNullableCallbackTest : TsMethodTestRunner() { + private val sourceScene = loadScene(resourcePath = "/samples/types/LifecycleInputPlanning.ts") + private val factory = sourceScene.projectClasses.single { it.name == "NullablePredicateFactory" } + private val scenarios = buildTsLifecycleScenarios(sourceScene, factory) + override val scene: EtsScene = scenarios.scene + + @Test + fun `returned validators call predicates with union and aliased union results`() { + val generated = scenarios.methods.associateBy { it.name } + + for (name in listOf("witness.return.filter", "witness.return.filterAlias")) { + val method = generated.getValue(name) + discoverProperties( + method = method, + { result -> result.value }, + invariants = arrayOf({ result -> result.value }), + ) + } + + val truePredicate = generated.getValue("witness.return.filter.true") + discoverProperties( + method = truePredicate, + { result -> !result.value }, + invariants = arrayOf({ result -> !result.value }), + ) + + assertTrue("return.opaque" in generated) + assertNull(generated["witness.return.opaque"]) + } +} diff --git a/usvm-ts/src/test/resources/samples/lang/AutomaticLifecycle.ts b/usvm-ts/src/test/resources/samples/lang/AutomaticLifecycle.ts index 8aa7858de4..7c9400abbb 100644 --- a/usvm-ts/src/test/resources/samples/lang/AutomaticLifecycle.ts +++ b/usvm-ts/src/test/resources/samples/lang/AutomaticLifecycle.ts @@ -35,3 +35,33 @@ class AutomaticLifecycle { return this.total; } } + +class AutomaticOrder { + static phase = 0; + + constructor() { + AutomaticOrder.phase = 13; + } + + observe(argument: AutomaticOrderArgument): number { + return argument.observed; + } +} + +class AutomaticOrderArgument { + observed: number; + + constructor() { + this.observed = AutomaticOrder.phase; + } +} + +class AutomaticComparison { + static classify(argument: AutomaticComparisonArgument): number { + return argument.name === "preferred" ? 1 : 0; + } +} + +class AutomaticComparisonArgument { + constructor(public name: string) {} +} diff --git a/usvm-ts/src/test/resources/samples/lang/CapturedInputFactory.ts b/usvm-ts/src/test/resources/samples/lang/CapturedInputFactory.ts new file mode 100644 index 0000000000..94e39f1a98 --- /dev/null +++ b/usvm-ts/src/test/resources/samples/lang/CapturedInputFactory.ts @@ -0,0 +1,34 @@ +export class CounterInput { + value: number; + + constructor(value: number) { + this.value = value; + } +} + +export class CapturedInputFactory { + static create(input: CounterInput): (direction: number) => number { + let current = input.value; + + return (direction: number) => { + current = current + (direction === -1 ? -1 : 1); + return current; + }; + } + + static observe(): number[] { + const input = new CounterInput(21); + const next = CapturedInputFactory.create(input); + + const first = next(1); + const second = next(-1); + + return [first, second, input.value]; + } +} + +export class PrimitiveCaptureFactory { + static create(expected: number): (value: number) => number { + return (value: number) => value === expected ? 1 : 0; + } +} diff --git a/usvm-ts/src/test/resources/samples/types/LifecycleInputPlanning.ts b/usvm-ts/src/test/resources/samples/types/LifecycleInputPlanning.ts new file mode 100644 index 0000000000..a04a954d35 --- /dev/null +++ b/usvm-ts/src/test/resources/samples/types/LifecycleInputPlanning.ts @@ -0,0 +1,87 @@ +class Atom { + constructor(readonly value: "atom", scale?: number) {} +} + +class RestChoice { + readonly marker: string; + + constructor(...arguments_: [Atom] | [string, number]) { + const first = arguments_[0]; + this.marker = typeof first === "string" ? first : first.value; + } +} + +class TextChoice { + constructor(readonly value: string) {} +} + +class PrivateConstructor { + private constructor() {} +} + +abstract class AbstractValue {} + +interface InterfaceValue { + value: number; +} + +class CyclicArgument { + constructor(readonly next: CyclicArgument) {} +} + +export class LifecycleInputPlanning { + constructed(value: RestChoice): string { + return value.marker; + } + + privateConstructor(value: PrivateConstructor): void {} + abstractClass(value: AbstractValue): void {} + interfaceValue(value: InterfaceValue): void {} + cycle(value: CyclicArgument): void {} + + classValue(value: typeof Atom): string { + return new value("atom").value; + } + + identity(callback: (value: number) => number): number { + return callback(37); + } + + noOp(callback: (value: number) => void): boolean { + return callback(14) === undefined; + } + + private predicate(callback: (value: number) => boolean): boolean { + return callback(7); + } + + unsupportedReturn(callback: (value: number) => CyclicArgument): void {} + + private stringSeed(choice: TextChoice): boolean { + return choice.value === "branch"; + } + + private fixedLiteral(choice: Atom): boolean { + return "other" === choice.value; + } + + private unrelatedSeed(choice: TextChoice, other: string): boolean { + return other === "unrelated"; + } +} + +type NullableDecision = null | boolean; + +export class NullablePredicateFactory { + static filter(predicate: (value: number | null) => boolean | null): () => boolean { + return () => predicate(null) === false; + } + + static filterAlias(predicate: (value: number | null) => NullableDecision): () => boolean { + return () => predicate(7) === false; + } + + static opaque(predicate: (value: number | null) => CyclicArgument | AbstractValue): () => boolean { + return () => predicate(null) !== undefined; + } +} From b3a31c20d1719c01be573830b6a3509b326561ee Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Wed, 2 Dec 2026 21:09:57 +0100 Subject: [PATCH 2/2] Keep typed lifecycle planning and fixtures within lint limits --- .../kotlin/org/usvm/machine/TsLifecycleScenarios.kt | 12 +++++++++++- .../lifecycle/TsLifecycleInputMaterializer.kt | 3 ++- .../machine/lifecycle/TsLifecycleInputPlanner.kt | 6 ++++-- .../usvm/machine/lifecycle/TsLifecycleStringSeed.kt | 3 ++- .../lifecycle/TsLifecycleCapturedInputFactoryTest.kt | 8 ++++++-- .../machine/lifecycle/TsLifecycleInputPlannerTest.kt | 6 ++++-- 6 files changed, 29 insertions(+), 9 deletions(-) diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/TsLifecycleScenarios.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/TsLifecycleScenarios.kt index bc97aec443..3dbb86e8c9 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/TsLifecycleScenarios.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/TsLifecycleScenarios.kt @@ -123,7 +123,8 @@ fun buildTsLifecycleScenarios( if (!method.isStatic && constructor == null) return@mapNotNull null directMethodPlan(name = method.name, method, constructor, constructorTypes) } - val witnessCandidates = plans.filter { it.name.startsWith("return.") || it.name.startsWith("field.") } + calledMethods + val callablePlans = plans.filter { it.name.startsWith("return.") || it.name.startsWith("field.") } + val witnessCandidates = callablePlans + calledMethods val witnessPlans = witnessCandidates.filter { it.types.size <= MAX_ARGUMENTS }.mapNotNull { plan -> val witness = preferredWitness(plan.types, planner) ?: return@mapNotNull null plan.copy(name = "witness.${plan.name}", witness = witness) @@ -135,6 +136,15 @@ fun buildTsLifecycleScenarios( val predicateWitness = selectedWitnesses.firstNotNullOfOrNull { it.booleanAlternative(planner) } if (predicateWitness != null) plans += predicateWitness + return materializeLifecyclePlans(scene = scene, owner = owner, plans = plans) +} + +private fun materializeLifecyclePlans( + scene: EtsScene, + owner: EtsClassSignature, + plans: List, +): TsLifecycleScenarios { + val driverFile = owner.file val returnedCallableScenarios = linkedMapOf() val entries = plans.filter { it.types.size <= MAX_ARGUMENTS }.map { plan -> val builder = TsLifecycleMethodBuilder(owner, plan.name) diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputMaterializer.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputMaterializer.kt index d927085866..23b3b27019 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputMaterializer.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputMaterializer.kt @@ -35,8 +35,9 @@ private fun TsLifecycleMethodBuilder.materializeCallback(input: TsLifecycleInput location = EtsStmtLocation(method = callback, index = 0), returnValue = input.returnOperand, ) + val body = BasicBlock(id = 0, statements = listOf(returnStatement)) callback.body.cfg = EtsBlockCfg( - blocks = listOf(BasicBlock(id = 0, statements = listOf(returnStatement))), + blocks = listOf(body), successors = mapOf(0 to emptyList()), ) registerCallback(callback) diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlanner.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlanner.kt index 53917cc289..1dd2f36923 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlanner.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlanner.kt @@ -46,7 +46,6 @@ internal sealed interface TsLifecycleInput { ) : TsLifecycleInput data class Callback(val functionType: EtsFunctionType, val returnOperand: EtsValue?) : TsLifecycleInput - } /** Plans one source-level construction candidate. A constructor still runs its own validation at execution time. */ @@ -147,7 +146,10 @@ internal class TsLifecycleInputPlanner(scene: EtsScene) { !it.isOptional && !it.isRest && it.type == returnType } val returnOperand = when { - requiredMatchingParameter != null -> EtsParameterRef(index = requiredMatchingParameter.index, type = returnType) + requiredMatchingParameter != null -> EtsParameterRef( + index = requiredMatchingParameter.index, + type = returnType, + ) returnType is EtsUnionType || returnType is EtsAliasType -> constantReturn(returnType, depth + 1) else -> primitiveLiteral(returnType) } ?: return null diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleStringSeed.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleStringSeed.kt index d830978f3c..51e030dc4d 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleStringSeed.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/lifecycle/TsLifecycleStringSeed.kt @@ -20,7 +20,8 @@ internal fun TsLifecycleInput.Constructed.withComparisonStringSeed( .mapNotNull { assignment -> val local = assignment.lhv as? EtsLocal ?: return@mapNotNull null local.name to assignment.rhv - }.groupBy(keySelector = { it.first }, valueTransform = { it.second }) + } + .groupBy(keySelector = { it.first }, valueTransform = { it.second }) return method.cfg.stmts.asSequence() .flatMap { it.getOperands() } diff --git a/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleCapturedInputFactoryTest.kt b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleCapturedInputFactoryTest.kt index 650416db62..a904a545ef 100644 --- a/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleCapturedInputFactoryTest.kt +++ b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleCapturedInputFactoryTest.kt @@ -56,8 +56,12 @@ class TsLifecycleCapturedInputFactoryTest : TsMethodTestRunner() { val primitiveScenarios = buildTsLifecycleScenarios(scene = sourceScene, target = primitiveFactory) val method = primitiveScenarios.methods.single { it.name == "return.create" } - val (analysis, tests) = TsMachine(scene = primitiveScenarios.scene, options = options, tsOptions = tsOptions).use { - val analysis = it.analyzeWithMetadata(methods = listOf(method)) + val (analysis, tests) = TsMachine( + scene = primitiveScenarios.scene, + options = options, + tsOptions = tsOptions, + ).use { machine -> + val analysis = machine.analyzeWithMetadata(methods = listOf(method)) analysis to analysis.states.map { state -> TsTestResolver().resolve(method = method, state = state) } } diff --git a/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlannerTest.kt b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlannerTest.kt index c04ef187d5..64083568a9 100644 --- a/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlannerTest.kt +++ b/usvm-ts/src/test/kotlin/org/usvm/machine/lifecycle/TsLifecycleInputPlannerTest.kt @@ -97,8 +97,10 @@ class TsLifecycleInputPlannerTest : TsMethodTestRunner() { val rejectedUnrelated = planner.comparisonAlternative(original, unrelated, parameterIndex = 0) val changedInput = assertIs(seeded) - assertEquals(EtsStringConstant(value = "branch"), assertIs(changedInput.arguments.single()).value) - assertEquals(EtsStringConstant(value = "x"), assertIs(original.arguments.single()).value) + val changedArgument = assertIs(changedInput.arguments.single()) + val originalArgument = assertIs(original.arguments.single()) + assertEquals(EtsStringConstant(value = "branch"), changedArgument.value) + assertEquals(EtsStringConstant(value = "x"), originalArgument.value) assertNull(rejectedFixed) assertNull(rejectedUnrelated) }