Reformat module reflection.jvm, fix inspections/warnings

This commit is contained in:
Alexander Udalov
2018-06-28 18:43:17 +02:00
parent 25ee67a644
commit a7c80f2df1
27 changed files with 450 additions and 473 deletions
@@ -15,6 +15,7 @@
*/ */
@file:JvmName("KCallablesJvm") @file:JvmName("KCallablesJvm")
package kotlin.reflect.jvm package kotlin.reflect.jvm
import java.lang.reflect.AccessibleObject import java.lang.reflect.AccessibleObject
@@ -15,6 +15,7 @@
*/ */
@file:JvmName("KClassesJvm") @file:JvmName("KClassesJvm")
package kotlin.reflect.jvm package kotlin.reflect.jvm
import kotlin.reflect.KClass import kotlin.reflect.KClass
@@ -26,6 +27,4 @@ import kotlin.reflect.jvm.internal.KClassImpl
* @see [java.lang.Class.getName] * @see [java.lang.Class.getName]
*/ */
val KClass<*>.jvmName: String val KClass<*>.jvmName: String
get() { get() = (this as KClassImpl).jClass.name
return (this as KClassImpl).jClass.name
}
@@ -15,14 +15,18 @@
*/ */
@file:JvmName("KTypesJvm") @file:JvmName("KTypesJvm")
package kotlin.reflect.jvm package kotlin.reflect.jvm
import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind.ANNOTATION_CLASS import org.jetbrains.kotlin.descriptors.ClassKind.ANNOTATION_CLASS
import org.jetbrains.kotlin.descriptors.ClassKind.INTERFACE import org.jetbrains.kotlin.descriptors.ClassKind.INTERFACE
import kotlin.reflect.* import kotlin.reflect.KClass
import kotlin.reflect.jvm.internal.KotlinReflectionInternalError import kotlin.reflect.KClassifier
import kotlin.reflect.KType
import kotlin.reflect.KTypeParameter
import kotlin.reflect.jvm.internal.KTypeImpl 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. * Returns the [KClass] instance representing the runtime class to which this type is erased to on JVM.
@@ -15,11 +15,11 @@
*/ */
@file:JvmName("ReflectJvmMapping") @file:JvmName("ReflectJvmMapping")
package kotlin.reflect.jvm package kotlin.reflect.jvm
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import java.lang.reflect.* import java.lang.reflect.*
import java.util.*
import kotlin.reflect.* import kotlin.reflect.*
import kotlin.reflect.full.companionObject import kotlin.reflect.full.companionObject
import kotlin.reflect.full.functions import kotlin.reflect.full.functions
@@ -65,7 +65,8 @@ val KFunction<*>.javaMethod: Method?
* Returns a Java [Constructor] instance corresponding to the given Kotlin function, * 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]. * or `null` if this function is not a constructor or cannot be represented by a Java [Constructor].
*/ */
@Suppress("UNCHECKED_CAST") val <T> KFunction<T>.javaConstructor: Constructor<T>? @Suppress("UNCHECKED_CAST")
val <T> KFunction<T>.javaConstructor: Constructor<T>?
get() = this.asKCallableImpl()?.caller?.member as? Constructor<T> get() = this.asKCallableImpl()?.caller?.member as? Constructor<T>
@@ -78,7 +79,6 @@ val KType.javaType: Type
get() = (this as KTypeImpl).javaType get() = (this as KTypeImpl).javaType
// Java reflection -> Kotlin reflection // Java reflection -> Kotlin reflection
/** /**
@@ -129,7 +129,7 @@ val Method.kotlinFunction: KFunction<*>?
companion.functions.firstOrNull { companion.functions.firstOrNull {
val m = it.javaMethod val m = it.javaMethod
m != null && m.name == this.name && 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 } }?.let { return it }
} }
} }
@@ -163,7 +163,7 @@ private fun createAnnotationInstance(annotationClass: Class<*>, methods: List<Re
} }
} }
return Proxy.newProxyInstance(annotationClass.classLoader, arrayOf(annotationClass)) { proxy, method, args -> return Proxy.newProxyInstance(annotationClass.classLoader, arrayOf(annotationClass)) { _, method, args ->
val name = method.name val name = method.name
when (name) { when (name) {
"annotationType" -> annotationClass "annotationType" -> annotationClass
@@ -39,7 +39,6 @@ internal object EmptyContainerForLocal : KDeclarationContainerImpl() {
override fun getLocalProperty(index: Int): PropertyDescriptor? = null override fun getLocalProperty(index: Int): PropertyDescriptor? = null
private fun fail(): Nothing = throw KotlinReflectionInternalError( private fun fail(): Nothing = throw KotlinReflectionInternalError(
"Introspecting local functions, lambdas, anonymous functions and local variables " + "Introspecting local functions, lambdas, anonymous functions and local variables is not yet fully supported in Kotlin reflection"
"is not yet fully supported in Kotlin reflection"
) )
} }
@@ -30,8 +30,7 @@ internal abstract class FunctionCaller<out M : Member?>(
valueParameterTypes: Array<Type> valueParameterTypes: Array<Type>
) { ) {
val parameterTypes: List<Type> = val parameterTypes: List<Type> =
instanceClass?.let { listOf(it, *valueParameterTypes) } ?: instanceClass?.let { listOf(it, *valueParameterTypes) } ?: valueParameterTypes.toList()
valueParameterTypes.toList()
val arity: Int val arity: Int
get() = parameterTypes.size get() = parameterTypes.size
@@ -124,24 +123,23 @@ internal abstract class FunctionCaller<out M : Member?>(
} }
} }
class BoundStaticMethod(method: ReflectMethod, private val boundReceiver: Any?) : class BoundStaticMethod(method: ReflectMethod, private val boundReceiver: Any?) : Method(
Method(method, requiresInstance = false, parameterTypes = method.genericParameterTypes.dropFirst()) { method, requiresInstance = false, parameterTypes = method.genericParameterTypes.dropFirst()
) {
override fun call(args: Array<*>): Any? { override fun call(args: Array<*>): Any? {
checkArguments(args) checkArguments(args)
return callMethod(null, argsWithReceiver(boundReceiver, args)) return callMethod(null, argsWithReceiver(boundReceiver, args))
} }
} }
class BoundInstanceMethod(method: ReflectMethod, private val boundReceiver: Any?) : class BoundInstanceMethod(method: ReflectMethod, private val boundReceiver: Any?) : Method(method, requiresInstance = false) {
Method(method, requiresInstance = false) {
override fun call(args: Array<*>): Any? { override fun call(args: Array<*>): Any? {
checkArguments(args) checkArguments(args)
return callMethod(boundReceiver, args) return callMethod(boundReceiver, args)
} }
} }
class BoundJvmStaticInObject(method: ReflectMethod) : class BoundJvmStaticInObject(method: ReflectMethod) : Method(method, requiresInstance = false) {
Method(method, requiresInstance = false) {
override fun call(args: Array<*>): Any? { override fun call(args: Array<*>): Any? {
checkArguments(args) checkArguments(args)
return callMethod(null, args) return callMethod(null, args)
@@ -199,16 +197,18 @@ internal abstract class FunctionCaller<out M : Member?>(
} }
} }
class ClassCompanionFieldGetter(field: ReflectField, klass: Class<*>) : class ClassCompanionFieldGetter(field: ReflectField, klass: Class<*>) : FunctionCaller<ReflectField>(
FunctionCaller<ReflectField>(field, field.genericType, klass, emptyArray()) { field, field.genericType, klass, emptyArray()
) {
override fun call(args: Array<*>): Any? { override fun call(args: Array<*>): Any? {
checkArguments(args) checkArguments(args)
return member.get(args.first()) return member.get(args.first())
} }
} }
class BoundInstanceFieldGetter(field: ReflectField, private val boundReceiver: Any?) : class BoundInstanceFieldGetter(field: ReflectField, private val boundReceiver: Any?) : FieldGetter(
FieldGetter(field, requiresInstance = false) { field, requiresInstance = false
) {
override fun call(args: Array<*>): Any? { override fun call(args: Array<*>): Any? {
checkArguments(args) checkArguments(args)
return member.get(boundReceiver) return member.get(boundReceiver)
@@ -217,8 +217,9 @@ internal abstract class FunctionCaller<out M : Member?>(
class BoundJvmStaticInObjectFieldGetter(field: ReflectField) : FieldGetter(field, requiresInstance = false) class BoundJvmStaticInObjectFieldGetter(field: ReflectField) : FieldGetter(field, requiresInstance = false)
class BoundClassCompanionFieldGetter(field: ReflectField, private val boundReceiver: Any?) : class BoundClassCompanionFieldGetter(field: ReflectField, private val boundReceiver: Any?) : FieldGetter(
FieldGetter(field, requiresInstance = false) { field, requiresInstance = false
) {
override fun call(args: Array<*>): Any? { override fun call(args: Array<*>): Any? {
checkArguments(args) checkArguments(args)
return member.get(boundReceiver) return member.get(boundReceiver)
@@ -236,32 +237,36 @@ internal abstract class FunctionCaller<out M : Member?>(
} }
} }
class ClassCompanionFieldSetter(field: ReflectField, klass: Class<*>) : class ClassCompanionFieldSetter(field: ReflectField, klass: Class<*>) : FunctionCaller<ReflectField>(
FunctionCaller<ReflectField>(field, Void.TYPE, klass, arrayOf(field.genericType)) { field, Void.TYPE, klass, arrayOf(field.genericType)
) {
override fun call(args: Array<*>): Any? { override fun call(args: Array<*>): Any? {
checkArguments(args) checkArguments(args)
return member.set(null, args.last()) return member.set(null, args.last())
} }
} }
class BoundInstanceFieldSetter(field: ReflectField, notNull: Boolean, private val boundReceiver: Any?) : class BoundInstanceFieldSetter(field: ReflectField, notNull: Boolean, private val boundReceiver: Any?) : FieldSetter(
FieldSetter(field, notNull, false) { field, notNull, false
) {
override fun call(args: Array<*>): Any? { override fun call(args: Array<*>): Any? {
checkArguments(args) checkArguments(args)
return member.set(boundReceiver, args.first()) return member.set(boundReceiver, args.first())
} }
} }
class BoundJvmStaticInObjectFieldSetter(field: ReflectField, notNull: Boolean) : class BoundJvmStaticInObjectFieldSetter(field: ReflectField, notNull: Boolean) : FieldSetter(
FieldSetter(field, notNull, requiresInstance = false) { field, notNull, requiresInstance = false
) {
override fun call(args: Array<*>): Any? { override fun call(args: Array<*>): Any? {
checkArguments(args) checkArguments(args)
return member.set(null, args.last()) return member.set(null, args.last())
} }
} }
class BoundClassCompanionFieldSetter(field: ReflectField, klass: Class<*>) : class BoundClassCompanionFieldSetter(field: ReflectField, klass: Class<*>) : FunctionCaller<ReflectField>(
FunctionCaller<ReflectField>(field, Void.TYPE, klass, arrayOf(field.genericType)) { field, Void.TYPE, klass, arrayOf(field.genericType)
) {
override fun call(args: Array<*>): Any? { override fun call(args: Array<*>): Any? {
checkArguments(args) checkArguments(args)
return member.set(null, args.last()) return member.set(null, args.last())
@@ -284,7 +289,7 @@ internal abstract class FunctionCaller<out M : Member?>(
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
inline fun <reified T> Array<out T>.dropFirst(): Array<T> = inline fun <reified T> Array<out T>.dropFirst(): Array<T> =
if (size <= 1) emptyArray<T>() else copyOfRange(1, size) as Array<T> if (size <= 1) emptyArray() else copyOfRange(1, size) as Array<T>
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
fun Array<*>.dropFirstArg(): Array<Any?> = fun Array<*>.dropFirstArg(): Array<Any?> =
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor
import java.lang.reflect.Type import java.lang.reflect.Type
import java.util.* import java.util.*
import kotlin.reflect.* import kotlin.reflect.*
import kotlin.reflect.jvm.internal.KotlinReflectionInternalError
import kotlin.reflect.jvm.javaType import kotlin.reflect.jvm.javaType
internal abstract class KCallableImpl<out R> : KCallable<R> { internal abstract class KCallableImpl<out R> : KCallable<R> {
@@ -38,11 +37,11 @@ internal abstract class KCallableImpl<out R> : KCallable<R> {
abstract val isBound: Boolean abstract val isBound: Boolean
private val annotations_ = ReflectProperties.lazySoft { descriptor.computeAnnotations() } private val _annotations = ReflectProperties.lazySoft { descriptor.computeAnnotations() }
override val annotations: List<Annotation> get() = annotations_() override val annotations: List<Annotation> get() = _annotations()
private val parameters_ = ReflectProperties.lazySoft { private val _parameters = ReflectProperties.lazySoft {
val descriptor = descriptor val descriptor = descriptor
val result = ArrayList<KParameter>() val result = ArrayList<KParameter>()
var index = 0 var index = 0
@@ -71,21 +70,21 @@ internal abstract class KCallableImpl<out R> : KCallable<R> {
} }
override val parameters: List<KParameter> override val parameters: List<KParameter>
get() = parameters_() get() = _parameters()
private val returnType_ = ReflectProperties.lazySoft { private val _returnType = ReflectProperties.lazySoft {
KTypeImpl(descriptor.returnType!!) { caller.returnType } KTypeImpl(descriptor.returnType!!) { caller.returnType }
} }
override val returnType: KType override val returnType: KType
get() = returnType_() get() = _returnType()
private val typeParameters_ = ReflectProperties.lazySoft { private val _typeParameters = ReflectProperties.lazySoft {
descriptor.typeParameters.map(::KTypeParameterImpl) descriptor.typeParameters.map(::KTypeParameterImpl)
} }
override val typeParameters: List<KTypeParameter> override val typeParameters: List<KTypeParameter>
get() = typeParameters_() get() = _typeParameters()
override val visibility: KVisibility? override val visibility: KVisibility?
get() = descriptor.visibility.toKVisibility() get() = descriptor.visibility.toKVisibility()
@@ -197,6 +196,5 @@ internal abstract class KCallableImpl<out R> : KCallable<R> {
Void.TYPE -> throw IllegalStateException("Parameter with void type is illegal") Void.TYPE -> throw IllegalStateException("Parameter with void type is illegal")
else -> throw UnsupportedOperationException("Unknown primitive: $type") else -> throw UnsupportedOperationException("Unknown primitive: $type")
} }
} } else null
else null
} }
@@ -94,8 +94,8 @@ internal class KClassImpl<T : Any>(override val jClass: Class<T>) : KDeclaration
} }
val nestedClasses: Collection<KClass<*>> by ReflectProperties.lazySoft { val nestedClasses: Collection<KClass<*>> by ReflectProperties.lazySoft {
descriptor.unsubstitutedInnerClassesScope.getContributedDescriptors().filterNot(DescriptorUtils::isEnumEntry).mapNotNull { descriptor.unsubstitutedInnerClassesScope.getContributedDescriptors().filterNot(DescriptorUtils::isEnumEntry)
nestedClass -> .mapNotNull { nestedClass ->
val jClass = (nestedClass as ClassDescriptor).toJavaClass() val jClass = (nestedClass as ClassDescriptor).toJavaClass()
jClass?.let { KClassImpl(it) } jClass?.let { KClassImpl(it) }
} }
@@ -108,8 +108,7 @@ internal class KClassImpl<T : Any>(override val jClass: Class<T>) : KDeclaration
val field = if (descriptor.isCompanionObject && !CompanionObjectMapping.isMappedIntrinsicCompanionObject(descriptor)) { val field = if (descriptor.isCompanionObject && !CompanionObjectMapping.isMappedIntrinsicCompanionObject(descriptor)) {
jClass.enclosingClass.getDeclaredField(descriptor.name.asString()) jClass.enclosingClass.getDeclaredField(descriptor.name.asString())
} } else {
else {
jClass.getDeclaredField(JvmAbi.INSTANCE_FIELD) jClass.getDeclaredField(JvmAbi.INSTANCE_FIELD)
} }
field.get(null) as T field.get(null) as T
@@ -132,8 +131,7 @@ internal class KClassImpl<T : Any>(override val jClass: Class<T>) : KDeclaration
if (jClass.superclass == superJavaClass) { if (jClass.superclass == superJavaClass) {
jClass.genericSuperclass jClass.genericSuperclass
} } else {
else {
val index = jClass.interfaces.indexOf(superJavaClass) val index = jClass.interfaces.indexOf(superJavaClass)
if (index < 0) throw KotlinReflectionInternalError("No superclass of $this in Java reflection for $superClass") if (index < 0) throw KotlinReflectionInternalError("No superclass of $this in Java reflection for $superClass")
jClass.genericInterfaces[index] jClass.genericInterfaces[index]
@@ -151,11 +149,11 @@ internal class KClassImpl<T : Any>(override val jClass: Class<T>) : KDeclaration
val declaredNonStaticMembers: Collection<KCallableImpl<*>> val declaredNonStaticMembers: Collection<KCallableImpl<*>>
by ReflectProperties.lazySoft { getMembers(memberScope, DECLARED) } by ReflectProperties.lazySoft { getMembers(memberScope, DECLARED) }
val declaredStaticMembers: Collection<KCallableImpl<*>> private val declaredStaticMembers: Collection<KCallableImpl<*>>
by ReflectProperties.lazySoft { getMembers(staticScope, DECLARED) } by ReflectProperties.lazySoft { getMembers(staticScope, DECLARED) }
val inheritedNonStaticMembers: Collection<KCallableImpl<*>> private val inheritedNonStaticMembers: Collection<KCallableImpl<*>>
by ReflectProperties.lazySoft { getMembers(memberScope, INHERITED) } by ReflectProperties.lazySoft { getMembers(memberScope, INHERITED) }
val inheritedStaticMembers: Collection<KCallableImpl<*>> private val inheritedStaticMembers: Collection<KCallableImpl<*>>
by ReflectProperties.lazySoft { getMembers(staticScope, INHERITED) } by ReflectProperties.lazySoft { getMembers(staticScope, INHERITED) }
val allNonStaticMembers: Collection<KCallableImpl<*>> val allNonStaticMembers: Collection<KCallableImpl<*>>
@@ -62,9 +62,8 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain
return scope.getContributedDescriptors().mapNotNull { descriptor -> return scope.getContributedDescriptors().mapNotNull { descriptor ->
if (descriptor is CallableMemberDescriptor && if (descriptor is CallableMemberDescriptor &&
descriptor.visibility != Visibilities.INVISIBLE_FAKE && descriptor.visibility != Visibilities.INVISIBLE_FAKE &&
belonginess.accept(descriptor)) belonginess.accept(descriptor)
descriptor.accept(visitor, Unit) ) descriptor.accept(visitor, Unit) else null
else null
}.toList() }.toList()
} }
@@ -191,11 +190,10 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain
allMethods.firstOrNull { method -> allMethods.firstOrNull { method ->
method.name == name && method.name == name &&
method.returnType == returnType && method.returnType == returnType &&
method.parameterTypes.contentEquals(parameterTypes) method.parameterTypes!!.contentEquals(parameterTypes)
} }
} }
} } catch (e: NoSuchMethodException) {
catch (e: NoSuchMethodException) {
null null
} }
@@ -203,8 +201,7 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain
try { try {
if (declared) getDeclaredConstructor(*parameterTypes.toTypedArray()) if (declared) getDeclaredConstructor(*parameterTypes.toTypedArray())
else getConstructor(*parameterTypes.toTypedArray()) else getConstructor(*parameterTypes.toTypedArray())
} } catch (e: NoSuchMethodException) {
catch (e: NoSuchMethodException) {
null null
} }
@@ -56,7 +56,7 @@ internal class KFunctionImpl private constructor(
override val name: String get() = descriptor.name.asString() 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 jvmSignature = RuntimeTypeMapper.mapSignature(descriptor)
val member: Member? = when (jvmSignature) { val member: Member? = when (jvmSignature) {
is KotlinConstructor -> { 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 jvmSignature = RuntimeTypeMapper.mapSignature(descriptor)
val member: Member? = when (jvmSignature) { val member: Member? = when (jvmSignature) {
is KotlinFunction -> { is KotlinFunction -> {
container.findDefaultMethod(jvmSignature.methodName, jvmSignature.methodDesc, container.findDefaultMethod(
!Modifier.isStatic(caller.member!!.modifiers), descriptor.isPublicInBytecode) jvmSignature.methodName, jvmSignature.methodDesc,
!Modifier.isStatic(caller.member!!.modifiers), descriptor.isPublicInBytecode
)
} }
is KotlinConstructor -> { is KotlinConstructor -> {
if (isAnnotationConstructor) if (isAnnotationConstructor)
@@ -58,8 +58,7 @@ internal class KPackageImpl(
// The default value for 'xs' is empty string, as declared in kotlin.Metadata // The default value for 'xs' is empty string, as declared in kotlin.Metadata
if (facadeName != null && facadeName.isNotEmpty()) { if (facadeName != null && facadeName.isNotEmpty()) {
jClass.classLoader.loadClass(facadeName.replace('/', '.')) jClass.classLoader.loadClass(facadeName.replace('/', '.'))
} } else {
else {
jClass jClass
} }
} }
@@ -70,8 +69,7 @@ internal class KPackageImpl(
val strings = header.strings val strings = header.strings
if (data != null && strings != null) { if (data != null && strings != null) {
JvmProtoBufUtil.readPackageDataFrom(data, strings) JvmProtoBufUtil.readPackageDataFrom(data, strings)
} } else null
else null
} }
} }
@@ -32,7 +32,8 @@ internal class KParameterImpl(
override val annotations: List<Annotation> by ReflectProperties.lazySoft { descriptor.computeAnnotations() } override val annotations: List<Annotation> by ReflectProperties.lazySoft { descriptor.computeAnnotations() }
override val name: String? get() { override val name: String?
get() {
val valueParameter = descriptor as? ValueParameterDescriptor ?: return null val valueParameter = descriptor as? ValueParameterDescriptor ?: return null
if (valueParameter.containingDeclaration.hasSynthesizedParameterNames()) return null if (valueParameter.containingDeclaration.hasSynthesizedParameterNames()) return null
val name = valueParameter.name val name = valueParameter.name
@@ -24,11 +24,13 @@ import kotlin.reflect.KProperty0
internal open class KProperty0Impl<out R> : KProperty0<R>, KPropertyImpl<R> { internal open class KProperty0Impl<out R> : KProperty0<R>, KPropertyImpl<R> {
constructor(container: KDeclarationContainerImpl, descriptor: PropertyDescriptor) : super(container, descriptor) 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<R> get() = getter_() override val getter: Getter<R> get() = _getter()
override fun get(): R = getter.call() override fun get(): R = getter.call()
@@ -46,11 +48,13 @@ internal open class KProperty0Impl<out R> : KProperty0<R>, KPropertyImpl<R> {
internal class KMutableProperty0Impl<R> : KProperty0Impl<R>, KMutableProperty0<R> { internal class KMutableProperty0Impl<R> : KProperty0Impl<R>, KMutableProperty0<R> {
constructor(container: KDeclarationContainerImpl, descriptor: PropertyDescriptor) : super(container, descriptor) 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<R> get() = setter_() override val setter: Setter<R> get() = _setter()
override fun set(value: R) = setter.call(value) override fun set(value: R) = setter.call(value)
@@ -22,13 +22,15 @@ import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KProperty1 import kotlin.reflect.KProperty1
internal open class KProperty1Impl<T, out R> : KProperty1<T, R>, KPropertyImpl<R> { internal open class KProperty1Impl<T, out R> : KProperty1<T, R>, KPropertyImpl<R> {
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) 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<T, R> get() = getter_() override val getter: Getter<T, R> get() = _getter()
override fun get(receiver: T): R = getter.call(receiver) override fun get(receiver: T): R = getter.call(receiver)
@@ -44,13 +46,15 @@ internal open class KProperty1Impl<T, out R> : KProperty1<T, R>, KPropertyImpl<R
} }
internal class KMutableProperty1Impl<T, R> : KProperty1Impl<T, R>, KMutableProperty1<T, R> { internal class KMutableProperty1Impl<T, R> : KProperty1Impl<T, R>, KMutableProperty1<T, R> {
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) 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<T, R> get() = setter_() override val setter: Setter<T, R> get() = _setter()
override fun set(receiver: T, value: R) = setter.call(receiver, value) override fun set(receiver: T, value: R) = setter.call(receiver, value)
@@ -23,13 +23,15 @@ import kotlin.reflect.KMutableProperty2
import kotlin.reflect.KProperty2 import kotlin.reflect.KProperty2
internal open class KProperty2Impl<D, E, out R> : KProperty2<D, E, R>, KPropertyImpl<R> { internal open class KProperty2Impl<D, E, out R> : KProperty2<D, E, R>, KPropertyImpl<R> {
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) 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<D, E, R> get() = getter_() override val getter: Getter<D, E, R> get() = _getter()
override fun get(receiver1: D, receiver2: E): R = getter.call(receiver1, receiver2) override fun get(receiver1: D, receiver2: E): R = getter.call(receiver1, receiver2)
@@ -49,13 +51,14 @@ internal class KMutableProperty2Impl<D, E, R> : KProperty2Impl<D, E, R>, KMutabl
constructor(container: KDeclarationContainerImpl, descriptor: PropertyDescriptor) : super(container, descriptor) 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<D, E, R> get() = setter_() override val setter: Setter<D, E, R> get() = _setter()
override fun set(receiver1: D, receiver2: E, value: R) = setter.call(receiver1, receiver2, value) override fun set(receiver1: D, receiver2: E, value: R) = setter.call(receiver1, receiver2, value)
class Setter<D, E, R>(override val property: KMutableProperty2Impl<D, E, R>) : KPropertyImpl.Setter<R>(), KMutableProperty2.Setter<D, E, R> { class Setter<D, E, R>(override val property: KMutableProperty2Impl<D, E, R>) : KPropertyImpl.Setter<R>(),
KMutableProperty2.Setter<D, E, R> {
override fun invoke(receiver1: D, receiver2: E, value: R): Unit = property.set(receiver1, receiver2, value) override fun invoke(receiver1: D, receiver2: E, value: R): Unit = property.set(receiver1, receiver2, value)
} }
} }
@@ -53,7 +53,7 @@ internal abstract class KPropertyImpl<out R> private constructor(
override val isBound: Boolean get() = boundReceiver != 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) val jvmSignature = RuntimeTypeMapper.mapPropertySignature(descriptor)
when (jvmSignature) { when (jvmSignature) {
is KotlinProperty -> { is KotlinProperty -> {
@@ -61,16 +61,14 @@ internal abstract class KPropertyImpl<out R> private constructor(
JvmProtoBufUtil.getJvmFieldSignature(jvmSignature.proto, jvmSignature.nameResolver, jvmSignature.typeTable)?.let { JvmProtoBufUtil.getJvmFieldSignature(jvmSignature.proto, jvmSignature.nameResolver, jvmSignature.typeTable)?.let {
val owner = if (JvmAbi.isCompanionObjectWithBackingFieldsInOuter(descriptor.containingDeclaration)) { val owner = if (JvmAbi.isCompanionObjectWithBackingFieldsInOuter(descriptor.containingDeclaration)) {
container.jClass.enclosingClass container.jClass.enclosingClass
} } else descriptor.containingDeclaration.let { containingDeclaration ->
else descriptor.containingDeclaration.let { containingDeclaration ->
if (containingDeclaration is ClassDescriptor) containingDeclaration.toJavaClass() if (containingDeclaration is ClassDescriptor) containingDeclaration.toJavaClass()
else container.jClass else container.jClass
} }
try { try {
owner?.getDeclaredField(it.name) owner?.getDeclaredField(it.name)
} } catch (e: NoSuchFieldException) {
catch (e: NoSuchFieldException) {
null null
} }
} }
@@ -80,7 +78,7 @@ internal abstract class KPropertyImpl<out R> private constructor(
} }
} }
val javaField: Field? get() = javaField_() val javaField: Field? get() = _javaField()
protected fun computeDelegateField(): Field? = protected fun computeDelegateField(): Field? =
if (@Suppress("DEPRECATION") descriptor.isDelegated) javaField else null if (@Suppress("DEPRECATION") descriptor.isDelegated) javaField else null
@@ -89,23 +87,24 @@ internal abstract class KPropertyImpl<out R> private constructor(
try { try {
if (receiver === EXTENSION_PROPERTY_DELEGATE) { if (receiver === EXTENSION_PROPERTY_DELEGATE) {
if (descriptor.extensionReceiverParameter == null) { if (descriptor.extensionReceiverParameter == null) {
throw RuntimeException("'$this' is not an extension property and thus getExtensionDelegate() " + throw RuntimeException(
"is not going to work, use getDelegate() instead") "'$this' is not an extension property and thus getExtensionDelegate() " +
"is not going to work, use getDelegate() instead"
)
} }
} }
field?.get(receiver) field?.get(receiver)
} } catch (e: IllegalAccessException) {
catch (e: IllegalAccessException) {
throw IllegalPropertyDelegateAccessException(e) throw IllegalPropertyDelegateAccessException(e)
} }
override abstract val getter: Getter<R> abstract override val getter: Getter<R>
private val descriptor_ = ReflectProperties.lazySoft(descriptorInitialValue) { private val _descriptor = ReflectProperties.lazySoft(descriptorInitialValue) {
container.findPropertyDescriptor(name, signature) container.findPropertyDescriptor(name, signature)
} }
override val descriptor: PropertyDescriptor get() = descriptor_() override val descriptor: PropertyDescriptor get() = _descriptor()
override val caller: FunctionCaller<*> get() = getter.caller override val caller: FunctionCaller<*> get() = getter.caller
@@ -69,7 +69,7 @@ internal class KTypeImpl(
} }
} }
override val arguments: List<KTypeProjection> by ReflectProperties.lazySoft arguments@ { override val arguments: List<KTypeProjection> by ReflectProperties.lazySoft arguments@{
val typeArguments = type.arguments val typeArguments = type.arguments
if (typeArguments.isEmpty()) return@arguments emptyList<KTypeProjection>() if (typeArguments.isEmpty()) return@arguments emptyList<KTypeProjection>()
@@ -78,8 +78,7 @@ internal class KTypeImpl(
typeArguments.mapIndexed { i, typeProjection -> typeArguments.mapIndexed { i, typeProjection ->
if (typeProjection.isStarProjection) { if (typeProjection.isStarProjection) {
KTypeProjection.STAR KTypeProjection.STAR
} } else {
else {
val type = KTypeImpl(typeProjection.type) { val type = KTypeImpl(typeProjection.type) {
val javaType = javaType val javaType = javaType
when (javaType) { when (javaType) {
@@ -21,7 +21,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.lang.ref.SoftReference; import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
public class ReflectProperties { public class ReflectProperties {
public static abstract class Val<T> { public static abstract class Val<T> {
@@ -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<T> extends Val<T> {
private final Function0<T> initializer;
private WeakReference<Object> value = null;
public LazyWeakVal(@NotNull Function0<T> initializer) {
this.initializer = initializer;
}
@Override
public T invoke() {
WeakReference<Object> cached = value;
if (cached != null) {
Object result = cached.get();
if (result != null) {
return unescape(result);
}
}
T result = initializer.invoke();
value = new WeakReference<Object>(escape(result));
return result;
}
}
@NotNull @NotNull
public static <T> LazyVal<T> lazy(@NotNull Function0<T> initializer) { public static <T> LazyVal<T> lazy(@NotNull Function0<T> initializer) {
return new LazyVal<T>(initializer); return new LazyVal<T>(initializer);
@@ -138,9 +110,4 @@ public class ReflectProperties {
public static <T> LazySoftVal<T> lazySoft(@NotNull Function0<T> initializer) { public static <T> LazySoftVal<T> lazySoft(@NotNull Function0<T> initializer) {
return lazySoft(null, initializer); return lazySoft(null, initializer);
} }
@NotNull
public static <T> LazyWeakVal<T> lazyWeak(@NotNull Function0<T> initializer) {
return new LazyWeakVal<T>(initializer);
}
} }
@@ -44,7 +44,7 @@ internal object ReflectionObjectRenderer {
if (addParentheses) append(")") if (addParentheses) append(")")
} }
fun renderCallable(descriptor: CallableDescriptor): String { private fun renderCallable(descriptor: CallableDescriptor): String {
return when (descriptor) { return when (descriptor) {
is PropertyDescriptor -> renderProperty(descriptor) is PropertyDescriptor -> renderProperty(descriptor)
is FunctionDescriptor -> renderFunction(descriptor) is FunctionDescriptor -> renderFunction(descriptor)
@@ -108,7 +108,8 @@ internal object ReflectionObjectRenderer {
fun renderTypeParameter(typeParameter: TypeParameterDescriptor): String { fun renderTypeParameter(typeParameter: TypeParameterDescriptor): String {
return buildString { return buildString {
when (typeParameter.variance) { when (typeParameter.variance) {
Variance.INVARIANT -> {} Variance.INVARIANT -> {
}
Variance.IN_VARIANCE -> append("in ") Variance.IN_VARIANCE -> append("in ")
Variance.OUT_VARIANCE -> append("out ") Variance.OUT_VARIANCE -> append("out ")
} }
@@ -92,7 +92,7 @@ internal sealed class JvmFunctionSignature {
override fun asString(): String = signature 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 override fun getMember(container: KDeclarationContainerImpl): Member = member
} }
} }
@@ -114,11 +114,10 @@ internal sealed class JvmPropertySignature {
) : JvmPropertySignature() { ) : JvmPropertySignature() {
private val string: String = if (signature.hasGetter()) { private val string: String = if (signature.hasGetter()) {
nameResolver.getString(signature.getter.name) + nameResolver.getString(signature.getter.desc) nameResolver.getString(signature.getter.name) + nameResolver.getString(signature.getter.desc)
} } else {
else {
val (name, desc) = val (name, desc) =
JvmProtoBufUtil.getJvmFieldSignature(proto, nameResolver, typeTable) ?: JvmProtoBufUtil.getJvmFieldSignature(proto, nameResolver, typeTable)
throw KotlinReflectionInternalError("No field signature for property: $descriptor") ?: throw KotlinReflectionInternalError("No field signature for property: $descriptor")
JvmAbi.getterName(name) + getManglingSuffix() + "()" + desc JvmAbi.getterName(name) + getManglingSuffix() + "()" + desc
} }
@@ -149,9 +148,7 @@ internal sealed class JvmPropertySignature {
class JavaField(val field: Field) : JvmPropertySignature() { class JavaField(val field: Field) : JvmPropertySignature() {
override fun asString(): String = override fun asString(): String =
JvmAbi.getterName(field.name) + JvmAbi.getterName(field.name) + "()" + field.type.desc
"()" +
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 // 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. " + throw KotlinReflectionInternalError(
"No metadata found for $function") "Reflection on built-in Kotlin types is not yet fully supported. No metadata found for $function"
)
} }
is JavaMethodDescriptor -> { is JavaMethodDescriptor -> {
val method = ((function.source as? JavaSourceElement)?.javaElement as? ReflectJavaMethod)?.member ?: val method = ((function.source as? JavaSourceElement)?.javaElement as? ReflectJavaMethod)?.member
throw KotlinReflectionInternalError("Incorrect resolution sequence for Java method $function") ?: throw KotlinReflectionInternalError("Incorrect resolution sequence for Java method $function")
return JvmFunctionSignature.JavaMethod(method) return JvmFunctionSignature.JavaMethod(method)
} }
@@ -243,16 +241,22 @@ internal object RuntimeTypeMapper {
when (function.name.asString()) { when (function.name.asString()) {
"equals" -> if (parameters.size == 1 && KotlinBuiltIns.isNullableAny(parameters.single().type)) { "equals" -> if (parameters.size == 1 && KotlinBuiltIns.isNullableAny(parameters.single().type)) {
return JvmFunctionSignature.BuiltInFunction.Predefined("equals(Ljava/lang/Object;)Z", return JvmFunctionSignature.BuiltInFunction.Predefined(
Any::class.java.getDeclaredMethod("equals", Any::class.java)) "equals(Ljava/lang/Object;)Z",
Any::class.java.getDeclaredMethod("equals", Any::class.java)
)
} }
"hashCode" -> if (parameters.isEmpty()) { "hashCode" -> if (parameters.isEmpty()) {
return JvmFunctionSignature.BuiltInFunction.Predefined("hashCode()I", return JvmFunctionSignature.BuiltInFunction.Predefined(
Any::class.java.getDeclaredMethod("hashCode")) "hashCode()I",
Any::class.java.getDeclaredMethod("hashCode")
)
} }
"toString" -> if (parameters.isEmpty()) { "toString" -> if (parameters.isEmpty()) {
return JvmFunctionSignature.BuiltInFunction.Predefined("toString()Ljava/lang/String;", return JvmFunctionSignature.BuiltInFunction.Predefined(
Any::class.java.getDeclaredMethod("toString")) "toString()Ljava/lang/String;",
Any::class.java.getDeclaredMethod("toString")
)
} }
// TODO: generalize and support other functions from built-ins // TODO: generalize and support other functions from built-ins
} }
@@ -36,8 +36,7 @@ internal fun <T : Any> getOrCreateKotlinClass(jClass: Class<T>): KClassImpl<T> {
if (kClass?.jClass == jClass) { if (kClass?.jClass == jClass) {
return kClass 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 // If the cached value is not a weak reference, it's an array of weak references
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
(cached as Array<WeakReference<KClassImpl<T>>>) (cached as Array<WeakReference<KClassImpl<T>>>)
@@ -58,15 +58,13 @@ internal fun Class<*>.getOrCreateModule(): RuntimeModuleData {
val module = RuntimeModuleData.create(classLoader) val module = RuntimeModuleData.create(classLoader)
try { try {
while (true) { while (true) {
val ref = moduleByClassLoader.putIfAbsent(key, WeakReference(module)) val ref = moduleByClassLoader.putIfAbsent(key, WeakReference(module)) ?: return module
if (ref == null) return module
val result = ref.get() val result = ref.get()
if (result != null) return result if (result != null) return result
moduleByClassLoader.remove(key, ref) moduleByClassLoader.remove(key, ref)
} }
} } finally {
finally {
key.temporaryStrongRef = null key.temporaryStrongRef = null
} }
} }
@@ -113,18 +113,15 @@ internal fun Annotated.computeAnnotations(): List<Annotation> =
internal inline fun <R> reflectionCall(block: () -> R): R = internal inline fun <R> reflectionCall(block: () -> R): R =
try { try {
block() block()
} } catch (e: IllegalAccessException) {
catch (e: IllegalAccessException) {
throw IllegalCallableAccessException(e) throw IllegalCallableAccessException(e)
} }
internal fun Any?.asKFunctionImpl(): KFunctionImpl? = internal fun Any?.asKFunctionImpl(): KFunctionImpl? =
this as? KFunctionImpl ?: this as? KFunctionImpl ?: (this as? FunctionReference)?.compute() as? KFunctionImpl
(this as? FunctionReference)?.compute() as? KFunctionImpl
internal fun Any?.asKPropertyImpl(): KPropertyImpl<*>? = internal fun Any?.asKPropertyImpl(): KPropertyImpl<*>? =
this as? KPropertyImpl<*> ?: this as? KPropertyImpl<*> ?: (this as? PropertyReference)?.compute() as? KPropertyImpl
(this as? PropertyReference)?.compute() as? KPropertyImpl
internal fun Any?.asKCallableImpl(): KCallableImpl<*>? = internal fun Any?.asKCallableImpl(): KCallableImpl<*>? =
this as? KCallableImpl<*> ?: asKFunctionImpl() ?: asKPropertyImpl() this as? KCallableImpl<*> ?: asKFunctionImpl() ?: asKPropertyImpl()