Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

SONARKT-552 Migrate DelegationPatternCheck to kotlin-analysis-api #566

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Issues disappeared from the Kotlin compiler are related to the fact, that we only pass Kotlin files to the analysis and don't provide classpath.

The issues disappear because for some parameters we can't resolve types (receive KaErrorType) and that's why we can't guarantee that there was a match of method signatures. The types that are unresolved are represented by classes written in Java (for example KtExpression).

So far I think we can accept this change as this is related to the analysis misconfiguration and not the rule behavior.

Copy link
Contributor

@leveretka leveretka Feb 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously an empty String was returned as a fully qualified name of an Error type. Since "" is equal to "", the issue appeared by accident and by accident those issues happened to be TP.

Before we introduced generation of Binding context in all cases, these issues weren't triggered as types weren't resolved at all.

"kotlin-kotlin-project:sources/kotlin/kotlin/compiler/backend/src/org/jetbrains/kotlin/codegen/range/ReversedRangeValue.kt": [
26
"kotlin-kotlin-project:sources/kotlin/kotlin/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/repl/AggregatedReplState.kt": [
95
],
"kotlin-kotlin-project:sources/kotlin/kotlin/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/repl/GenericReplCompilingEvaluator.kt": [
77,
Expand All @@ -11,10 +11,6 @@
30,
32,
34,
37,
39,
44,
46,
48
],
"kotlin-kotlin-project:sources/kotlin/kotlin/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/repl/GenericReplCompiler.kt": [
Expand All @@ -24,16 +20,7 @@
36
],
"kotlin-kotlin-project:sources/kotlin/kotlin/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilderAdapter.kt": [
33,
37,
40,
43,
45,
48,
55,
58,
65,
73,
79,
81,
83,
Expand All @@ -43,23 +30,12 @@
99,
103,
107,
111,
115,
117,
119,
121,
123,
127,
134,
138,
142,
146,
155,
159,
163,
166,
176,
180,
184,
188,
192,
Expand All @@ -73,44 +49,27 @@
],
"kotlin-kotlin-project:sources/kotlin/kotlin/compiler/frontend/src/org/jetbrains/kotlin/descriptors/annotations/AnnotationSplitter.kt": [
133,
134,
135,
136,
137,
138
],
"kotlin-kotlin-project:sources/kotlin/kotlin/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/context/ResolutionResultsCache.kt": [
69
],
"kotlin-kotlin-project:sources/kotlin/kotlin/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/InvokeProcessors.kt": [
47,
165
],
"kotlin-kotlin-project:sources/kotlin/kotlin/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/utils/ScopeUtils.kt": [
153,
155,
157
],
"kotlin-kotlin-project:sources/kotlin/kotlin/core/descriptors/src/org/jetbrains/kotlin/descriptors/annotations/AnnotationsImpl.kt": [
47
],
"kotlin-kotlin-project:sources/kotlin/kotlin/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/AbstractScopeAdapter.kt": [
56,
57,
58,
60
58
],
"kotlin-kotlin-project:sources/kotlin/kotlin/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/InnerClassesScopeWrapper.kt": [
43,
44,
45,
47
45
],
"kotlin-kotlin-project:sources/kotlin/kotlin/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/SubstitutingScope.kt": [
82,
83,
84,
86
84
],
"kotlin-kotlin-project:sources/kotlin/kotlin/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedAnnotations.kt": [
38
Expand All @@ -124,15 +83,23 @@
107
],
"kotlin-kotlin-project:sources/kotlin/kotlin/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/IdeaModuleInfos.kt": [
443,
450
443
],
"kotlin-kotlin-project:sources/kotlin/kotlin/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/output/InlayScratchOutputHandler.kt": [
45
],
"kotlin-kotlin-project:sources/kotlin/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/baseTransformations.kt": [
140
],
"kotlin-kotlin-project:sources/kotlin/kotlin/libraries/stdlib/js/src/kotlin/collections/HashMap.kt": [
30
],
"kotlin-kotlin-project:sources/kotlin/kotlin/libraries/stdlib/js/src/kotlin/collections/LinkedHashMap.kt": [
202
],
"kotlin-kotlin-project:sources/kotlin/kotlin/libraries/stdlib/src/kotlin/collections/Iterators.kt": [
39
],
"kotlin-kotlin-project:sources/kotlin/kotlin/libraries/stdlib/src/kotlin/collections/MapWithDefault.kt": [
72,
73,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
"kotlin-okio-project:sources/kotlin/okio/okio/jvm/src/main/java/okio/InflaterSource.kt": [
111
],
"kotlin-okio-project:sources/kotlin/okio/okio/jvm/src/main/java/okio/Okio.kt": [
78,
80,
113
],
"kotlin-okio-project:sources/kotlin/okio/okio/jvm/src/main/java/okio/RealBufferedSink.kt": [
250
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@
package org.sonarsource.kotlin.checks

import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes
import org.jetbrains.kotlin.js.descriptorUtils.getKotlinTypeFqName
import org.jetbrains.kotlin.analysis.api.symbols.KaClassKind
import org.jetbrains.kotlin.analysis.api.symbols.KaClassSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KaFunctionSymbol
import org.jetbrains.kotlin.analysis.api.symbols.name
import org.jetbrains.kotlin.analysis.api.types.KaType
import org.jetbrains.kotlin.analysis.api.types.KaTypeParameterType
import org.jetbrains.kotlin.analysis.api.types.symbol
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtClassOrObject
Expand All @@ -31,29 +35,20 @@ import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.psiUtil.getCallNameExpression
import org.jetbrains.kotlin.psi.psiUtil.isPublic
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isInterface
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.sonar.check.Rule
import org.sonarsource.kotlin.api.checks.AbstractCheck
import org.sonarsource.kotlin.api.checks.allPaired
import org.sonarsource.kotlin.api.checks.determineType
import org.sonarsource.kotlin.api.checks.determineTypeAsString
import org.sonarsource.kotlin.api.checks.overrides
import org.sonarsource.kotlin.api.checks.returnType
import org.sonarsource.kotlin.api.checks.returnTypeAsString
import org.sonarsource.kotlin.api.frontend.KotlinFileContext
import org.sonarsource.kotlin.api.visiting.withKaSession

@org.sonarsource.kotlin.api.frontend.K1only
@Rule(key = "S6514")
class DelegationPatternCheck : AbstractCheck() {

override fun visitClassOrObject(classOrObject: KtClassOrObject, context: KotlinFileContext) {
val classType = classOrObject.determineType(context.bindingContext) ?: return
if (classType.isInterface()) return
val superInterfaces = getSuperInterfaces(classType).toSet()
override fun visitClassOrObject(classOrObject: KtClassOrObject, context: KotlinFileContext) = withKaSession {
val classSymbol = classOrObject.classSymbol ?: return
if (classSymbol.classKind == KaClassKind.INTERFACE) return
val superInterfaces: Set<KaClassSymbol> = classSymbol.getSuperInterfaces()
if (superInterfaces.isEmpty()) return

classOrObject.declarations.forEach {
Expand All @@ -63,60 +58,75 @@ class DelegationPatternCheck : AbstractCheck() {
}
}

private fun checkNamedFunction(function: KtNamedFunction, superInterfaces: Set<KotlinType>, context: KotlinFileContext) {
private fun checkNamedFunction(function: KtNamedFunction, superInterfaces: Set<KaClassSymbol>, context: KotlinFileContext) = withKaSession {
if (!(function.isPublic && function.overrides())) return
val bindingContext = context.bindingContext
val delegeeType = getDelegeeOrNull(function, bindingContext)?.determineType(bindingContext) ?: return
val delegeeType = getDelegeeOrNull(function)?.expressionType ?: return

if (getCommonSuperInterfaces(superInterfaces, delegeeType).any {
isFunctionInInterface(function, it, bindingContext)
isFunctionInInterface(function, it)
}) {
context.reportIssue(function.nameIdentifier!!, """Replace with interface delegation using "by" in the class header.""")
}
}
}

private fun isFunctionInInterface(function: KtNamedFunction, superInterface: KotlinType, bindingContext: BindingContext): Boolean {
val classDescriptor = TypeUtils.getClassDescriptor(superInterface) as? ClassDescriptorWithResolutionScopes ?: return false
return classDescriptor.declaredCallableMembers.any {
isEqualFunctionSignature(function, it, bindingContext)
private fun isFunctionInInterface(function: KtNamedFunction, superInterface: KaClassSymbol): Boolean = withKaSession {
superInterface.declaredMemberScope.declarations.any {
it is KaFunctionSymbol && haveCompatibleFunctionSignature(it, function.symbol)
}
}

private fun isEqualFunctionSignature(
function: KtNamedFunction,
functionDescriptor: CallableMemberDescriptor,
bindingContext: BindingContext,
) = function.name == functionDescriptor.name.identifier &&
function.returnTypeAsString(bindingContext) == functionDescriptor.returnType?.getKotlinTypeFqName(false) &&
function.valueParameters.allPaired(functionDescriptor.valueParameters) { parameter, paramerterDescriptor ->
parameter.typeReference?.determineTypeAsString(bindingContext) == paramerterDescriptor.type.getKotlinTypeFqName(false)
}
private fun haveCompatibleFunctionSignature(
function1: KaFunctionSymbol,
function2: KaFunctionSymbol,
) = withKaSession {
function1.returnType.sameOrTypeParam(function2.returnType) &&
function1.name == function2.name &&
function1.valueParameters.allPaired(function2.valueParameters) { p1, p2 ->
p1.returnType.sameOrTypeParam(p2.returnType)
}
}

fun KaType.sameOrTypeParam(other: KaType): Boolean = withKaSession {
if (this@sameOrTypeParam is KaTypeParameterType && other is KaTypeParameterType) return true
return symbol != null && other.symbol != null && symbol == other.symbol
}

fun getCommonSuperInterfaces(superInterfaces: Set<KotlinType>, otherType: KotlinType) =
getSuperInterfaces(otherType).intersect(superInterfaces)
fun getCommonSuperInterfaces(superInterfaces: Set<KaClassSymbol>, otherType: KaType) =
(otherType.symbol as? KaClassSymbol)?.let {
(it.getSuperInterfaces() + it).intersect(superInterfaces)
} ?: emptySet()

private fun getSuperInterfaces(kotlinType: KotlinType): List<KotlinType> =
kotlinType.supertypes().filter(KotlinType::isInterface).let {
if (kotlinType.isInterface()) it + kotlinType else it
}
fun KaType.getSuperInterfaces(): Set<KaClassSymbol> =
(symbol as? KaClassSymbol)?.getSuperInterfaces() ?: emptySet()

fun KaClassSymbol.getSuperInterfaces(): Set<KaClassSymbol> = withKaSession {
val superTypes = [email protected] { !it.isAnyType }
val symbols: Collection<KaClassSymbol> = superTypes.mapNotNull { it.symbol as? KaClassSymbol }
val hierarchy: List<KaClassSymbol> = superTypes.flatMap { it.getSuperInterfaces() }
return (symbols + hierarchy)
.filter { it.classKind == KaClassKind.INTERFACE }
.toSet()
}

private fun getDelegeeOrNull(function: KtNamedFunction, bindingContext: BindingContext): KtNameReferenceExpression? {
private fun getDelegeeOrNull(function: KtNamedFunction): KtNameReferenceExpression? = withKaSession {
val qualifiedCallExpression = getFunctionSingleBodyElementOrNull(function) as? KtDotQualifiedExpression ?: return null
val receiverExpression = qualifiedCallExpression.receiverExpression as? KtNameReferenceExpression ?: return null
val callExpression = qualifiedCallExpression.selectorExpression as? KtCallExpression ?: return null
val callExpressionType = callExpression.expressionType ?: return null

return if (function.name!! == callExpression.getCallNameExpression()?.getReferencedName() &&
function.returnType(bindingContext) == callExpression.determineType(bindingContext) &&
function.returnType.semanticallyEquals(callExpressionType) &&
function.valueParameters.allPaired(callExpression.valueArguments) { parameter, argument ->
isDelegatedParameter(parameter, argument, bindingContext)
isDelegatedParameter(parameter, argument)
}) receiverExpression else null
}

private fun isDelegatedParameter(parameter: KtParameter, arguments: KtValueArgument, bindingContext: BindingContext): Boolean {
private fun isDelegatedParameter(parameter: KtParameter, arguments: KtValueArgument): Boolean = withKaSession {
val argumentExpression = arguments.getArgumentExpression() as? KtNameReferenceExpression ?: return false
return parameter.name == argumentExpression.getReferencedName() &&
parameter.determineType(bindingContext) == argumentExpression.determineType(bindingContext)
if (parameter.name != argumentExpression.getReferencedName()) return false
val argumentType = argumentExpression.expressionType ?: return false
return parameter.symbol.returnType.semanticallyEquals(argumentType)
}

private fun getFunctionSingleBodyElementOrNull(function: KtNamedFunction): PsiElement? {
Expand Down