summaryrefslogtreecommitdiff
path: root/plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UseExpressionBodyInspection.kt
blob: 365a11df6f97181805e9f1f6d6b20c84b73e0993 (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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// 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.inspections

import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING
import com.intellij.codeInspection.ProblemHighlightType.INFORMATION
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.core.canOmitDeclaredType
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.core.util.isOneLiner
import org.jetbrains.kotlin.idea.intentions.hasResultingIfWithoutElse
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.resultingWhens
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext

class UseExpressionBodyInspection(private val convertEmptyToUnit: Boolean) : AbstractKotlinInspection() {

    constructor() : this(convertEmptyToUnit = true)

    private data class Status(val toHighlight: PsiElement?, val subject: String, val highlightType: ProblemHighlightType)

    fun isActiveFor(declaration: KtDeclarationWithBody) = statusFor(declaration) != null

    private fun statusFor(declaration: KtDeclarationWithBody): Status? {
        if (declaration is KtConstructor<*>) return null

        val valueStatement = declaration.findValueStatement() ?: return null
        val value = valueStatement.getValue()
        if (value.anyDescendantOfType<KtReturnExpression>(
                canGoInside = { it !is KtFunctionLiteral && it !is KtNamedFunction && it !is KtPropertyAccessor }
            )
        ) return null

        val toHighlight = valueStatement.toHighlight()
        return when {
            valueStatement !is KtReturnExpression -> Status(toHighlight, KotlinBundle.message("block.body"), INFORMATION)
            valueStatement.returnedExpression is KtWhenExpression -> Status(toHighlight, KotlinBundle.message("return.when"), INFORMATION)
            valueStatement.isOneLiner() -> Status(toHighlight, KotlinBundle.message("one.line.return"), GENERIC_ERROR_OR_WARNING)
            else -> Status(toHighlight, KotlinBundle.message("text.return"), INFORMATION)
        }
    }

    override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
        declarationVisitor(fun(declaration) {
            if (declaration !is KtDeclarationWithBody) return
            val (toHighlightElement, suffix, highlightType) = statusFor(declaration) ?: return
            // Change range to start with left brace
            val hasHighlighting = highlightType != INFORMATION

            fun defaultLevel(): HighlightDisplayLevel {
                val project = declaration.project
                val inspectionProfileManager = ProjectInspectionProfileManager.getInstance(project)
                val inspectionProfile = inspectionProfileManager.currentProfile
                val state = inspectionProfile.getToolDefaultState("UseExpressionBody", project)
                return state.level
            }

            val toHighlightRange = toHighlightElement?.textRange?.let {
                if (hasHighlighting && defaultLevel() != HighlightDisplayLevel.DO_NOT_SHOW) {
                    it
                } else {
                    // Extend range to [left brace..end of highlight element]
                    val offset = (declaration.blockExpression()?.lBrace?.startOffset ?: it.startOffset) - it.startOffset
                    it.shiftRight(offset).grown(-offset)
                }
            }

            holder.registerProblemWithoutOfflineInformation(
                declaration,
                KotlinBundle.message("use.expression.body.instead.of.0", suffix),
                isOnTheFly,
                highlightType,
                toHighlightRange?.shiftRight(-declaration.startOffset),
                ConvertToExpressionBodyFix()
            )
        })

    private fun KtDeclarationWithBody.findValueStatement(): KtExpression? {
        val body = blockExpression() ?: return null
        return body.findValueStatement()
    }

    private fun KtDeclarationWithBody.blockExpression() = when (this) {
        is KtFunctionLiteral -> null
        else -> if (!hasBlockBody()) null else bodyBlockExpression
    }

    private fun KtBlockExpression.findValueStatement(): KtExpression? {
        val bodyStatements = statements
        if (bodyStatements.isEmpty()) {
            return if (convertEmptyToUnit) KtPsiFactory(this).createExpression("Unit") else null
        }
        val statement = bodyStatements.singleOrNull() ?: return null
        when (statement) {
            is KtReturnExpression -> {
                return statement
            }

            //TODO: IMO this is not good code, there should be a way to detect that KtExpression does not have value
            is KtDeclaration, is KtLoopExpression -> return null

            else -> {
                // assignment does not have value
                if (statement is KtBinaryExpression && statement.operationToken in KtTokens.ALL_ASSIGNMENTS) return null

                val context = statement.safeAnalyzeNonSourceRootCode()
                val expressionType = context.getType(statement) ?: return null
                val isUnit = KotlinBuiltIns.isUnit(expressionType)
                if (!isUnit && !KotlinBuiltIns.isNothing(expressionType)) return null
                if (isUnit) {
                    if (statement.hasResultingIfWithoutElse()) {
                        return null
                    }
                    val resultingWhens = statement.resultingWhens()
                    if (resultingWhens.any { it.elseExpression == null && context.get(BindingContext.EXHAUSTIVE_WHEN, it) != true }) {
                        return null
                    }
                }
                return statement
            }
        }
    }

    private fun KtExpression.getValue() = when (this) {
        is KtReturnExpression -> returnedExpression
        else -> null
    } ?: this

    private fun KtExpression.toHighlight(): PsiElement? = when (this) {
        is KtReturnExpression -> returnKeyword
        is KtCallExpression -> calleeExpression
        is KtQualifiedExpression -> selectorExpression?.toHighlight()
        is KtObjectLiteralExpression -> objectDeclaration.getObjectKeyword()
        else -> null
    }

    fun simplify(declaration: KtDeclarationWithBody, canDeleteTypeRef: Boolean) {
        val deleteTypeHandler: (KtCallableDeclaration) -> Unit = {
            it.deleteChildRange(it.colon!!, it.typeReference!!)
        }
        simplify(declaration, deleteTypeHandler.takeIf { canDeleteTypeRef })
    }

    private fun simplify(declaration: KtDeclarationWithBody, deleteTypeHandler: ((KtCallableDeclaration) -> Unit)?) {
        val block = declaration.blockExpression() ?: return
        val valueStatement = block.findValueStatement() ?: return
        val value = valueStatement.getValue()

        if (!declaration.hasDeclaredReturnType() && declaration is KtNamedFunction && block.statements.isNotEmpty()) {
            val valueType = value.safeAnalyzeNonSourceRootCode().getType(value)
            if (valueType == null || !KotlinBuiltIns.isUnit(valueType)) {
                declaration.setType(StandardNames.FqNames.unit.asString(), shortenReferences = true)
            }
        }

        val body = declaration.bodyExpression!!

        val commentSaver = CommentSaver(body)

        val factory = KtPsiFactory(declaration)
        val eq = declaration.addBefore(factory.createEQ(), body)
        declaration.addAfter(factory.createWhiteSpace(), eq)

        val newBody = body.replaced(value)

        commentSaver.restore(newBody)

        if (deleteTypeHandler != null && declaration is KtCallableDeclaration) {
            if (declaration.hasDeclaredReturnType() && declaration.canOmitDeclaredType(newBody, canChangeTypeToSubtype = true)) {
                deleteTypeHandler(declaration)
            }
        }

        val editor = declaration.findExistingEditor()
        if (editor != null) {
            val startOffset = newBody.startOffset
            val document = editor.document
            val startLine = document.getLineNumber(startOffset)
            val rightMargin = editor.settings.getRightMargin(editor.project)
            if (document.getLineEndOffset(startLine) - document.getLineStartOffset(startLine) >= rightMargin) {
                declaration.addBefore(factory.createNewLine(), newBody)
            }
        }
    }

    inner class ConvertToExpressionBodyFix : LocalQuickFix {
        override fun getFamilyName() = name

        override fun getName() = KotlinBundle.message("convert.to.expression.body.fix.text")

        override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
            val declaration = descriptor.psiElement as? KtDeclarationWithBody ?: return
            simplify(declaration) {
                val typeRef = it.typeReference!!
                val colon = it.colon!!
                it.findExistingEditor()?.apply {
                    selectionModel.setSelection(colon.startOffset, typeRef.endOffset)
                    caretModel.moveToOffset(typeRef.endOffset)
                }
            }
        }
    }

}