summaryrefslogtreecommitdiff
path: root/plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/LambdaToAnonymousFunctionIntention.kt
blob: 733cdb26656d2e0126b2c74df24c422d94044dc1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package org.jetbrains.kotlin.idea.intentions

import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.moveInsideParentheses
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.error.ErrorType
import org.jetbrains.kotlin.types.isFlexible
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable

class LambdaToAnonymousFunctionIntention : SelfTargetingIntention<KtLambdaExpression>(
    KtLambdaExpression::class.java,
    KotlinBundle.lazyMessage("convert.to.anonymous.function"),
    KotlinBundle.lazyMessage("convert.lambda.expression.to.anonymous.function")
), LowPriorityAction {
    override fun isApplicableTo(element: KtLambdaExpression, caretOffset: Int): Boolean {
        val argument = element.getStrictParentOfType<KtValueArgument>()
        val call = argument?.getStrictParentOfType<KtCallElement>()
        if (call?.getStrictParentOfType<KtFunction>()?.hasModifier(KtTokens.INLINE_KEYWORD) == true) return false

        val context = element.analyze(BodyResolveMode.PARTIAL)
        if (call?.getResolvedCall(context)?.getParameterForArgument(argument)?.type?.isSuspendFunctionType == true) return false
        val descriptor = context[
                BindingContext.DECLARATION_TO_DESCRIPTOR,
                element.functionLiteral,
        ] as? AnonymousFunctionDescriptor ?: return false

        if (descriptor.valueParameters.any { it.isDestructuring() || it.type is ErrorType }) return false

        val lastElement = element.functionLiteral.arrow ?: element.functionLiteral.lBrace
        return caretOffset <= lastElement.endOffset
    }

    override fun applyTo(element: KtLambdaExpression, editor: Editor?) {
        val functionDescriptor = element.functionLiteral.descriptor as? AnonymousFunctionDescriptor ?: return
        val resultingFunction = convertLambdaToFunction(element, functionDescriptor) ?: return
        val argument = when (val parent = resultingFunction.parent) {
            is KtLambdaArgument -> parent
            is KtLabeledExpression -> parent.replace(resultingFunction).parent as? KtLambdaArgument
            else -> null
        } ?: return

        argument.moveInsideParentheses(argument.analyze(BodyResolveMode.PARTIAL))
    }

    private fun ValueParameterDescriptor.isDestructuring() = this is ValueParameterDescriptorImpl.WithDestructuringDeclaration

    companion object {
        fun convertLambdaToFunction(
            lambda: KtLambdaExpression,
            functionDescriptor: FunctionDescriptor,
            functionName: String = "",
            functionParameterName: (ValueParameterDescriptor, Int) -> String = { parameter, _ ->
                val parameterName = parameter.name
                if (parameterName.isSpecial) "_" else parameterName.asString().quoteIfNeeded()
            },
            typeParameters: Map<TypeConstructor, KotlinType> = emptyMap(),
            replaceElement: (KtNamedFunction) -> KtExpression = { lambda.replaced(it) }
        ): KtExpression? {
            val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES
            val functionLiteral = lambda.functionLiteral
            val bodyExpression = functionLiteral.bodyExpression ?: return null

            val context = bodyExpression.analyze(BodyResolveMode.PARTIAL)
            val functionLiteralDescriptor by lazy { functionLiteral.descriptor }
            bodyExpression.collectDescendantsOfType<KtReturnExpression>().forEach {
                val targetDescriptor = it.getTargetFunctionDescriptor(context)
                if (targetDescriptor == functionDescriptor || targetDescriptor == functionLiteralDescriptor) it.labeledExpression?.delete()
            }

            val psiFactory = KtPsiFactory(lambda)
            val function = psiFactory.createFunction(
                KtPsiFactory.CallableBuilder(KtPsiFactory.CallableBuilder.Target.FUNCTION).apply {
                    typeParams()
                    functionDescriptor.extensionReceiverParameter?.type?.let {
                        receiver(typeSourceCode.renderType(it))
                    }

                    name(functionName)
                    for ((index, parameter) in functionDescriptor.valueParameters.withIndex()) {
                        val type = parameter.type.let { if (it.isFlexible()) it.makeNotNullable() else it }
                        val renderType = typeSourceCode.renderType(
                            getTypeFromParameters(type, typeParameters)
                        )
                        val parameterName = functionParameterName(parameter, index)
                        param(parameterName, renderType)
                    }

                    functionDescriptor.returnType?.takeIf { !it.isUnit() }?.let {
                        val lastStatement = bodyExpression.statements.lastOrNull()
                        if (lastStatement != null && lastStatement !is KtReturnExpression) {
                            val foldableReturns = BranchedFoldingUtils.getFoldableReturns(lastStatement)
                            if (foldableReturns == null || foldableReturns.isEmpty()) {
                                lastStatement.replace(psiFactory.createExpressionByPattern("return $0", lastStatement))
                            }
                        }
                        val renderType = typeSourceCode.renderType(
                            getTypeFromParameters(it, typeParameters)
                        )
                        returnType(renderType)
                    } ?: noReturnType()
                    blockBody(" " + bodyExpression.text)
                }.asString()
            )

            val result = wrapInParenthesisIfNeeded(replaceElement(function), psiFactory)
            ShortenReferences.DEFAULT.process(result)

            return result
        }

        private fun getTypeFromParameters(
            type: KotlinType,
            typeParameters: Map<TypeConstructor, KotlinType>
        ): KotlinType {
            if (type.isTypeParameter())
                return typeParameters[type.constructor] ?: type
            return type
        }

        private fun wrapInParenthesisIfNeeded(expression: KtExpression, psiFactory: KtPsiFactory): KtExpression {
            val parent = expression.parent ?: return expression
            val grandParent = parent.parent ?: return expression

            if (parent is KtCallExpression && grandParent !is KtParenthesizedExpression && grandParent !is KtDeclaration) {
                return expression.replaced(psiFactory.createExpressionByPattern("($0)", expression))
            }

            return expression
        }
    }
}