diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/KCallablesJvm.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/KCallablesJvm.kt index cf773643099..9db5eb30708 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/KCallablesJvm.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/KCallablesJvm.kt @@ -15,6 +15,7 @@ */ @file:JvmName("KCallablesJvm") + package kotlin.reflect.jvm import java.lang.reflect.AccessibleObject @@ -40,21 +41,21 @@ var KCallable<*>.isAccessible: Boolean return when (this) { is KMutableProperty -> javaField?.isAccessible ?: true && - javaGetter?.isAccessible ?: true && - javaSetter?.isAccessible ?: true + javaGetter?.isAccessible ?: true && + javaSetter?.isAccessible ?: true is KProperty -> javaField?.isAccessible ?: true && - javaGetter?.isAccessible ?: true + javaGetter?.isAccessible ?: true is KProperty.Getter -> property.javaField?.isAccessible ?: true && - javaMethod?.isAccessible ?: true + javaMethod?.isAccessible ?: true is KMutableProperty.Setter<*> -> property.javaField?.isAccessible ?: true && - javaMethod?.isAccessible ?: true + javaMethod?.isAccessible ?: true is KFunction -> javaMethod?.isAccessible ?: true && - (this.asKCallableImpl()?.defaultCaller?.member as? AccessibleObject)?.isAccessible ?: true && - this.javaConstructor?.isAccessible ?: true + (this.asKCallableImpl()?.defaultCaller?.member as? AccessibleObject)?.isAccessible ?: true && + this.javaConstructor?.isAccessible ?: true else -> throw UnsupportedOperationException("Unknown callable: $this ($javaClass)") } } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/KClassesJvm.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/KClassesJvm.kt index afe4a145f8b..b676a665e28 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/KClassesJvm.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/KClassesJvm.kt @@ -15,6 +15,7 @@ */ @file:JvmName("KClassesJvm") + package kotlin.reflect.jvm import kotlin.reflect.KClass @@ -26,6 +27,4 @@ import kotlin.reflect.jvm.internal.KClassImpl * @see [java.lang.Class.getName] */ val KClass<*>.jvmName: String - get() { - return (this as KClassImpl).jClass.name - } + get() = (this as KClassImpl).jClass.name diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/KTypesJvm.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/KTypesJvm.kt index 4d4379241ee..a07cda5f80a 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/KTypesJvm.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/KTypesJvm.kt @@ -15,14 +15,18 @@ */ @file:JvmName("KTypesJvm") + package kotlin.reflect.jvm import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind.ANNOTATION_CLASS import org.jetbrains.kotlin.descriptors.ClassKind.INTERFACE -import kotlin.reflect.* -import kotlin.reflect.jvm.internal.KotlinReflectionInternalError +import kotlin.reflect.KClass +import kotlin.reflect.KClassifier +import kotlin.reflect.KType +import kotlin.reflect.KTypeParameter import kotlin.reflect.jvm.internal.KTypeImpl +import kotlin.reflect.jvm.internal.KotlinReflectionInternalError /** * Returns the [KClass] instance representing the runtime class to which this type is erased to on JVM. diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/ReflectJvmMapping.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/ReflectJvmMapping.kt index 1f25585c6d2..84e4a4cede2 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/ReflectJvmMapping.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/ReflectJvmMapping.kt @@ -15,11 +15,11 @@ */ @file:JvmName("ReflectJvmMapping") + package kotlin.reflect.jvm import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader import java.lang.reflect.* -import java.util.* import kotlin.reflect.* import kotlin.reflect.full.companionObject import kotlin.reflect.full.functions @@ -65,7 +65,8 @@ val KFunction<*>.javaMethod: Method? * Returns a Java [Constructor] instance corresponding to the given Kotlin function, * or `null` if this function is not a constructor or cannot be represented by a Java [Constructor]. */ -@Suppress("UNCHECKED_CAST") val KFunction.javaConstructor: Constructor? +@Suppress("UNCHECKED_CAST") +val KFunction.javaConstructor: Constructor? get() = this.asKCallableImpl()?.caller?.member as? Constructor @@ -78,7 +79,6 @@ val KType.javaType: Type get() = (this as KTypeImpl).javaType - // Java reflection -> Kotlin reflection /** @@ -102,11 +102,11 @@ val Field.kotlinProperty: KProperty<*>? private fun Member.getKPackage(): KDeclarationContainer? = - when (ReflectKotlinClass.create(declaringClass)?.classHeader?.kind) { - KotlinClassHeader.Kind.FILE_FACADE, KotlinClassHeader.Kind.MULTIFILE_CLASS, KotlinClassHeader.Kind.MULTIFILE_CLASS_PART -> - KPackageImpl(declaringClass) - else -> null - } + when (ReflectKotlinClass.create(declaringClass)?.classHeader?.kind) { + KotlinClassHeader.Kind.FILE_FACADE, KotlinClassHeader.Kind.MULTIFILE_CLASS, KotlinClassHeader.Kind.MULTIFILE_CLASS_PART -> + KPackageImpl(declaringClass) + else -> null + } /** * Returns a [KFunction] instance corresponding to the given Java [Method] instance, @@ -129,7 +129,7 @@ val Method.kotlinFunction: KFunction<*>? companion.functions.firstOrNull { val m = it.javaMethod m != null && m.name == this.name && - Arrays.equals(m.parameterTypes, this.parameterTypes) && m.returnType == this.returnType + m.parameterTypes!!.contentEquals(this.parameterTypes) && m.returnType == this.returnType }?.let { return it } } } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/AnnotationConstructorCaller.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/AnnotationConstructorCaller.kt index f9536aa12f6..1b57df815a1 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/AnnotationConstructorCaller.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/AnnotationConstructorCaller.kt @@ -23,13 +23,13 @@ import kotlin.reflect.jvm.internal.structure.wrapperByPrimitive import java.lang.reflect.Method as ReflectMethod internal class AnnotationConstructorCaller( - private val jClass: Class<*>, - private val parameterNames: List, - private val callMode: CallMode, - origin: Origin, - private val methods: List = parameterNames.map { name -> jClass.getDeclaredMethod(name) } + private val jClass: Class<*>, + private val parameterNames: List, + private val callMode: CallMode, + origin: Origin, + private val methods: List = parameterNames.map { name -> jClass.getDeclaredMethod(name) } ) : FunctionCaller( - null, jClass, null, methods.map { it.genericReturnType }.toTypedArray() + null, jClass, null, methods.map { it.genericReturnType }.toTypedArray() ) { enum class CallMode { CALL_BY_NAME, POSITIONAL_CALL } @@ -44,9 +44,9 @@ internal class AnnotationConstructorCaller( // TODO: consider lifting this restriction once KT-8957 is implemented if (callMode == CallMode.POSITIONAL_CALL && origin == Origin.JAVA && (parameterNames - "value").isNotEmpty()) { throw UnsupportedOperationException( - "Positional call of a Java annotation constructor is allowed only if there are no parameters " + - "or one parameter named \"value\". This restriction exists because Java annotations (in contrast to Kotlin)" + - "do not impose any order on their arguments. Use KCallable#callBy instead." + "Positional call of a Java annotation constructor is allowed only if there are no parameters " + + "or one parameter named \"value\". This restriction exists because Java annotations (in contrast to Kotlin)" + + "do not impose any order on their arguments. Use KCallable#callBy instead." ) } } @@ -56,8 +56,8 @@ internal class AnnotationConstructorCaller( val values = args.mapIndexed { index, arg -> val value = - if (arg == null && callMode == CallMode.CALL_BY_NAME) defaultValues[index] - else arg.transformKotlinToJvm(erasedParameterTypes[index]) + if (arg == null && callMode == CallMode.CALL_BY_NAME) defaultValues[index] + else arg.transformKotlinToJvm(erasedParameterTypes[index]) value ?: throwIllegalArgumentType(index, parameterNames[index], erasedParameterTypes[index]) } @@ -103,23 +103,23 @@ private fun throwIllegalArgumentType(index: Int, name: String, expectedJvmType: private fun createAnnotationInstance(annotationClass: Class<*>, methods: List, values: Map): Any { fun equals(other: Any?): Boolean = - (other as? Annotation)?.annotationClass?.java == annotationClass && - methods.all { method -> - val ours = values[method.name] - val theirs = method(other) - when (ours) { - is BooleanArray -> Arrays.equals(ours, theirs as BooleanArray) - is CharArray -> Arrays.equals(ours, theirs as CharArray) - is ByteArray -> Arrays.equals(ours, theirs as ByteArray) - is ShortArray -> Arrays.equals(ours, theirs as ShortArray) - is IntArray -> Arrays.equals(ours, theirs as IntArray) - is FloatArray -> Arrays.equals(ours, theirs as FloatArray) - is LongArray -> Arrays.equals(ours, theirs as LongArray) - is DoubleArray -> Arrays.equals(ours, theirs as DoubleArray) - is Array<*> -> Arrays.equals(ours, theirs as Array<*>) - else -> ours == theirs + (other as? Annotation)?.annotationClass?.java == annotationClass && + methods.all { method -> + val ours = values[method.name] + val theirs = method(other) + when (ours) { + is BooleanArray -> Arrays.equals(ours, theirs as BooleanArray) + is CharArray -> Arrays.equals(ours, theirs as CharArray) + is ByteArray -> Arrays.equals(ours, theirs as ByteArray) + is ShortArray -> Arrays.equals(ours, theirs as ShortArray) + is IntArray -> Arrays.equals(ours, theirs as IntArray) + is FloatArray -> Arrays.equals(ours, theirs as FloatArray) + is LongArray -> Arrays.equals(ours, theirs as LongArray) + is DoubleArray -> Arrays.equals(ours, theirs as DoubleArray) + is Array<*> -> Arrays.equals(ours, theirs as Array<*>) + else -> ours == theirs + } } - } val hashCode by lazy { values.entries.sumBy { entry -> @@ -163,7 +163,7 @@ private fun createAnnotationInstance(annotationClass: Class<*>, methods: List + return Proxy.newProxyInstance(annotationClass.classLoader, arrayOf(annotationClass)) { _, method, args -> val name = method.name when (name) { "annotationType" -> annotationClass diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/EmptyContainerForLocal.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/EmptyContainerForLocal.kt index 44b2cef7bd4..7bec8703ee2 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/EmptyContainerForLocal.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/EmptyContainerForLocal.kt @@ -39,7 +39,6 @@ internal object EmptyContainerForLocal : KDeclarationContainerImpl() { override fun getLocalProperty(index: Int): PropertyDescriptor? = null private fun fail(): Nothing = throw KotlinReflectionInternalError( - "Introspecting local functions, lambdas, anonymous functions and local variables " + - "is not yet fully supported in Kotlin reflection" + "Introspecting local functions, lambdas, anonymous functions and local variables is not yet fully supported in Kotlin reflection" ) } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/FunctionCaller.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/FunctionCaller.kt index 157c537a811..9afe8230cea 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/FunctionCaller.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/FunctionCaller.kt @@ -24,14 +24,13 @@ import java.lang.reflect.Field as ReflectField import java.lang.reflect.Method as ReflectMethod internal abstract class FunctionCaller( - internal val member: M, - internal val returnType: Type, - internal val instanceClass: Class<*>?, - valueParameterTypes: Array + internal val member: M, + internal val returnType: Type, + internal val instanceClass: Class<*>?, + valueParameterTypes: Array ) { val parameterTypes: List = - instanceClass?.let { listOf(it, *valueParameterTypes) } ?: - valueParameterTypes.toList() + instanceClass?.let { listOf(it, *valueParameterTypes) } ?: valueParameterTypes.toList() val arity: Int get() = parameterTypes.size @@ -53,13 +52,13 @@ internal abstract class FunctionCaller( // Constructors class Constructor(constructor: ReflectConstructor<*>) : FunctionCaller>( - constructor, - constructor.declaringClass, - constructor.declaringClass.let { klass -> - val outerClass = klass.declaringClass - if (outerClass != null && !Modifier.isStatic(klass.modifiers)) outerClass else null - }, - constructor.genericParameterTypes + constructor, + constructor.declaringClass, + constructor.declaringClass.let { klass -> + val outerClass = klass.declaringClass + if (outerClass != null && !Modifier.isStatic(klass.modifiers)) outerClass else null + }, + constructor.genericParameterTypes ) { override fun call(args: Array<*>): Any? { checkArguments(args) @@ -70,10 +69,10 @@ internal abstract class FunctionCaller( // TODO fix 'callBy' for bound (and non-bound) inner class constructor references // See https://youtrack.jetbrains.com/issue/KT-14990 class BoundConstructor(constructor: ReflectConstructor<*>, private val boundReceiver: Any?) : - FunctionCaller>( - constructor, constructor.declaringClass, null, - constructor.genericParameterTypes - ) { + FunctionCaller>( + constructor, constructor.declaringClass, null, + constructor.genericParameterTypes + ) { override fun call(args: Array<*>): Any? { checkArguments(args) return member.newInstance(*argsWithReceiver(boundReceiver, args)) @@ -83,14 +82,14 @@ internal abstract class FunctionCaller( // Methods abstract class Method( - method: ReflectMethod, - requiresInstance: Boolean = !Modifier.isStatic(method.modifiers), - parameterTypes: Array = method.genericParameterTypes + method: ReflectMethod, + requiresInstance: Boolean = !Modifier.isStatic(method.modifiers), + parameterTypes: Array = method.genericParameterTypes ) : FunctionCaller( - method, - method.genericReturnType, - if (requiresInstance) method.declaringClass else null, - parameterTypes + method, + method.genericReturnType, + if (requiresInstance) method.declaringClass else null, + parameterTypes ) { private val isVoidMethod = returnType == Void.TYPE @@ -124,24 +123,23 @@ internal abstract class FunctionCaller( } } - class BoundStaticMethod(method: ReflectMethod, private val boundReceiver: Any?) : - Method(method, requiresInstance = false, parameterTypes = method.genericParameterTypes.dropFirst()) { + class BoundStaticMethod(method: ReflectMethod, private val boundReceiver: Any?) : Method( + method, requiresInstance = false, parameterTypes = method.genericParameterTypes.dropFirst() + ) { override fun call(args: Array<*>): Any? { checkArguments(args) return callMethod(null, argsWithReceiver(boundReceiver, args)) } } - class BoundInstanceMethod(method: ReflectMethod, private val boundReceiver: Any?) : - Method(method, requiresInstance = false) { + class BoundInstanceMethod(method: ReflectMethod, private val boundReceiver: Any?) : Method(method, requiresInstance = false) { override fun call(args: Array<*>): Any? { checkArguments(args) return callMethod(boundReceiver, args) } } - class BoundJvmStaticInObject(method: ReflectMethod) : - Method(method, requiresInstance = false) { + class BoundJvmStaticInObject(method: ReflectMethod) : Method(method, requiresInstance = false) { override fun call(args: Array<*>): Any? { checkArguments(args) return callMethod(null, args) @@ -151,13 +149,13 @@ internal abstract class FunctionCaller( // Field accessors abstract class FieldGetter( - field: ReflectField, - requiresInstance: Boolean = !Modifier.isStatic(field.modifiers) + field: ReflectField, + requiresInstance: Boolean = !Modifier.isStatic(field.modifiers) ) : FunctionCaller( - field, - field.genericType, - if (requiresInstance) field.declaringClass else null, - emptyArray() + field, + field.genericType, + if (requiresInstance) field.declaringClass else null, + emptyArray() ) { override fun call(args: Array<*>): Any? { checkArguments(args) @@ -166,14 +164,14 @@ internal abstract class FunctionCaller( } abstract class FieldSetter( - field: ReflectField, - private val notNull: Boolean, - requiresInstance: Boolean = !Modifier.isStatic(field.modifiers) + field: ReflectField, + private val notNull: Boolean, + requiresInstance: Boolean = !Modifier.isStatic(field.modifiers) ) : FunctionCaller( - field, - Void.TYPE, - if (requiresInstance) field.declaringClass else null, - arrayOf(field.genericType) + field, + Void.TYPE, + if (requiresInstance) field.declaringClass else null, + arrayOf(field.genericType) ) { override fun checkArguments(args: Array<*>) { super.checkArguments(args) @@ -199,16 +197,18 @@ internal abstract class FunctionCaller( } } - class ClassCompanionFieldGetter(field: ReflectField, klass: Class<*>) : - FunctionCaller(field, field.genericType, klass, emptyArray()) { + class ClassCompanionFieldGetter(field: ReflectField, klass: Class<*>) : FunctionCaller( + field, field.genericType, klass, emptyArray() + ) { override fun call(args: Array<*>): Any? { checkArguments(args) return member.get(args.first()) } } - class BoundInstanceFieldGetter(field: ReflectField, private val boundReceiver: Any?) : - FieldGetter(field, requiresInstance = false) { + class BoundInstanceFieldGetter(field: ReflectField, private val boundReceiver: Any?) : FieldGetter( + field, requiresInstance = false + ) { override fun call(args: Array<*>): Any? { checkArguments(args) return member.get(boundReceiver) @@ -217,8 +217,9 @@ internal abstract class FunctionCaller( class BoundJvmStaticInObjectFieldGetter(field: ReflectField) : FieldGetter(field, requiresInstance = false) - class BoundClassCompanionFieldGetter(field: ReflectField, private val boundReceiver: Any?) : - FieldGetter(field, requiresInstance = false) { + class BoundClassCompanionFieldGetter(field: ReflectField, private val boundReceiver: Any?) : FieldGetter( + field, requiresInstance = false + ) { override fun call(args: Array<*>): Any? { checkArguments(args) return member.get(boundReceiver) @@ -236,32 +237,36 @@ internal abstract class FunctionCaller( } } - class ClassCompanionFieldSetter(field: ReflectField, klass: Class<*>) : - FunctionCaller(field, Void.TYPE, klass, arrayOf(field.genericType)) { + class ClassCompanionFieldSetter(field: ReflectField, klass: Class<*>) : FunctionCaller( + field, Void.TYPE, klass, arrayOf(field.genericType) + ) { override fun call(args: Array<*>): Any? { checkArguments(args) return member.set(null, args.last()) } } - class BoundInstanceFieldSetter(field: ReflectField, notNull: Boolean, private val boundReceiver: Any?) : - FieldSetter(field, notNull, false) { + class BoundInstanceFieldSetter(field: ReflectField, notNull: Boolean, private val boundReceiver: Any?) : FieldSetter( + field, notNull, false + ) { override fun call(args: Array<*>): Any? { checkArguments(args) return member.set(boundReceiver, args.first()) } } - class BoundJvmStaticInObjectFieldSetter(field: ReflectField, notNull: Boolean) : - FieldSetter(field, notNull, requiresInstance = false) { + class BoundJvmStaticInObjectFieldSetter(field: ReflectField, notNull: Boolean) : FieldSetter( + field, notNull, requiresInstance = false + ) { override fun call(args: Array<*>): Any? { checkArguments(args) return member.set(null, args.last()) } } - class BoundClassCompanionFieldSetter(field: ReflectField, klass: Class<*>) : - FunctionCaller(field, Void.TYPE, klass, arrayOf(field.genericType)) { + class BoundClassCompanionFieldSetter(field: ReflectField, klass: Class<*>) : FunctionCaller( + field, Void.TYPE, klass, arrayOf(field.genericType) + ) { override fun call(args: Array<*>): Any? { checkArguments(args) return member.set(null, args.last()) @@ -277,17 +282,17 @@ internal abstract class FunctionCaller( companion object { // TODO lazily allocate array at bound callers? fun argsWithReceiver(receiver: Any?, args: Array): Array = - arrayOfNulls(args.size + 1).apply { - this[0] = receiver - System.arraycopy(args, 0, this, 1, args.size) - } + arrayOfNulls(args.size + 1).apply { + this[0] = receiver + System.arraycopy(args, 0, this, 1, args.size) + } @Suppress("UNCHECKED_CAST") inline fun Array.dropFirst(): Array = - if (size <= 1) emptyArray() else copyOfRange(1, size) as Array + if (size <= 1) emptyArray() else copyOfRange(1, size) as Array @Suppress("UNCHECKED_CAST") fun Array<*>.dropFirstArg(): Array = - (this as Array).dropFirst() + (this as Array).dropFirst() } } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/FunctionWithAllInvokes.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/FunctionWithAllInvokes.kt index 2ae761a6411..aa61cd70a71 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/FunctionWithAllInvokes.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/FunctionWithAllInvokes.kt @@ -19,31 +19,31 @@ package kotlin.reflect.jvm.internal import kotlin.reflect.KCallable internal interface FunctionWithAllInvokes : - // (0..22).forEach { n -> println("Function$n<" + (0..n).joinToString { "Any?" } + ">,") } - Function0, - Function1, - Function2, - Function3, - Function4, - Function5, - Function6, - Function7, - Function8, - Function9, - Function10, - Function11, - Function12, - Function13, - Function14, - Function15, - Function16, - Function17, - Function18, - Function19, - Function20, - Function21, - Function22, - KCallable + // (0..22).forEach { n -> println("Function$n<" + (0..n).joinToString { "Any?" } + ">,") } + Function0, + Function1, + Function2, + Function3, + Function4, + Function5, + Function6, + Function7, + Function8, + Function9, + Function10, + Function11, + Function12, + Function13, + Function14, + Function15, + Function16, + Function17, + Function18, + Function19, + Function20, + Function21, + Function22, + KCallable { // (0..22).forEach { n -> println("override fun invoke(" + (1..n).joinToString { "p$it: Any?" } + "): Any? = call(" + (1..n).joinToString { "p$it" } + ")") } override fun invoke(): Any? = call() diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KCallableImpl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KCallableImpl.kt index 96f215593c4..fbdb5a0b579 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KCallableImpl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KCallableImpl.kt @@ -22,7 +22,6 @@ import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor import java.lang.reflect.Type import java.util.* import kotlin.reflect.* -import kotlin.reflect.jvm.internal.KotlinReflectionInternalError import kotlin.reflect.jvm.javaType internal abstract class KCallableImpl : KCallable { @@ -38,11 +37,11 @@ internal abstract class KCallableImpl : KCallable { abstract val isBound: Boolean - private val annotations_ = ReflectProperties.lazySoft { descriptor.computeAnnotations() } + private val _annotations = ReflectProperties.lazySoft { descriptor.computeAnnotations() } - override val annotations: List get() = annotations_() + override val annotations: List get() = _annotations() - private val parameters_ = ReflectProperties.lazySoft { + private val _parameters = ReflectProperties.lazySoft { val descriptor = descriptor val result = ArrayList() var index = 0 @@ -71,21 +70,21 @@ internal abstract class KCallableImpl : KCallable { } override val parameters: List - get() = parameters_() + get() = _parameters() - private val returnType_ = ReflectProperties.lazySoft { + private val _returnType = ReflectProperties.lazySoft { KTypeImpl(descriptor.returnType!!) { caller.returnType } } override val returnType: KType - get() = returnType_() + get() = _returnType() - private val typeParameters_ = ReflectProperties.lazySoft { + private val _typeParameters = ReflectProperties.lazySoft { descriptor.typeParameters.map(::KTypeParameterImpl) } override val typeParameters: List - get() = typeParameters_() + get() = _typeParameters() override val visibility: KVisibility? get() = descriptor.visibility.toKVisibility() @@ -184,19 +183,18 @@ internal abstract class KCallableImpl : KCallable { } private fun defaultPrimitiveValue(type: Type): Any? = - if (type is Class<*> && type.isPrimitive) { - when (type) { - Boolean::class.java -> false - Char::class.java -> 0.toChar() - Byte::class.java -> 0.toByte() - Short::class.java -> 0.toShort() - Int::class.java -> 0 - Float::class.java -> 0f - Long::class.java -> 0L - Double::class.java -> 0.0 - Void.TYPE -> throw IllegalStateException("Parameter with void type is illegal") - else -> throw UnsupportedOperationException("Unknown primitive: $type") - } + if (type is Class<*> && type.isPrimitive) { + when (type) { + Boolean::class.java -> false + Char::class.java -> 0.toChar() + Byte::class.java -> 0.toByte() + Short::class.java -> 0.toShort() + Int::class.java -> 0 + Float::class.java -> 0f + Long::class.java -> 0L + Double::class.java -> 0.0 + Void.TYPE -> throw IllegalStateException("Parameter with void type is illegal") + else -> throw UnsupportedOperationException("Unknown primitive: $type") } - else null + } else null } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KClassImpl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KClassImpl.kt index 2a7e42fb815..1e900de7b2c 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KClassImpl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KClassImpl.kt @@ -47,8 +47,8 @@ internal class KClassImpl(override val jClass: Class) : KDeclaration val moduleData = data().moduleData val descriptor = - if (classId.isLocal) moduleData.deserialization.deserializeClass(classId) - else moduleData.module.findClassAcrossModuleDependencies(classId) + if (classId.isLocal) moduleData.deserialization.deserializeClass(classId) + else moduleData.module.findClassAcrossModuleDependencies(classId) descriptor ?: reportUnresolvedClass() } @@ -94,11 +94,11 @@ internal class KClassImpl(override val jClass: Class) : KDeclaration } val nestedClasses: Collection> by ReflectProperties.lazySoft { - descriptor.unsubstitutedInnerClassesScope.getContributedDescriptors().filterNot(DescriptorUtils::isEnumEntry).mapNotNull { - nestedClass -> - val jClass = (nestedClass as ClassDescriptor).toJavaClass() - jClass?.let { KClassImpl(it) } - } + descriptor.unsubstitutedInnerClassesScope.getContributedDescriptors().filterNot(DescriptorUtils::isEnumEntry) + .mapNotNull { nestedClass -> + val jClass = (nestedClass as ClassDescriptor).toJavaClass() + jClass?.let { KClassImpl(it) } + } } @Suppress("UNCHECKED_CAST") @@ -108,8 +108,7 @@ internal class KClassImpl(override val jClass: Class) : KDeclaration val field = if (descriptor.isCompanionObject && !CompanionObjectMapping.isMappedIntrinsicCompanionObject(descriptor)) { jClass.enclosingClass.getDeclaredField(descriptor.name.asString()) - } - else { + } else { jClass.getDeclaredField(JvmAbi.INSTANCE_FIELD) } field.get(null) as T @@ -128,12 +127,11 @@ internal class KClassImpl(override val jClass: Class) : KDeclaration if (superClass !is ClassDescriptor) throw KotlinReflectionInternalError("Supertype not a class: $superClass") val superJavaClass = superClass.toJavaClass() - ?: throw KotlinReflectionInternalError("Unsupported superclass of $this: $superClass") + ?: throw KotlinReflectionInternalError("Unsupported superclass of $this: $superClass") if (jClass.superclass == superJavaClass) { jClass.genericSuperclass - } - else { + } else { val index = jClass.interfaces.indexOf(superJavaClass) if (index < 0) throw KotlinReflectionInternalError("No superclass of $this in Java reflection for $superClass") jClass.genericInterfaces[index] @@ -151,11 +149,11 @@ internal class KClassImpl(override val jClass: Class) : KDeclaration val declaredNonStaticMembers: Collection> by ReflectProperties.lazySoft { getMembers(memberScope, DECLARED) } - val declaredStaticMembers: Collection> + private val declaredStaticMembers: Collection> by ReflectProperties.lazySoft { getMembers(staticScope, DECLARED) } - val inheritedNonStaticMembers: Collection> + private val inheritedNonStaticMembers: Collection> by ReflectProperties.lazySoft { getMembers(memberScope, INHERITED) } - val inheritedStaticMembers: Collection> + private val inheritedStaticMembers: Collection> by ReflectProperties.lazySoft { getMembers(staticScope, INHERITED) } val allNonStaticMembers: Collection> @@ -192,12 +190,12 @@ internal class KClassImpl(override val jClass: Class) : KDeclaration } override fun getProperties(name: Name): Collection = - (memberScope.getContributedVariables(name, NoLookupLocation.FROM_REFLECTION) + - staticScope.getContributedVariables(name, NoLookupLocation.FROM_REFLECTION)) + (memberScope.getContributedVariables(name, NoLookupLocation.FROM_REFLECTION) + + staticScope.getContributedVariables(name, NoLookupLocation.FROM_REFLECTION)) override fun getFunctions(name: Name): Collection = - memberScope.getContributedFunctions(name, NoLookupLocation.FROM_REFLECTION) + - staticScope.getContributedFunctions(name, NoLookupLocation.FROM_REFLECTION) + memberScope.getContributedFunctions(name, NoLookupLocation.FROM_REFLECTION) + + staticScope.getContributedFunctions(name, NoLookupLocation.FROM_REFLECTION) override fun getLocalProperty(index: Int): PropertyDescriptor? { // TODO: also check that this is a synthetic class (Metadata.k == 3) @@ -263,10 +261,10 @@ internal class KClassImpl(override val jClass: Class) : KDeclaration get() = descriptor.isCompanionObject override fun equals(other: Any?): Boolean = - other is KClassImpl<*> && javaObjectType == other.javaObjectType + other is KClassImpl<*> && javaObjectType == other.javaObjectType override fun hashCode(): Int = - javaObjectType.hashCode() + javaObjectType.hashCode() override fun toString(): String { return "class " + classId.let { classId -> @@ -282,15 +280,15 @@ internal class KClassImpl(override val jClass: Class) : KDeclaration when (kind) { KotlinClassHeader.Kind.FILE_FACADE, KotlinClassHeader.Kind.MULTIFILE_CLASS, KotlinClassHeader.Kind.MULTIFILE_CLASS_PART -> { throw UnsupportedOperationException( - "Packages and file facades are not yet supported in Kotlin reflection. " + - "Meanwhile please use Java reflection to inspect this class: $jClass" + "Packages and file facades are not yet supported in Kotlin reflection. " + + "Meanwhile please use Java reflection to inspect this class: $jClass" ) } KotlinClassHeader.Kind.SYNTHETIC_CLASS -> { throw UnsupportedOperationException( - "This class is an internal synthetic class generated by the Kotlin compiler, such as an anonymous class " + - "for a lambda, a SAM wrapper, a callable reference, etc. It's not a Kotlin class or interface, so the reflection " + - "library has no idea what declarations does it have. Please use Java reflection to inspect this class: $jClass" + "This class is an internal synthetic class generated by the Kotlin compiler, such as an anonymous class " + + "for a lambda, a SAM wrapper, a callable reference, etc. It's not a Kotlin class or interface, so the reflection " + + "library has no idea what declarations does it have. Please use Java reflection to inspect this class: $jClass" ) } KotlinClassHeader.Kind.UNKNOWN -> { diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KDeclarationContainerImpl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KDeclarationContainerImpl.kt index 9103e5a9c8e..cdf05a88350 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KDeclarationContainerImpl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KDeclarationContainerImpl.kt @@ -50,21 +50,20 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain protected fun getMembers(scope: MemberScope, belonginess: MemberBelonginess): Collection> { val visitor = object : DeclarationDescriptorVisitorEmptyBodies, Unit>() { override fun visitPropertyDescriptor(descriptor: PropertyDescriptor, data: Unit): KCallableImpl<*> = - createProperty(descriptor) + createProperty(descriptor) override fun visitFunctionDescriptor(descriptor: FunctionDescriptor, data: Unit): KCallableImpl<*> = - KFunctionImpl(this@KDeclarationContainerImpl, descriptor) + KFunctionImpl(this@KDeclarationContainerImpl, descriptor) override fun visitConstructorDescriptor(descriptor: ConstructorDescriptor, data: Unit): KCallableImpl<*> = - throw IllegalStateException("No constructors should appear in this scope: $descriptor") + throw IllegalStateException("No constructors should appear in this scope: $descriptor") } return scope.getContributedDescriptors().mapNotNull { descriptor -> if (descriptor is CallableMemberDescriptor && descriptor.visibility != Visibilities.INVISIBLE_FAKE && - belonginess.accept(descriptor)) - descriptor.accept(visitor, Unit) - else null + belonginess.accept(descriptor) + ) descriptor.accept(visitor, Unit) else null }.toList() } @@ -73,12 +72,12 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain INHERITED; fun accept(member: CallableMemberDescriptor): Boolean = - member.kind.isReal == (this == DECLARED) + member.kind.isReal == (this == DECLARED) } private fun createProperty(descriptor: PropertyDescriptor): KPropertyImpl<*> { val receiverCount = (descriptor.dispatchReceiverParameter?.let { 1 } ?: 0) + - (descriptor.extensionReceiverParameter?.let { 1 } ?: 0) + (descriptor.extensionReceiverParameter?.let { 1 } ?: 0) when { descriptor.isVar -> when (receiverCount) { @@ -101,13 +100,13 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain if (match != null) { val (number) = match.destructured return getLocalProperty(number.toInt()) - ?: throw KotlinReflectionInternalError("Local property #$number not found in $jClass") + ?: throw KotlinReflectionInternalError("Local property #$number not found in $jClass") } val properties = getProperties(Name.identifier(name)) - .filter { descriptor -> - RuntimeTypeMapper.mapPropertySignature(descriptor).asString() == signature - } + .filter { descriptor -> + RuntimeTypeMapper.mapPropertySignature(descriptor).asString() == signature + } if (properties.isEmpty()) { throw KotlinReflectionInternalError("Property '$name' (JVM signature: $signature) not resolved in $this") @@ -125,16 +124,16 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain // TODO: consider writing additional info (besides signature) to property reference objects to distinguish them in this case val mostVisibleProperties = properties - .groupBy { it.visibility } - .toSortedMap(Comparator { first, second -> - Visibilities.compare(first, second) ?: 0 - }).values.last() + .groupBy { it.visibility } + .toSortedMap(Comparator { first, second -> + Visibilities.compare(first, second) ?: 0 + }).values.last() if (mostVisibleProperties.size == 1) { return mostVisibleProperties.first() } throw KotlinReflectionInternalError( - "${properties.size} properties '$name' (JVM signature: $signature) resolved in $this: $properties" + "${properties.size} properties '$name' (JVM signature: $signature) resolved in $this: $properties" ) } @@ -143,15 +142,15 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain fun findFunctionDescriptor(name: String, signature: String): FunctionDescriptor { val functions = (if (name == "") constructorDescriptors.toList() else getFunctions(Name.identifier(name))) - .filter { descriptor -> - RuntimeTypeMapper.mapSignature(descriptor).asString() == signature - } + .filter { descriptor -> + RuntimeTypeMapper.mapSignature(descriptor).asString() == signature + } if (functions.size != 1) { val debugText = "'$name' (JVM signature: $signature)" throw KotlinReflectionInternalError( - if (functions.isEmpty()) "Function $debugText not resolved in $this" - else "${functions.size} functions $debugText resolved in $this: $functions" + if (functions.isEmpty()) "Function $debugText not resolved in $this" + else "${functions.size} functions $debugText resolved in $this: $functions" ) } @@ -178,35 +177,33 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain } private fun Class<*>.tryGetMethod(name: String, parameterTypes: Array>, returnType: Class<*>, declared: Boolean): Method? = - try { - val result = if (declared) getDeclaredMethod(name, *parameterTypes) else getMethod(name, *parameterTypes) + try { + val result = if (declared) getDeclaredMethod(name, *parameterTypes) else getMethod(name, *parameterTypes) - if (result.returnType == returnType) result - else { - // If we've found a method with an unexpected return type, it's likely that there are several methods in this class - // with the given parameter types and Java reflection API has returned not the one we're looking for. - // Falling back to enumerating all methods in the class in this (rather rare) case. - // Example: class A(val x: Int) { fun getX(): String = ... } - val allMethods = if (declared) declaredMethods else methods - allMethods.firstOrNull { method -> - method.name == name && - method.returnType == returnType && - method.parameterTypes.contentEquals(parameterTypes) - } + if (result.returnType == returnType) result + else { + // If we've found a method with an unexpected return type, it's likely that there are several methods in this class + // with the given parameter types and Java reflection API has returned not the one we're looking for. + // Falling back to enumerating all methods in the class in this (rather rare) case. + // Example: class A(val x: Int) { fun getX(): String = ... } + val allMethods = if (declared) declaredMethods else methods + allMethods.firstOrNull { method -> + method.name == name && + method.returnType == returnType && + method.parameterTypes!!.contentEquals(parameterTypes) } } - catch (e: NoSuchMethodException) { - null - } + } catch (e: NoSuchMethodException) { + null + } private fun Class<*>.tryGetConstructor(parameterTypes: List>, declared: Boolean): Constructor<*>? = - try { - if (declared) getDeclaredConstructor(*parameterTypes.toTypedArray()) - else getConstructor(*parameterTypes.toTypedArray()) - } - catch (e: NoSuchMethodException) { - null - } + try { + if (declared) getDeclaredConstructor(*parameterTypes.toTypedArray()) + else getConstructor(*parameterTypes.toTypedArray()) + } catch (e: NoSuchMethodException) { + null + } fun findMethodBySignature(name: String, desc: String, isPublic: Boolean): Method? { if (name == "") return null @@ -267,23 +264,23 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain } private fun parseType(desc: String, begin: Int, end: Int): Class<*> = - when (desc[begin]) { - 'L' -> jClass.safeClassLoader.loadClass(desc.substring(begin + 1, end - 1).replace('/', '.')) - '[' -> parseType(desc, begin + 1, end).createArrayType() - 'V' -> Void.TYPE - 'Z' -> Boolean::class.java - 'C' -> Char::class.java - 'B' -> Byte::class.java - 'S' -> Short::class.java - 'I' -> Int::class.java - 'F' -> Float::class.java - 'J' -> Long::class.java - 'D' -> Double::class.java - else -> throw KotlinReflectionInternalError("Unknown type prefix in the method signature: $desc") - } + when (desc[begin]) { + 'L' -> jClass.safeClassLoader.loadClass(desc.substring(begin + 1, end - 1).replace('/', '.')) + '[' -> parseType(desc, begin + 1, end).createArrayType() + 'V' -> Void.TYPE + 'Z' -> Boolean::class.java + 'C' -> Char::class.java + 'B' -> Byte::class.java + 'S' -> Short::class.java + 'I' -> Int::class.java + 'F' -> Float::class.java + 'J' -> Long::class.java + 'D' -> Double::class.java + else -> throw KotlinReflectionInternalError("Unknown type prefix in the method signature: $desc") + } private fun loadReturnType(desc: String): Class<*> = - parseType(desc, desc.indexOf(')') + 1, desc.length) + parseType(desc, desc.indexOf(')') + 1, desc.length) companion object { private val DEFAULT_CONSTRUCTOR_MARKER = Class.forName("kotlin.jvm.internal.DefaultConstructorMarker") diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KFunctionImpl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KFunctionImpl.kt index 308becedf63..8722ce17de9 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KFunctionImpl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KFunctionImpl.kt @@ -32,20 +32,20 @@ import kotlin.reflect.jvm.internal.AnnotationConstructorCaller.Origin.KOTLIN import kotlin.reflect.jvm.internal.JvmFunctionSignature.* internal class KFunctionImpl private constructor( - override val container: KDeclarationContainerImpl, - name: String, - private val signature: String, - descriptorInitialValue: FunctionDescriptor?, - private val boundReceiver: Any? = CallableReference.NO_RECEIVER + override val container: KDeclarationContainerImpl, + name: String, + private val signature: String, + descriptorInitialValue: FunctionDescriptor?, + private val boundReceiver: Any? = CallableReference.NO_RECEIVER ) : KCallableImpl(), KFunction, FunctionBase, FunctionWithAllInvokes { constructor(container: KDeclarationContainerImpl, name: String, signature: String, boundReceiver: Any?) : this(container, name, signature, null, boundReceiver) constructor(container: KDeclarationContainerImpl, descriptor: FunctionDescriptor) : this( - container, - descriptor.name.asString(), - RuntimeTypeMapper.mapSignature(descriptor).asString(), - descriptor + container, + descriptor.name.asString(), + RuntimeTypeMapper.mapSignature(descriptor).asString(), + descriptor ) override val isBound: Boolean get() = boundReceiver != CallableReference.NO_RECEIVER @@ -56,7 +56,7 @@ internal class KFunctionImpl private constructor( override val name: String get() = descriptor.name.asString() - override val caller: FunctionCaller<*> by ReflectProperties.lazySoft caller@ { + override val caller: FunctionCaller<*> by ReflectProperties.lazySoft caller@{ val jvmSignature = RuntimeTypeMapper.mapSignature(descriptor) val member: Member? = when (jvmSignature) { is KotlinConstructor -> { @@ -90,12 +90,14 @@ internal class KFunctionImpl private constructor( } } - override val defaultCaller: FunctionCaller<*>? by ReflectProperties.lazySoft defaultCaller@ { + override val defaultCaller: FunctionCaller<*>? by ReflectProperties.lazySoft defaultCaller@{ val jvmSignature = RuntimeTypeMapper.mapSignature(descriptor) val member: Member? = when (jvmSignature) { is KotlinFunction -> { - container.findDefaultMethod(jvmSignature.methodName, jvmSignature.methodDesc, - !Modifier.isStatic(caller.member!!.modifiers), descriptor.isPublicInBytecode) + container.findDefaultMethod( + jvmSignature.methodName, jvmSignature.methodDesc, + !Modifier.isStatic(caller.member!!.modifiers), descriptor.isPublicInBytecode + ) } is KotlinConstructor -> { if (isAnnotationConstructor) @@ -120,7 +122,7 @@ internal class KFunctionImpl private constructor( // In objects, $default's signature does _not_ contain the additional object instance parameter, // as opposed to companion objects where the first parameter is the companion object instance. descriptor.annotations.findAnnotation(JVM_STATIC) != null && - !(descriptor.containingDeclaration as ClassDescriptor).isCompanionObject -> + !(descriptor.containingDeclaration as ClassDescriptor).isCompanionObject -> createJvmStaticInObjectCaller(member) else -> @@ -131,16 +133,16 @@ internal class KFunctionImpl private constructor( } private fun createStaticMethodCaller(member: Method) = - if (isBound) FunctionCaller.BoundStaticMethod(member, boundReceiver) else FunctionCaller.StaticMethod(member) + if (isBound) FunctionCaller.BoundStaticMethod(member, boundReceiver) else FunctionCaller.StaticMethod(member) private fun createJvmStaticInObjectCaller(member: Method) = - if (isBound) FunctionCaller.BoundJvmStaticInObject(member) else FunctionCaller.JvmStaticInObject(member) + if (isBound) FunctionCaller.BoundJvmStaticInObject(member) else FunctionCaller.JvmStaticInObject(member) private fun createInstanceMethodCaller(member: Method) = - if (isBound) FunctionCaller.BoundInstanceMethod(member, boundReceiver) else FunctionCaller.InstanceMethod(member) + if (isBound) FunctionCaller.BoundInstanceMethod(member, boundReceiver) else FunctionCaller.InstanceMethod(member) private fun createConstructorCaller(member: Constructor<*>) = - if (isBound) FunctionCaller.BoundConstructor(member, boundReceiver) else FunctionCaller.Constructor(member) + if (isBound) FunctionCaller.BoundConstructor(member, boundReceiver) else FunctionCaller.Constructor(member) override fun getArity() = caller.arity @@ -165,8 +167,8 @@ internal class KFunctionImpl private constructor( } override fun hashCode(): Int = - (container.hashCode() * 31 + name.hashCode()) * 31 + signature.hashCode() + (container.hashCode() * 31 + name.hashCode()) * 31 + signature.hashCode() override fun toString(): String = - ReflectionObjectRenderer.renderFunction(descriptor) + ReflectionObjectRenderer.renderFunction(descriptor) } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KPackageImpl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KPackageImpl.kt index 97efeb45467..707a02cd482 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KPackageImpl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KPackageImpl.kt @@ -36,8 +36,8 @@ import kotlin.reflect.jvm.internal.components.ReflectKotlinClass import kotlin.reflect.jvm.internal.structure.classId internal class KPackageImpl( - override val jClass: Class<*>, - @Suppress("unused") val usageModuleName: String? = null // may be useful for debug + override val jClass: Class<*>, + @Suppress("unused") val usageModuleName: String? = null // may be useful for debug ) : KDeclarationContainerImpl() { private inner class Data : KDeclarationContainerImpl.Data() { private val kotlinClass: ReflectKotlinClass? by ReflectProperties.lazySoft { @@ -58,8 +58,7 @@ internal class KPackageImpl( // The default value for 'xs' is empty string, as declared in kotlin.Metadata if (facadeName != null && facadeName.isNotEmpty()) { jClass.classLoader.loadClass(facadeName.replace('/', '.')) - } - else { + } else { jClass } } @@ -70,8 +69,7 @@ internal class KPackageImpl( val strings = header.strings if (data != null && strings != null) { JvmProtoBufUtil.readPackageDataFrom(data, strings) - } - else null + } else null } } @@ -97,10 +95,10 @@ internal class KPackageImpl( get() = emptyList() override fun getProperties(name: Name): Collection = - scope.getContributedVariables(name, NoLookupLocation.FROM_REFLECTION) + scope.getContributedVariables(name, NoLookupLocation.FROM_REFLECTION) override fun getFunctions(name: Name): Collection = - scope.getContributedFunctions(name, NoLookupLocation.FROM_REFLECTION) + scope.getContributedFunctions(name, NoLookupLocation.FROM_REFLECTION) override fun getLocalProperty(index: Int): PropertyDescriptor? { return data().metadata?.let { (nameResolver, packageProto) -> @@ -111,10 +109,10 @@ internal class KPackageImpl( } override fun equals(other: Any?): Boolean = - other is KPackageImpl && jClass == other.jClass + other is KPackageImpl && jClass == other.jClass override fun hashCode(): Int = - jClass.hashCode() + jClass.hashCode() override fun toString(): String { val fqName = jClass.classId.packageFqName diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KParameterImpl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KParameterImpl.kt index 5a024be5dde..1c821868a95 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KParameterImpl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KParameterImpl.kt @@ -23,21 +23,22 @@ import kotlin.reflect.KParameter import kotlin.reflect.KType internal class KParameterImpl( - val callable: KCallableImpl<*>, - override val index: Int, - override val kind: KParameter.Kind, - computeDescriptor: () -> ParameterDescriptor + val callable: KCallableImpl<*>, + override val index: Int, + override val kind: KParameter.Kind, + computeDescriptor: () -> ParameterDescriptor ) : KParameter { private val descriptor: ParameterDescriptor by ReflectProperties.lazySoft(computeDescriptor) override val annotations: List by ReflectProperties.lazySoft { descriptor.computeAnnotations() } - override val name: String? get() { - val valueParameter = descriptor as? ValueParameterDescriptor ?: return null - if (valueParameter.containingDeclaration.hasSynthesizedParameterNames()) return null - val name = valueParameter.name - return if (name.isSpecial) null else name.asString() - } + override val name: String? + get() { + val valueParameter = descriptor as? ValueParameterDescriptor ?: return null + if (valueParameter.containingDeclaration.hasSynthesizedParameterNames()) return null + val name = valueParameter.name + return if (name.isSpecial) null else name.asString() + } override val type: KType get() = KTypeImpl(descriptor.type) { callable.caller.parameterTypes[index] } @@ -49,11 +50,11 @@ internal class KParameterImpl( get() = descriptor.let { it is ValueParameterDescriptor && it.varargElementType != null } override fun equals(other: Any?) = - other is KParameterImpl && callable == other.callable && descriptor == other.descriptor + other is KParameterImpl && callable == other.callable && descriptor == other.descriptor override fun hashCode() = - (callable.hashCode() * 31) + descriptor.hashCode() + (callable.hashCode() * 31) + descriptor.hashCode() override fun toString() = - ReflectionObjectRenderer.renderParameter(this) + ReflectionObjectRenderer.renderParameter(this) } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty0Impl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty0Impl.kt index 4b9bdd8b984..9ed1fe3219f 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty0Impl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty0Impl.kt @@ -24,11 +24,13 @@ import kotlin.reflect.KProperty0 internal open class KProperty0Impl : KProperty0, KPropertyImpl { constructor(container: KDeclarationContainerImpl, descriptor: PropertyDescriptor) : super(container, descriptor) - constructor(container: KDeclarationContainerImpl, name: String, signature: String, boundReceiver: Any?) : super(container, name, signature, boundReceiver) + constructor(container: KDeclarationContainerImpl, name: String, signature: String, boundReceiver: Any?) : super( + container, name, signature, boundReceiver + ) - private val getter_ = ReflectProperties.lazy { Getter(this) } + private val _getter = ReflectProperties.lazy { Getter(this) } - override val getter: Getter get() = getter_() + override val getter: Getter get() = _getter() override fun get(): R = getter.call() @@ -46,11 +48,13 @@ internal open class KProperty0Impl : KProperty0, KPropertyImpl { internal class KMutableProperty0Impl : KProperty0Impl, KMutableProperty0 { constructor(container: KDeclarationContainerImpl, descriptor: PropertyDescriptor) : super(container, descriptor) - constructor(container: KDeclarationContainerImpl, name: String, signature: String, boundReceiver: Any?) : super(container, name, signature, boundReceiver) + constructor(container: KDeclarationContainerImpl, name: String, signature: String, boundReceiver: Any?) : super( + container, name, signature, boundReceiver + ) - private val setter_ = ReflectProperties.lazy { Setter(this) } + private val _setter = ReflectProperties.lazy { Setter(this) } - override val setter: Setter get() = setter_() + override val setter: Setter get() = _setter() override fun set(value: R) = setter.call(value) diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty1Impl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty1Impl.kt index dbe1345d11b..7163b965575 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty1Impl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty1Impl.kt @@ -22,13 +22,15 @@ import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty1 internal open class KProperty1Impl : KProperty1, KPropertyImpl { - constructor(container: KDeclarationContainerImpl, name: String, signature: String, boundReceiver: Any?) : super(container, name, signature, boundReceiver) + constructor(container: KDeclarationContainerImpl, name: String, signature: String, boundReceiver: Any?) : super( + container, name, signature, boundReceiver + ) constructor(container: KDeclarationContainerImpl, descriptor: PropertyDescriptor) : super(container, descriptor) - private val getter_ = ReflectProperties.lazy { Getter(this) } + private val _getter = ReflectProperties.lazy { Getter(this) } - override val getter: Getter get() = getter_() + override val getter: Getter get() = _getter() override fun get(receiver: T): R = getter.call(receiver) @@ -44,13 +46,15 @@ internal open class KProperty1Impl : KProperty1, KPropertyImpl : KProperty1Impl, KMutableProperty1 { - constructor(container: KDeclarationContainerImpl, name: String, signature: String, boundReceiver: Any?) : super(container, name, signature, boundReceiver) + constructor(container: KDeclarationContainerImpl, name: String, signature: String, boundReceiver: Any?) : super( + container, name, signature, boundReceiver + ) constructor(container: KDeclarationContainerImpl, descriptor: PropertyDescriptor) : super(container, descriptor) - private val setter_ = ReflectProperties.lazy { Setter(this) } + private val _setter = ReflectProperties.lazy { Setter(this) } - override val setter: Setter get() = setter_() + override val setter: Setter get() = _setter() override fun set(receiver: T, value: R) = setter.call(receiver, value) diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty2Impl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty2Impl.kt index e57e5f5477d..04b6e711b94 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty2Impl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KProperty2Impl.kt @@ -23,13 +23,15 @@ import kotlin.reflect.KMutableProperty2 import kotlin.reflect.KProperty2 internal open class KProperty2Impl : KProperty2, KPropertyImpl { - constructor(container: KDeclarationContainerImpl, name: String, signature: String) : super(container, name, signature, CallableReference.NO_RECEIVER) + constructor(container: KDeclarationContainerImpl, name: String, signature: String) : super( + container, name, signature, CallableReference.NO_RECEIVER + ) constructor(container: KDeclarationContainerImpl, descriptor: PropertyDescriptor) : super(container, descriptor) - private val getter_ = ReflectProperties.lazy { Getter(this) } + private val _getter = ReflectProperties.lazy { Getter(this) } - override val getter: Getter get() = getter_() + override val getter: Getter get() = _getter() override fun get(receiver1: D, receiver2: E): R = getter.call(receiver1, receiver2) @@ -49,13 +51,14 @@ internal class KMutableProperty2Impl : KProperty2Impl, KMutabl constructor(container: KDeclarationContainerImpl, descriptor: PropertyDescriptor) : super(container, descriptor) - private val setter_ = ReflectProperties.lazy { Setter(this) } + private val _setter = ReflectProperties.lazy { Setter(this) } - override val setter: Setter get() = setter_() + override val setter: Setter get() = _setter() override fun set(receiver1: D, receiver2: E, value: R) = setter.call(receiver1, receiver2, value) - class Setter(override val property: KMutableProperty2Impl) : KPropertyImpl.Setter(), KMutableProperty2.Setter { + class Setter(override val property: KMutableProperty2Impl) : KPropertyImpl.Setter(), + KMutableProperty2.Setter { override fun invoke(receiver1: D, receiver2: E, value: R): Unit = property.set(receiver1, receiver2, value) } } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KPropertyImpl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KPropertyImpl.kt index 8aaab73b06a..ef3a392adf0 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KPropertyImpl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KPropertyImpl.kt @@ -33,27 +33,27 @@ import kotlin.reflect.full.IllegalPropertyDelegateAccessException import kotlin.reflect.jvm.internal.JvmPropertySignature.* internal abstract class KPropertyImpl private constructor( - override val container: KDeclarationContainerImpl, - override val name: String, - val signature: String, - descriptorInitialValue: PropertyDescriptor?, - val boundReceiver: Any? + override val container: KDeclarationContainerImpl, + override val name: String, + val signature: String, + descriptorInitialValue: PropertyDescriptor?, + val boundReceiver: Any? ) : KCallableImpl(), KProperty { constructor(container: KDeclarationContainerImpl, name: String, signature: String, boundReceiver: Any?) : this( - container, name, signature, null, boundReceiver + container, name, signature, null, boundReceiver ) constructor(container: KDeclarationContainerImpl, descriptor: PropertyDescriptor) : this( - container, - descriptor.name.asString(), - RuntimeTypeMapper.mapPropertySignature(descriptor).asString(), - descriptor, - CallableReference.NO_RECEIVER + container, + descriptor.name.asString(), + RuntimeTypeMapper.mapPropertySignature(descriptor).asString(), + descriptor, + CallableReference.NO_RECEIVER ) override val isBound: Boolean get() = boundReceiver != CallableReference.NO_RECEIVER - private val javaField_ = ReflectProperties.lazySoft { + private val _javaField = ReflectProperties.lazySoft { val jvmSignature = RuntimeTypeMapper.mapPropertySignature(descriptor) when (jvmSignature) { is KotlinProperty -> { @@ -61,16 +61,14 @@ internal abstract class KPropertyImpl private constructor( JvmProtoBufUtil.getJvmFieldSignature(jvmSignature.proto, jvmSignature.nameResolver, jvmSignature.typeTable)?.let { val owner = if (JvmAbi.isCompanionObjectWithBackingFieldsInOuter(descriptor.containingDeclaration)) { container.jClass.enclosingClass - } - else descriptor.containingDeclaration.let { containingDeclaration -> + } else descriptor.containingDeclaration.let { containingDeclaration -> if (containingDeclaration is ClassDescriptor) containingDeclaration.toJavaClass() else container.jClass } try { owner?.getDeclaredField(it.name) - } - catch (e: NoSuchFieldException) { + } catch (e: NoSuchFieldException) { null } } @@ -80,32 +78,33 @@ internal abstract class KPropertyImpl private constructor( } } - val javaField: Field? get() = javaField_() + val javaField: Field? get() = _javaField() protected fun computeDelegateField(): Field? = - if (@Suppress("DEPRECATION") descriptor.isDelegated) javaField else null + if (@Suppress("DEPRECATION") descriptor.isDelegated) javaField else null protected fun getDelegate(field: Field?, receiver: Any?): Any? = - try { - if (receiver === EXTENSION_PROPERTY_DELEGATE) { - if (descriptor.extensionReceiverParameter == null) { - throw RuntimeException("'$this' is not an extension property and thus getExtensionDelegate() " + - "is not going to work, use getDelegate() instead") - } + try { + if (receiver === EXTENSION_PROPERTY_DELEGATE) { + if (descriptor.extensionReceiverParameter == null) { + throw RuntimeException( + "'$this' is not an extension property and thus getExtensionDelegate() " + + "is not going to work, use getDelegate() instead" + ) } - field?.get(receiver) - } - catch (e: IllegalAccessException) { - throw IllegalPropertyDelegateAccessException(e) } + field?.get(receiver) + } catch (e: IllegalAccessException) { + throw IllegalPropertyDelegateAccessException(e) + } - override abstract val getter: Getter + abstract override val getter: Getter - private val descriptor_ = ReflectProperties.lazySoft(descriptorInitialValue) { + private val _descriptor = ReflectProperties.lazySoft(descriptorInitialValue) { container.findPropertyDescriptor(name, signature) } - override val descriptor: PropertyDescriptor get() = descriptor_() + override val descriptor: PropertyDescriptor get() = _descriptor() override val caller: FunctionCaller<*> get() = getter.caller @@ -121,13 +120,13 @@ internal abstract class KPropertyImpl private constructor( } override fun hashCode(): Int = - (container.hashCode() * 31 + name.hashCode()) * 31 + signature.hashCode() + (container.hashCode() * 31 + name.hashCode()) * 31 + signature.hashCode() override fun toString(): String = - ReflectionObjectRenderer.renderProperty(descriptor) + ReflectionObjectRenderer.renderProperty(descriptor) abstract class Accessor : - KCallableImpl(), KProperty.Accessor, KFunction { + KCallableImpl(), KProperty.Accessor, KFunction { abstract override val property: KPropertyImpl abstract override val descriptor: PropertyAccessorDescriptor @@ -185,14 +184,14 @@ private fun KPropertyImpl.Accessor<*, *>.computeCallerForAccessor(isGetter: Bool fun isInsideClassCompanionObject(): Boolean { val possibleCompanionObject = property.descriptor.containingDeclaration return DescriptorUtils.isCompanionObject(possibleCompanionObject) && - !DescriptorUtils.isInterface(possibleCompanionObject.containingDeclaration) + !DescriptorUtils.isInterface(possibleCompanionObject.containingDeclaration) } fun isJvmStaticProperty() = - property.descriptor.annotations.findAnnotation(JVM_STATIC) != null + property.descriptor.annotations.findAnnotation(JVM_STATIC) != null fun isNotNullProperty() = - !TypeUtils.isNullableType(property.descriptor.type) + !TypeUtils.isNullableType(property.descriptor.type) fun computeFieldCaller(field: Field): FunctionCaller = when { isInsideClassCompanionObject() -> { @@ -235,16 +234,16 @@ private fun KPropertyImpl.Accessor<*, *>.computeCallerForAccessor(isGetter: Bool val accessor = accessorSignature?.let { signature -> property.container.findMethodBySignature( - jvmSignature.nameResolver.getString(signature.name), - jvmSignature.nameResolver.getString(signature.desc), - descriptor.isPublicInBytecode + jvmSignature.nameResolver.getString(signature.name), + jvmSignature.nameResolver.getString(signature.desc), + descriptor.isPublicInBytecode ) } when { accessor == null -> computeFieldCaller( - property.javaField - ?: throw KotlinReflectionInternalError("No accessors or field is found for property $property") + property.javaField + ?: throw KotlinReflectionInternalError("No accessors or field is found for property $property") ) !Modifier.isStatic(accessor.modifiers) -> if (isBound) FunctionCaller.BoundInstanceMethod(accessor, property.boundReceiver) @@ -262,10 +261,10 @@ private fun KPropertyImpl.Accessor<*, *>.computeCallerForAccessor(isGetter: Bool } is JavaMethodProperty -> { val method = - if (isGetter) jvmSignature.getterMethod - else jvmSignature.setterMethod ?: throw KotlinReflectionInternalError( - "No source found for setter of Java method property: ${jvmSignature.getterMethod}" - ) + if (isGetter) jvmSignature.getterMethod + else jvmSignature.setterMethod ?: throw KotlinReflectionInternalError( + "No source found for setter of Java method property: ${jvmSignature.getterMethod}" + ) if (isBound) FunctionCaller.BoundInstanceMethod(method, property.boundReceiver) else FunctionCaller.InstanceMethod(method) } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KTypeImpl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KTypeImpl.kt index 55aa91f89e6..a477a0ef6f8 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KTypeImpl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KTypeImpl.kt @@ -36,8 +36,8 @@ import kotlin.reflect.jvm.internal.structure.primitiveByWrapper import kotlin.reflect.jvm.jvmErasure internal class KTypeImpl( - val type: KotlinType, - computeJavaType: () -> Type + val type: KotlinType, + computeJavaType: () -> Type ) : KType { internal val javaType: Type by ReflectProperties.lazySoft(computeJavaType) @@ -52,8 +52,8 @@ internal class KTypeImpl( // There may be no argument if it's a primitive array (such as IntArray) val argument = type.arguments.singleOrNull()?.type ?: return KClassImpl(jClass) val elementClassifier = - convert(argument) - ?: throw KotlinReflectionInternalError("Cannot determine classifier for array element type: $this") + convert(argument) + ?: throw KotlinReflectionInternalError("Cannot determine classifier for array element type: $this") return KClassImpl(elementClassifier.jvmErasure.java.createArrayType()) } @@ -69,7 +69,7 @@ internal class KTypeImpl( } } - override val arguments: List by ReflectProperties.lazySoft arguments@ { + override val arguments: List by ReflectProperties.lazySoft arguments@{ val typeArguments = type.arguments if (typeArguments.isEmpty()) return@arguments emptyList() @@ -78,8 +78,7 @@ internal class KTypeImpl( typeArguments.mapIndexed { i, typeProjection -> if (typeProjection.isStarProjection) { KTypeProjection.STAR - } - else { + } else { val type = KTypeImpl(typeProjection.type) { val javaType = javaType when (javaType) { @@ -114,11 +113,11 @@ internal class KTypeImpl( get() = type.isMarkedNullable override fun equals(other: Any?) = - other is KTypeImpl && type == other.type + other is KTypeImpl && type == other.type override fun hashCode() = - type.hashCode() + type.hashCode() override fun toString() = - ReflectionObjectRenderer.renderType(type) + ReflectionObjectRenderer.renderType(type) } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KTypeParameterImpl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KTypeParameterImpl.kt index 56e1f50c539..e9795712ecd 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KTypeParameterImpl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KTypeParameterImpl.kt @@ -45,11 +45,11 @@ internal class KTypeParameterImpl(override val descriptor: TypeParameterDescript get() = descriptor.isReified override fun equals(other: Any?) = - other is KTypeParameterImpl && descriptor == other.descriptor + other is KTypeParameterImpl && descriptor == other.descriptor override fun hashCode() = - descriptor.hashCode() + descriptor.hashCode() override fun toString() = - ReflectionObjectRenderer.renderTypeParameter(descriptor) + ReflectionObjectRenderer.renderTypeParameter(descriptor) } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/ReflectProperties.java b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/ReflectProperties.java index 9eacc7f47b1..78eb274343b 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/ReflectProperties.java +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/ReflectProperties.java @@ -21,7 +21,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.ref.SoftReference; -import java.lang.ref.WeakReference; public class ReflectProperties { public static abstract class Val { @@ -97,33 +96,6 @@ public class ReflectProperties { } } - // A delegate for a lazy property on a weak reference, whose initializer may be invoked multiple times - // including simultaneously from different threads - public static class LazyWeakVal extends Val { - private final Function0 initializer; - private WeakReference value = null; - - public LazyWeakVal(@NotNull Function0 initializer) { - this.initializer = initializer; - } - - @Override - public T invoke() { - WeakReference cached = value; - if (cached != null) { - Object result = cached.get(); - if (result != null) { - return unescape(result); - } - } - - T result = initializer.invoke(); - value = new WeakReference(escape(result)); - - return result; - } - } - @NotNull public static LazyVal lazy(@NotNull Function0 initializer) { return new LazyVal(initializer); @@ -138,9 +110,4 @@ public class ReflectProperties { public static LazySoftVal lazySoft(@NotNull Function0 initializer) { return lazySoft(null, initializer); } - - @NotNull - public static LazyWeakVal lazyWeak(@NotNull Function0 initializer) { - return new LazyWeakVal(initializer); - } } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/ReflectionObjectRenderer.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/ReflectionObjectRenderer.kt index 0389f86ec85..434343a29e1 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/ReflectionObjectRenderer.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/ReflectionObjectRenderer.kt @@ -44,7 +44,7 @@ internal object ReflectionObjectRenderer { if (addParentheses) append(")") } - fun renderCallable(descriptor: CallableDescriptor): String { + private fun renderCallable(descriptor: CallableDescriptor): String { return when (descriptor) { is PropertyDescriptor -> renderProperty(descriptor) is FunctionDescriptor -> renderFunction(descriptor) @@ -108,7 +108,8 @@ internal object ReflectionObjectRenderer { fun renderTypeParameter(typeParameter: TypeParameterDescriptor): String { return buildString { when (typeParameter.variance) { - Variance.INVARIANT -> {} + Variance.INVARIANT -> { + } Variance.IN_VARIANCE -> append("in ") Variance.OUT_VARIANCE -> append("out ") } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/RuntimeTypeMapper.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/RuntimeTypeMapper.kt index f299ceac082..e037659241c 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/RuntimeTypeMapper.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/RuntimeTypeMapper.kt @@ -76,7 +76,7 @@ internal sealed class JvmFunctionSignature { class JavaConstructor(val constructor: Constructor<*>) : JvmFunctionSignature() { override fun asString(): String = - constructor.parameterTypes.joinToString(separator = "", prefix = "(", postfix = ")V") { it.desc } + constructor.parameterTypes.joinToString(separator = "", prefix = "(", postfix = ")V") { it.desc } } class FakeJavaAnnotationConstructor(val jClass: Class<*>) : JvmFunctionSignature() { @@ -84,7 +84,7 @@ internal sealed class JvmFunctionSignature { val methods = jClass.declaredMethods.sortedBy { it.name } override fun asString(): String = - methods.joinToString(separator = "", prefix = "(", postfix = ")V") { it.returnType.desc } + methods.joinToString(separator = "", prefix = "(", postfix = ")V") { it.returnType.desc } } open class BuiltInFunction(private val signature: String) : JvmFunctionSignature() { @@ -92,7 +92,7 @@ internal sealed class JvmFunctionSignature { override fun asString(): String = signature - class Predefined(signature: String, private val member: Member): BuiltInFunction(signature) { + class Predefined(signature: String, private val member: Member) : BuiltInFunction(signature) { override fun getMember(container: KDeclarationContainerImpl): Member = member } } @@ -106,19 +106,18 @@ internal sealed class JvmPropertySignature { abstract fun asString(): String class KotlinProperty( - val descriptor: PropertyDescriptor, - val proto: ProtoBuf.Property, - val signature: JvmProtoBuf.JvmPropertySignature, - val nameResolver: NameResolver, - val typeTable: TypeTable + val descriptor: PropertyDescriptor, + val proto: ProtoBuf.Property, + val signature: JvmProtoBuf.JvmPropertySignature, + val nameResolver: NameResolver, + val typeTable: TypeTable ) : JvmPropertySignature() { private val string: String = if (signature.hasGetter()) { nameResolver.getString(signature.getter.name) + nameResolver.getString(signature.getter.desc) - } - else { + } else { val (name, desc) = - JvmProtoBufUtil.getJvmFieldSignature(proto, nameResolver, typeTable) ?: - throw KotlinReflectionInternalError("No field signature for property: $descriptor") + JvmProtoBufUtil.getJvmFieldSignature(proto, nameResolver, typeTable) + ?: throw KotlinReflectionInternalError("No field signature for property: $descriptor") JvmAbi.getterName(name) + getManglingSuffix() + "()" + desc } @@ -149,9 +148,7 @@ internal sealed class JvmPropertySignature { class JavaField(val field: Field) : JvmPropertySignature() { override fun asString(): String = - JvmAbi.getterName(field.name) + - "()" + - field.type.desc + JvmAbi.getterName(field.name) + "()" + field.type.desc } } @@ -186,12 +183,13 @@ internal object RuntimeTypeMapper { } } // If it's a deserialized function but has no JVM signature, it must be from built-ins - throw KotlinReflectionInternalError("Reflection on built-in Kotlin types is not yet fully supported. " + - "No metadata found for $function") + throw KotlinReflectionInternalError( + "Reflection on built-in Kotlin types is not yet fully supported. No metadata found for $function" + ) } is JavaMethodDescriptor -> { - val method = ((function.source as? JavaSourceElement)?.javaElement as? ReflectJavaMethod)?.member ?: - throw KotlinReflectionInternalError("Incorrect resolution sequence for Java method $function") + val method = ((function.source as? JavaSourceElement)?.javaElement as? ReflectJavaMethod)?.member + ?: throw KotlinReflectionInternalError("Incorrect resolution sequence for Java method $function") return JvmFunctionSignature.JavaMethod(method) } @@ -226,8 +224,8 @@ internal object RuntimeTypeMapper { when (element) { is ReflectJavaField -> JvmPropertySignature.JavaField(element.member) is ReflectJavaMethod -> JvmPropertySignature.JavaMethodProperty( - element.member, - ((property.setter?.source as? JavaSourceElement)?.javaElement as? ReflectJavaMethod)?.member + element.member, + ((property.setter?.source as? JavaSourceElement)?.javaElement as? ReflectJavaMethod)?.member ) else -> throw KotlinReflectionInternalError("Incorrect resolution sequence for Java field $property (source = $element)") } @@ -243,16 +241,22 @@ internal object RuntimeTypeMapper { when (function.name.asString()) { "equals" -> if (parameters.size == 1 && KotlinBuiltIns.isNullableAny(parameters.single().type)) { - return JvmFunctionSignature.BuiltInFunction.Predefined("equals(Ljava/lang/Object;)Z", - Any::class.java.getDeclaredMethod("equals", Any::class.java)) + return JvmFunctionSignature.BuiltInFunction.Predefined( + "equals(Ljava/lang/Object;)Z", + Any::class.java.getDeclaredMethod("equals", Any::class.java) + ) } "hashCode" -> if (parameters.isEmpty()) { - return JvmFunctionSignature.BuiltInFunction.Predefined("hashCode()I", - Any::class.java.getDeclaredMethod("hashCode")) + return JvmFunctionSignature.BuiltInFunction.Predefined( + "hashCode()I", + Any::class.java.getDeclaredMethod("hashCode") + ) } "toString" -> if (parameters.isEmpty()) { - return JvmFunctionSignature.BuiltInFunction.Predefined("toString()Ljava/lang/String;", - Any::class.java.getDeclaredMethod("toString")) + return JvmFunctionSignature.BuiltInFunction.Predefined( + "toString()Ljava/lang/String;", + Any::class.java.getDeclaredMethod("toString") + ) } // TODO: generalize and support other functions from built-ins } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/kClassCache.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/kClassCache.kt index 1cf079ad016..e173619e2fd 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/kClassCache.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/kClassCache.kt @@ -36,8 +36,7 @@ internal fun getOrCreateKotlinClass(jClass: Class): KClassImpl { if (kClass?.jClass == jClass) { return kClass } - } - else if (cached != null) { + } else if (cached != null) { // If the cached value is not a weak reference, it's an array of weak references @Suppress("UNCHECKED_CAST") (cached as Array>>) diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/moduleByClassLoader.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/moduleByClassLoader.kt index 203518c55f2..3f457471aa2 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/moduleByClassLoader.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/moduleByClassLoader.kt @@ -35,13 +35,13 @@ private class WeakClassLoaderBox(classLoader: ClassLoader) { var temporaryStrongRef: ClassLoader? = classLoader override fun equals(other: Any?) = - other is WeakClassLoaderBox && ref.get() === other.ref.get() + other is WeakClassLoaderBox && ref.get() === other.ref.get() override fun hashCode() = - identityHashCode + identityHashCode override fun toString() = - ref.get()?.toString() ?: "" + ref.get()?.toString() ?: "" } internal fun Class<*>.getOrCreateModule(): RuntimeModuleData { @@ -58,15 +58,13 @@ internal fun Class<*>.getOrCreateModule(): RuntimeModuleData { val module = RuntimeModuleData.create(classLoader) try { while (true) { - val ref = moduleByClassLoader.putIfAbsent(key, WeakReference(module)) - if (ref == null) return module + val ref = moduleByClassLoader.putIfAbsent(key, WeakReference(module)) ?: return module val result = ref.get() if (result != null) return result moduleByClassLoader.remove(key, ref) } - } - finally { + } finally { key.temporaryStrongRef = null } } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/util.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/util.kt index 59f83ff6bca..2999096a609 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/util.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/util.kt @@ -91,43 +91,40 @@ internal fun loadClass(classLoader: ClassLoader, packageName: String, className: } internal fun Visibility.toKVisibility(): KVisibility? = - when (this) { - Visibilities.PUBLIC -> KVisibility.PUBLIC - Visibilities.PROTECTED -> KVisibility.PROTECTED - Visibilities.INTERNAL -> KVisibility.INTERNAL - Visibilities.PRIVATE, Visibilities.PRIVATE_TO_THIS -> KVisibility.PRIVATE - else -> null - } + when (this) { + Visibilities.PUBLIC -> KVisibility.PUBLIC + Visibilities.PROTECTED -> KVisibility.PROTECTED + Visibilities.INTERNAL -> KVisibility.INTERNAL + Visibilities.PRIVATE, Visibilities.PRIVATE_TO_THIS -> KVisibility.PRIVATE + else -> null + } internal fun Annotated.computeAnnotations(): List = - annotations.mapNotNull { - val source = it.source - when (source) { - is ReflectAnnotationSource -> source.annotation - is RuntimeSourceElementFactory.RuntimeSourceElement -> (source.javaElement as? ReflectJavaAnnotation)?.annotation - else -> null - } + annotations.mapNotNull { + val source = it.source + when (source) { + is ReflectAnnotationSource -> source.annotation + is RuntimeSourceElementFactory.RuntimeSourceElement -> (source.javaElement as? ReflectJavaAnnotation)?.annotation + else -> null } + } // TODO: wrap other exceptions internal inline fun reflectionCall(block: () -> R): R = - try { - block() - } - catch (e: IllegalAccessException) { - throw IllegalCallableAccessException(e) - } + try { + block() + } catch (e: IllegalAccessException) { + throw IllegalCallableAccessException(e) + } internal fun Any?.asKFunctionImpl(): KFunctionImpl? = - this as? KFunctionImpl ?: - (this as? FunctionReference)?.compute() as? KFunctionImpl + this as? KFunctionImpl ?: (this as? FunctionReference)?.compute() as? KFunctionImpl internal fun Any?.asKPropertyImpl(): KPropertyImpl<*>? = - this as? KPropertyImpl<*> ?: - (this as? PropertyReference)?.compute() as? KPropertyImpl + this as? KPropertyImpl<*> ?: (this as? PropertyReference)?.compute() as? KPropertyImpl internal fun Any?.asKCallableImpl(): KCallableImpl<*>? = - this as? KCallableImpl<*> ?: asKFunctionImpl() ?: asKPropertyImpl() + this as? KCallableImpl<*> ?: asKFunctionImpl() ?: asKPropertyImpl() internal val ReflectKotlinClass.packageModuleName: String? get() { @@ -157,11 +154,11 @@ internal val CallableMemberDescriptor.isPublicInBytecode: Boolean } internal fun deserializeToDescriptor( - moduleAnchor: Class<*>, - proto: M, - nameResolver: NameResolver, - typeTable: TypeTable, - createDescriptor: MemberDeserializer.(M) -> D + moduleAnchor: Class<*>, + proto: M, + nameResolver: NameResolver, + typeTable: TypeTable, + createDescriptor: MemberDeserializer.(M) -> D ): D? { val moduleData = moduleAnchor.getOrCreateModule() @@ -172,8 +169,8 @@ internal fun deserializeToDescriptor( } val context = DeserializationContext( - moduleData.deserialization, nameResolver, moduleData.module, typeTable, VersionRequirementTable.EMPTY, - containerSource = null, parentTypeDeserializer = null, typeParameters = typeParameters + moduleData.deserialization, nameResolver, moduleData.module, typeTable, VersionRequirementTable.EMPTY, + containerSource = null, parentTypeDeserializer = null, typeParameters = typeParameters ) return MemberDeserializer(context).createDescriptor(proto) } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/reflectLambda.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/reflectLambda.kt index 4ac907cbb94..fd93e666a40 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/reflectLambda.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/reflectLambda.kt @@ -37,7 +37,7 @@ fun Function.reflect(): KFunction? { val (nameResolver, proto) = JvmProtoBufUtil.readFunctionDataFrom(data, annotation.d2) val descriptor = deserializeToDescriptor(javaClass, proto, nameResolver, TypeTable(proto.typeTable), MemberDeserializer::loadFunction) - ?: return null + ?: return null @Suppress("UNCHECKED_CAST") return KFunctionImpl(EmptyContainerForLocal, descriptor) as KFunction