Skip to content

Add executable generic parameter type resolving #2584

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 20, 2023
Merged
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
108 changes: 108 additions & 0 deletions utbot-java-fuzzing/src/main/kotlin/org/utbot/fuzzer/TypeUtils.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package org.utbot.fuzzer

import com.google.common.reflect.TypeResolver
import com.google.common.reflect.TypeToken
import mu.KotlinLogging
import org.utbot.framework.plugin.api.ConstructorId
import org.utbot.framework.plugin.api.ExecutableId
import org.utbot.framework.plugin.api.MethodId
import org.utbot.framework.plugin.api.util.constructor
import org.utbot.framework.plugin.api.util.executable
import org.utbot.framework.plugin.api.util.isArray
import org.utbot.framework.plugin.api.util.jClass
import org.utbot.framework.plugin.api.util.method
import java.lang.reflect.GenericArrayType
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.util.Optional

private val logger = KotlinLogging.logger {}
private val loggedUnresolvedExecutables = mutableSetOf<ExecutableId>()

val Type.typeToken: TypeToken<*> get() = TypeToken.of(this)
inline fun <reified T> typeTokenOf(): TypeToken<T> = object : TypeToken<T>() {}
inline fun <reified T> jTypeOf(): Type = typeTokenOf<T>().type

val FuzzedType.jType: Type get() = toType(cache = mutableMapOf())

private fun FuzzedType.toType(cache: MutableMap<FuzzedType, Type>): Type = cache.getOrPut(this) {
when {
generics.isEmpty() -> classId.jClass
classId.isArray && generics.size == 1 -> GenericArrayType { generics.single().toType(cache) }
else -> object : ParameterizedType {
override fun getActualTypeArguments(): Array<Type> =
generics.map { it.toType(cache) }.toTypedArray()

override fun getRawType(): Type =
classId.jClass

override fun getOwnerType(): Type? = null
}
}
}

/**
* Returns fully parameterized type, e.g. for `Map` class
* `Map<K, V>` type is returned, where `K` and `V` are type variables.
*/
fun Class<*>.toTypeParametrizedByTypeVariables(): Type =
if (typeParameters.isEmpty()) this
else object : ParameterizedType {
override fun getActualTypeArguments(): Array<Type> =
typeParameters.toList().toTypedArray()

override fun getRawType(): Type =
this@toTypeParametrizedByTypeVariables

override fun getOwnerType(): Type? =
declaringClass?.toTypeParametrizedByTypeVariables()
}

/**
* Returns types of arguments that should be passed to [executableId] for it to return [neededType] and `null` iff
* [executableId] can't return [neededType] (e.g. if it returns `List<String>` while `List<Integer>` is needed).
*
* For example, if [executableId] is [Optional.of] and [neededType] is `Optional<String>`,
* then one element list containing `String` type is returned.
*/
fun resolveParameterTypes(
executableId: ExecutableId,
neededType: Type
): List<Type>? {
return try {
val actualType = when (executableId) {
is MethodId -> executableId.method.genericReturnType
is ConstructorId -> executableId.constructor.declaringClass.toTypeParametrizedByTypeVariables()
}

val neededClass = neededType.typeToken.rawType
val actualClass = actualType.typeToken.rawType

if (!neededClass.isAssignableFrom(actualClass))
return null

@Suppress("UNCHECKED_CAST")
val actualSuperType = actualType.typeToken.getSupertype(neededClass as Class<in Any>).type
val typeResolver = try {
TypeResolver().where(actualSuperType, neededType)
} catch (e: Exception) {
// TypeResolver.where() throws an exception when unification of actual & needed types fails
// e.g. when unifying Optional<Integer> and Optional<String>
return null
}

// in some cases when bounded wildcards are involved TypeResolver.where() doesn't throw even though types are
// incompatible (e.g. when needed type is `List<? super Integer>` while actual super type is `List<String>`)
if (!typeResolver.resolveType(actualSuperType).typeToken.isSubtypeOf(neededType))
return null

executableId.executable.genericParameterTypes.map {
typeResolver.resolveType(it)
}
} catch (e: Exception) {
if (loggedUnresolvedExecutables.add(executableId))
logger.error(e) { "Failed to resolve types for $executableId, using unresolved generic type" }

executableId.executable.genericParameterTypes.toList()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ import org.utbot.fuzzing.Routine
import org.utbot.fuzzing.Scope
import org.utbot.fuzzing.ScopeProperty
import org.utbot.fuzzing.Seed
import org.utbot.fuzzing.spring.utils.jType
import org.utbot.fuzzing.spring.utils.toTypeParametrizedByTypeVariables
import org.utbot.fuzzing.spring.utils.typeToken
import org.utbot.fuzzer.jType
import org.utbot.fuzzer.toTypeParametrizedByTypeVariables
import org.utbot.fuzzer.typeToken
import org.utbot.fuzzing.toFuzzerType

val methodsToMockProperty = ScopeProperty<Set<MethodId>>(
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package org.utbot.fuzzing.samples;

import java.util.*;

public class StringList extends ArrayList<String> {
public static StringList create() {
return new StringList();
}

public static List<String> createAndUpcast() {
return new StringList();
}

public static List<StringList> createListOfLists() {
return new ArrayList<>();
}

public static List<List<String>> createListOfUpcastedLists() {
return new ArrayList<>();
}

public static List<? extends List<? extends String>> createReadOnlyListOfReadOnlyLists() {
return new ArrayList<>();
}

@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static <T> List<? extends List<T>> createListOfParametrizedLists(Optional<? extends T> elm) {
return Collections.singletonList(Collections.singletonList(elm.orElse(null)));
}
}
Loading