Refactoring: move common parts about SAMs to frontend module

This commit is contained in:
Mikhail Zarechenskiy
2019-11-18 13:49:14 +03:00
parent fc32e8b017
commit c93c82236c
14 changed files with 136 additions and 158 deletions
@@ -26,6 +26,7 @@ import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor;
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor;
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor;
import org.jetbrains.kotlin.load.java.sam.SingleAbstractMethodUtils;
import org.jetbrains.kotlin.load.kotlin.sam.SamConversionResolverImplKt;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.typeUtil.TypeUtilsKt;
@@ -78,7 +79,7 @@ public class SamType {
@NotNull
public SimpleFunctionDescriptor getOriginalAbstractMethod() {
return (SimpleFunctionDescriptor) SingleAbstractMethodUtils.getAbstractMembers(getClassDescriptor()).get(0);
return (SimpleFunctionDescriptor) SamConversionResolverImplKt.getAbstractMembers(getClassDescriptor()).get(0);
}
@Override
@@ -0,0 +1,18 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.load.java.sam
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.resolve.SamConversionResolver
import org.jetbrains.kotlin.types.SimpleType
object JavaBasedSamConversionResolver : SamConversionResolver {
override fun resolveFunctionTypeIfSamInterface(classDescriptor: ClassDescriptor): SimpleType? {
if (classDescriptor !is JavaClassDescriptor) return null
return classDescriptor.defaultFunctionTypeForSamInterface
}
}
@@ -1,45 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.load.java.sam
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.resolve.SamConversionResolver
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.types.SimpleType
class SamConversionResolverImpl(
storageManager: StorageManager,
private val samWithReceiverResolvers: Iterable<SamWithReceiverResolver>
): SamConversionResolver {
private val functionTypesForSamInterfaces = storageManager.createCacheWithNullableValues<ClassDescriptor, SimpleType>()
override fun resolveFunctionTypeIfSamInterface(classDescriptor: ClassDescriptor): SimpleType? {
return functionTypesForSamInterfaces.computeIfAbsent(classDescriptor) {
val abstractMethod = SingleAbstractMethodUtils.getSingleAbstractMethodOrNull(classDescriptor) ?: return@computeIfAbsent null
val shouldConvertFirstParameterToDescriptor = samWithReceiverResolvers.any { it.shouldConvertFirstSamParameterToReceiver(abstractMethod) }
SingleAbstractMethodUtils.getFunctionTypeForAbstractMethod(abstractMethod, shouldConvertFirstParameterToDescriptor)
}
}
}
object JavaBasedSamConversionResolver : SamConversionResolver {
override fun resolveFunctionTypeIfSamInterface(classDescriptor: ClassDescriptor): SimpleType? {
if (classDescriptor !is JavaClassDescriptor) return null
return classDescriptor.defaultFunctionTypeForSamInterface
}
}
@@ -1,23 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.load.java.sam
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
interface SamWithReceiverResolver {
fun shouldConvertFirstSamParameterToReceiver(function: FunctionDescriptor): Boolean
}
@@ -18,21 +18,18 @@ package org.jetbrains.kotlin.load.java.sam;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.FunctionTypesKt;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl;
import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl;
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl;
import org.jetbrains.kotlin.resolve.SamConversionResolver;
import org.jetbrains.kotlin.load.java.descriptors.JavaClassConstructorDescriptor;
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor;
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor;
import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaClassDescriptor;
import org.jetbrains.kotlin.load.kotlin.sam.SamConversionResolverImplKt;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.name.SpecialNames;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.resolve.SamConversionResolver;
import org.jetbrains.kotlin.resolve.jvm.JavaResolverUtils;
import org.jetbrains.kotlin.types.*;
@@ -47,17 +44,6 @@ public class SingleAbstractMethodUtils {
private SingleAbstractMethodUtils() {
}
@NotNull
public static List<CallableMemberDescriptor> getAbstractMembers(@NotNull ClassDescriptor classDescriptor) {
List<CallableMemberDescriptor> abstractMembers = new ArrayList<>();
for (DeclarationDescriptor member : DescriptorUtils.getAllDescriptors(classDescriptor.getUnsubstitutedMemberScope())) {
if (member instanceof CallableMemberDescriptor && ((CallableMemberDescriptor) member).getModality() == Modality.ABSTRACT) {
abstractMembers.add((CallableMemberDescriptor) member);
}
}
return abstractMembers;
}
@Nullable
public static KotlinType getFunctionTypeForSamType(@NotNull KotlinType samType, @NotNull SamConversionResolver samResolver) {
UnwrappedType unwrappedType = samType.unwrap();
@@ -103,75 +89,13 @@ public class SingleAbstractMethodUtils {
return null;
}
@NotNull
public static SimpleType getFunctionTypeForAbstractMethod(
@NotNull FunctionDescriptor function,
boolean shouldConvertFirstParameterToDescriptor
) {
KotlinType returnType = function.getReturnType();
assert returnType != null : "function is not initialized: " + function;
List<ValueParameterDescriptor> valueParameters = function.getValueParameters();
List<KotlinType> parameterTypes = new ArrayList<>(valueParameters.size());
List<Name> parameterNames = new ArrayList<>(valueParameters.size());
int startIndex = 0;
KotlinType receiverType = null;
if (shouldConvertFirstParameterToDescriptor && !function.getValueParameters().isEmpty()) {
receiverType = valueParameters.get(0).getType();
startIndex = 1;
}
for (int i = startIndex; i < valueParameters.size(); ++i) {
ValueParameterDescriptor parameter = valueParameters.get(i);
parameterTypes.add(parameter.getType());
parameterNames.add(function.hasSynthesizedParameterNames() ? SpecialNames.NO_NAME_PROVIDED : parameter.getName());
}
return FunctionTypesKt.createFunctionType(
DescriptorUtilsKt.getBuiltIns(function), Annotations.Companion.getEMPTY(),
receiverType, parameterTypes, parameterNames, returnType, function.isSuspend()
);
}
@Nullable
public static FunctionDescriptor getSingleAbstractMethodOrNull(@NotNull ClassDescriptor klass) {
// NB: this check MUST BE at start. Please do not touch until following to-do is resolved
// Otherwise android data binding can cause resolve re-entrance
// For details see KT-18687, KT-16149
// TODO: prevent resolve re-entrance on architecture level, or (alternatively) ask data binding owners not to do it
if (DescriptorUtilsKt.getFqNameSafe(klass).asString().endsWith(".databinding.DataBindingComponent")) {
return null;
}
if (klass instanceof JavaClassDescriptor) {
if (((JavaClassDescriptor) klass).isDefinitelyNotSamInterface()) {
return null;
}
} else if (!klass.isFun()) {
return null;
}
List<CallableMemberDescriptor> abstractMembers = getAbstractMembers(klass);
if (abstractMembers.size() == 1) {
CallableMemberDescriptor member = abstractMembers.get(0);
if (member instanceof SimpleFunctionDescriptor) {
return member.getTypeParameters().isEmpty()
? (FunctionDescriptor) member
: null;
}
}
return null;
}
@NotNull
public static SamConstructorDescriptor createSamConstructorFunction(
@NotNull DeclarationDescriptor owner,
@NotNull ClassDescriptor samInterface,
@NotNull SamConversionResolver samResolver
) {
assert getSingleAbstractMethodOrNull(samInterface) != null : samInterface;
assert SamConversionResolverImplKt.getSingleAbstractMethodOrNull(samInterface) != null : samInterface;
SamConstructorDescriptorImpl result = new SamConstructorDescriptorImpl(owner, samInterface);
@@ -235,9 +159,7 @@ public class SingleAbstractMethodUtils {
public static boolean isSamClassDescriptor(@NotNull ClassDescriptor descriptor) {
if (descriptor.isFun()) return true;
if (descriptor instanceof LazyJavaClassDescriptor &&
((LazyJavaClassDescriptor) descriptor).getDefaultFunctionTypeForSamInterface() != null
) return true;
if (descriptor instanceof LazyJavaClassDescriptor && descriptor.getDefaultFunctionTypeForSamInterface() != null) return true;
return false;
}
@@ -12,7 +12,7 @@ import org.jetbrains.kotlin.container.useImpl
import org.jetbrains.kotlin.container.useInstance
import org.jetbrains.kotlin.resolve.SamConversionResolver
import org.jetbrains.kotlin.load.java.sam.JvmSamConversionTransformer
import org.jetbrains.kotlin.load.java.sam.SamConversionResolverImpl
import org.jetbrains.kotlin.load.kotlin.sam.SamConversionResolverImpl
import org.jetbrains.kotlin.resolve.PlatformConfiguratorBase
import org.jetbrains.kotlin.resolve.checkers.BigFunctionTypeAvailabilityChecker
import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker
@@ -0,0 +1,88 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.load.kotlin.sam
import org.jetbrains.kotlin.builtins.createFunctionType
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations.Companion.EMPTY
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.SamConversionResolver
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
import java.util.*
class SamConversionResolverImpl(
storageManager: StorageManager,
private val samWithReceiverResolvers: Iterable<SamWithReceiverResolver>
): SamConversionResolver {
private val functionTypesForSamInterfaces = storageManager.createCacheWithNullableValues<ClassDescriptor, SimpleType>()
override fun resolveFunctionTypeIfSamInterface(classDescriptor: ClassDescriptor): SimpleType? {
return functionTypesForSamInterfaces.computeIfAbsent(classDescriptor) {
val abstractMethod = getSingleAbstractMethodOrNull(classDescriptor) ?: return@computeIfAbsent null
val shouldConvertFirstParameterToDescriptor = samWithReceiverResolvers.any { it.shouldConvertFirstSamParameterToReceiver(abstractMethod) }
getFunctionTypeForAbstractMethod(abstractMethod, shouldConvertFirstParameterToDescriptor)
}
}
}
fun getSingleAbstractMethodOrNull(klass: ClassDescriptor): FunctionDescriptor? {
// NB: this check MUST BE at start. Please do not touch until following to-do is resolved
// Otherwise android data binding can cause resolve re-entrance
// For details see KT-18687, KT-16149
// TODO: prevent resolve re-entrance on architecture level, or (alternatively) ask data binding owners not to do it
if (klass.fqNameSafe.asString().endsWith(".databinding.DataBindingComponent")) return null
if (klass.isDefinitelyNotSamInterface) return null
val abstractMember = getAbstractMembers(klass).singleOrNull() ?: return null
return if (abstractMember is SimpleFunctionDescriptor && abstractMember.typeParameters.isEmpty())
abstractMember
else
null
}
@Suppress("UNCHECKED_CAST")
fun getAbstractMembers(classDescriptor: ClassDescriptor): List<CallableMemberDescriptor> {
return DescriptorUtils
.getAllDescriptors(classDescriptor.unsubstitutedMemberScope)
.filter { it is CallableMemberDescriptor && it.modality == Modality.ABSTRACT } as List<CallableMemberDescriptor>
}
fun getFunctionTypeForAbstractMethod(
function: FunctionDescriptor,
shouldConvertFirstParameterToDescriptor: Boolean
): SimpleType {
val returnType = function.returnType ?: error("function is not initialized: $function")
val valueParameters = function.valueParameters
val parameterTypes = ArrayList<KotlinType>(valueParameters.size)
val parameterNames = ArrayList<Name>(valueParameters.size)
var startIndex = 0
var receiverType: KotlinType? = null
if (shouldConvertFirstParameterToDescriptor && function.valueParameters.isNotEmpty()) {
receiverType = valueParameters[0].type
startIndex = 1
}
for (i in startIndex until valueParameters.size) {
val parameter = valueParameters[i]
parameterTypes.add(parameter.type)
parameterNames.add(if (function.hasSynthesizedParameterNames()) SpecialNames.NO_NAME_PROVIDED else parameter.name)
}
return createFunctionType(
function.builtIns, EMPTY, receiverType, parameterTypes,
parameterNames, returnType, function.isSuspend
)
}
@@ -0,0 +1,12 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.load.kotlin.sam
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
interface SamWithReceiverResolver {
fun shouldConvertFirstSamParameterToReceiver(function: FunctionDescriptor): Boolean
}
@@ -18,6 +18,8 @@ import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.load.java.sam.SamAdapterDescriptor
import org.jetbrains.kotlin.load.java.sam.SamConstructorDescriptor
import org.jetbrains.kotlin.load.java.sam.SingleAbstractMethodUtils
import org.jetbrains.kotlin.load.kotlin.sam.getFunctionTypeForAbstractMethod
import org.jetbrains.kotlin.load.kotlin.sam.getSingleAbstractMethodOrNull
import org.jetbrains.kotlin.load.java.typeEnhancement.hasEnhancedNullability
import org.jetbrains.kotlin.load.kotlin.JvmPackagePartSource
import org.jetbrains.kotlin.psi2ir.generators.GeneratorExtensions
@@ -58,9 +60,9 @@ class JvmGeneratorExtensions(private val generateFacades: Boolean = true) : Gene
override fun getSubstitutedFunctionTypeForSamType(samType: KotlinType): KotlinType {
val descriptor = samType.constructor.declarationDescriptor as? JavaClassDescriptor
?: throw AssertionError("SAM should be represented by a Java class: $samType")
val singleAbstractMethod = SingleAbstractMethodUtils.getSingleAbstractMethodOrNull(descriptor)
val singleAbstractMethod = getSingleAbstractMethodOrNull(descriptor)
?: throw AssertionError("$descriptor should have a single abstract method")
val unsubstitutedFunctionType = SingleAbstractMethodUtils.getFunctionTypeForAbstractMethod(singleAbstractMethod, false)
val unsubstitutedFunctionType = getFunctionTypeForAbstractMethod(singleAbstractMethod, false)
return TypeSubstitutor.create(samType).substitute(unsubstitutedFunctionType, Variance.INVARIANT)
?: throw AssertionError("Failed to substitute function type $unsubstitutedFunctionType corresponding to $samType")
}
@@ -17,6 +17,7 @@ import org.jetbrains.kotlin.idea.decompiler.textBuilder.DeserializerForDecompile
import org.jetbrains.kotlin.idea.decompiler.textBuilder.LoggingErrorReporter
import org.jetbrains.kotlin.idea.decompiler.textBuilder.ResolveEverythingToKotlinAnyLocalClassifierResolver
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.load.kotlin.sam.SamConversionResolverImpl
import org.jetbrains.kotlin.load.java.structure.JavaClass
import org.jetbrains.kotlin.load.java.structure.classId
import org.jetbrains.kotlin.load.kotlin.*
@@ -43,6 +43,7 @@ import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.load.java.sam.SingleAbstractMethodUtils
import org.jetbrains.kotlin.load.kotlin.sam.getSingleAbstractMethodOrNull
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
@@ -763,7 +764,7 @@ class ExpressionsOfTypeProcessor(
testLog { "Resolved java class to descriptor: ${psiClass.qualifiedName}" }
val classDescriptor = psiClass.getJavaMemberDescriptor() as? JavaClassDescriptor
if (classDescriptor != null && SingleAbstractMethodUtils.getSingleAbstractMethodOrNull(classDescriptor) != null) {
if (classDescriptor != null && getSingleAbstractMethodOrNull(classDescriptor) != null) {
addSamInterfaceToProcess(psiClass)
return true
}
@@ -18,6 +18,7 @@ import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.load.java.sam.SingleAbstractMethodUtils
import org.jetbrains.kotlin.load.kotlin.sam.getSingleAbstractMethodOrNull
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
@@ -72,7 +73,7 @@ class SamConversionToAnonymousObjectIntention : SelfTargetingRangeIntention<KtCa
val type = getType(context) ?: return null
if (!SingleAbstractMethodUtils.isSamType(type)) return null
val javaClass = type.constructor.declarationDescriptor as? JavaClassDescriptor ?: return null
return SingleAbstractMethodUtils.getSingleAbstractMethodOrNull(javaClass)
return getSingleAbstractMethodOrNull(javaClass)
}
companion object {
@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.samWithReceiver
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.extensions.AnnotationBasedExtension
import org.jetbrains.kotlin.load.java.sam.SamWithReceiverResolver
import org.jetbrains.kotlin.load.kotlin.sam.SamWithReceiverResolver
import org.jetbrains.kotlin.psi.KtModifierListOwner
class SamWithReceiverResolverExtension(
@@ -30,7 +30,7 @@ import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.extensions.AnnotationBasedExtension
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor
import org.jetbrains.kotlin.load.java.sam.SamWithReceiverResolver
import org.jetbrains.kotlin.load.kotlin.sam.SamWithReceiverResolver
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.KtFile