Refactoring: "simplify assert not null" is now an inspection

This commit is contained in:
Mikhail Glukhikh
2017-12-20 20:59:59 +03:00
parent 8ebe16c9b2
commit 9e919829c8
27 changed files with 134 additions and 132 deletions
@@ -1 +0,0 @@
val v = something()<spot>!!</spot>
@@ -1,2 +0,0 @@
val v = something()
<spot>assert(v != null)</spot>
@@ -1,6 +0,0 @@
<html>
<body>
This intention replaces an 'assert' call which checks that a variable declared above has non-null value
with use of '!!' or '?:' operator in the variable initializer.
</body>
</html>
+1 -6
View File
@@ -782,11 +782,6 @@
<category>Kotlin</category>
</intentionAction>
<intentionAction>
<className>org.jetbrains.kotlin.idea.intentions.SimplifyAssertNotNullIntention</className>
<category>Kotlin</category>
</intentionAction>
<intentionAction>
<className>org.jetbrains.kotlin.idea.intentions.ImportMemberIntention</className>
<category>Kotlin</category>
@@ -1546,7 +1541,7 @@
language="kotlin"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.intentions.SimplifyAssertNotNullInspection"
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.SimplifyAssertNotNullInspection"
displayName="assert call can be replaced with !! or ?:'"
groupPath="Kotlin"
groupName="Style issues"
@@ -1,5 +1,5 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
* 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.
@@ -14,16 +14,19 @@
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.intentions
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.CodeInsightUtilCore
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.expressionComparedToNull
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
@@ -36,13 +39,16 @@ import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class SimplifyAssertNotNullInspection : IntentionBasedInspection<KtCallExpression>(SimplifyAssertNotNullIntention::class)
class SimplifyAssertNotNullInspection : AbstractApplicabilityBasedInspection<KtCallExpression>() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): KtVisitorVoid =
object : KtVisitorVoid() {
override fun visitCallExpression(expression: KtCallExpression) {
super.visitCallExpression(expression)
visitTargetElement(expression, holder, isOnTheFly)
}
}
class SimplifyAssertNotNullIntention : SelfTargetingOffsetIndependentIntention<KtCallExpression>(
KtCallExpression::class.java,
"Replace assert with '!!' or '?:'"
) {
override fun isApplicableTo(element: KtCallExpression): Boolean {
override fun isApplicable(element: KtCallExpression): Boolean {
if ((element.calleeExpression as? KtNameReferenceExpression)?.getReferencedName() != "assert") return false
val arguments = element.valueArguments
@@ -62,38 +68,48 @@ class SimplifyAssertNotNullIntention : SelfTargetingOffsetIndependentIntention<K
val function = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return false
if (function.importableFqName?.asString() != "kotlin.assert") return false
if (arguments.size == 1) {
this.text = "Replace with '!!' operator"
}
else {
if (arguments.size != 1) {
if (extractMessage(element) == null) return false
this.text = "Replace with '?: error(...)'"
}
return true
}
override fun applyTo(element: KtCallExpression, editor: Editor?) {
val declaration = findVariableDeclaration(element)!!
val initializer = declaration.initializer!!
val message = extractMessage(element)
override fun inspectionText(element: KtCallExpression) = "assert can be replaced with operator"
val commentSaver = CommentSaver(element)
override val defaultFixText: String = "Replace assert with operator"
override fun fixText(element: KtCallExpression): String {
return if (element.valueArguments.size == 1) {
"Replace with '!!' operator"
}
else {
"Replace with '?: error(...)'"
}
}
override fun applyTo(element: PsiElement, project: Project, editor: Editor?) {
val expression = element as? KtCallExpression ?: return
val declaration = findVariableDeclaration(expression)!!
val initializer = declaration.initializer!!
val message = extractMessage(expression)
val commentSaver = CommentSaver(expression)
if (message == null) {
val newInitializer = KtPsiFactory(element).createExpressionByPattern("$0!!", initializer)
val newInitializer = KtPsiFactory(expression).createExpressionByPattern("$0!!", initializer)
initializer.replace(newInitializer)
}
else {
val newInitializer = KtPsiFactory(element).createExpressionByPattern("$0 ?: kotlin.error($1)", initializer, message)
val newInitializer = KtPsiFactory(expression).createExpressionByPattern("$0 ?: kotlin.error($1)", initializer, message)
val result = initializer.replace(newInitializer)
val qualifiedExpression = (result as KtBinaryExpression).right as KtDotQualifiedExpression
ShortenReferences.DEFAULT.process(element.containingKtFile,
ShortenReferences.DEFAULT.process(expression.containingKtFile,
qualifiedExpression.startOffset,
(qualifiedExpression.selectorExpression as KtCallExpression).calleeExpression!!.endOffset)
}
element.delete()
expression.delete()
commentSaver.restore(declaration)
@@ -96,7 +96,7 @@ object J2KPostProcessingRegistrar {
registerIntentionBasedProcessing(AnonymousFunctionToLambdaIntention())
registerIntentionBasedProcessing(RemoveUnnecessaryParenthesesIntention())
registerIntentionBasedProcessing(DestructureIntention())
registerIntentionBasedProcessing(SimplifyAssertNotNullIntention())
registerInspectionBasedProcessing(SimplifyAssertNotNullInspection())
registerIntentionBasedProcessing(RemoveRedundantCallsOfConversionMethodsIntention())
registerDiagnosticBasedProcessing<KtBinaryExpressionWithTypeRHS>(Errors.USELESS_CAST) { element, _ ->
@@ -0,0 +1 @@
org.jetbrains.kotlin.idea.inspections.SimplifyAssertNotNullInspection
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// FIX: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// FIX: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '!!' operator"
// FIX: "Replace with '!!' operator"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '!!' operator"
// FIX: "Replace with '!!' operator"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// IS_APPLICABLE: false
// PROBLEM: none
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// IS_APPLICABLE: false
// PROBLEM: none
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// FIX: "Replace with '?: error(...)'"
// WITH_RUNTIME
class C {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// FIX: "Replace with '?: error(...)'"
// WITH_RUNTIME
class C {
@@ -1,4 +1,4 @@
// IS_APPLICABLE: false
// PROBLEM: none
// WITH_RUNTIME
class C {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '!!' operator"
// FIX: "Replace with '!!' operator"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '!!' operator"
// FIX: "Replace with '!!' operator"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// IS_APPLICABLE: false
// PROBLEM: none
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// IS_APPLICABLE: false
// PROBLEM: none
// WITH_RUNTIME
class C(val v: String?) {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// FIX: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// FIX: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// FIX: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1,4 +1,4 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// FIX: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
@@ -1 +0,0 @@
org.jetbrains.kotlin.idea.intentions.SimplifyAssertNotNullIntention
@@ -3516,6 +3516,81 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
}
}
@TestMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class SimplifyAssertNotNull extends AbstractLocalInspectionTest {
public void testAllFilesPresentInSimplifyAssertNotNull() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/inspectionsLocal/simplifyAssertNotNull"), Pattern.compile("^([\\w\\-_]+)\\.(kt|kts)$"), TargetBackend.ANY, true);
}
@TestMetadata("comments.kt")
public void testComments() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/comments.kt");
doTest(fileName);
}
@TestMetadata("commentsNoMessage.kt")
public void testCommentsNoMessage() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/commentsNoMessage.kt");
doTest(fileName);
}
@TestMetadata("complicatedMessageLambda.kt")
public void testComplicatedMessageLambda() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/complicatedMessageLambda.kt");
doTest(fileName);
}
@TestMetadata("eqNull.kt")
public void testEqNull() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/eqNull.kt");
doTest(fileName);
}
@TestMetadata("errorFunctionInContext.kt")
public void testErrorFunctionInContext() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/errorFunctionInContext.kt");
doTest(fileName);
}
@TestMetadata("falseAssert.kt")
public void testFalseAssert() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/falseAssert.kt");
doTest(fileName);
}
@TestMetadata("noMessage.kt")
public void testNoMessage() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/noMessage.kt");
doTest(fileName);
}
@TestMetadata("otherVariable.kt")
public void testOtherVariable() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/otherVariable.kt");
doTest(fileName);
}
@TestMetadata("qualifiedAccess.kt")
public void testQualifiedAccess() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/qualifiedAccess.kt");
doTest(fileName);
}
@TestMetadata("withMessage.kt")
public void testWithMessage() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/withMessage.kt");
doTest(fileName);
}
@TestMetadata("withMessageLambdaOutside.kt")
public void testWithMessageLambdaOutside() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/simplifyAssertNotNull/withMessageLambdaOutside.kt");
doTest(fileName);
}
}
@TestMetadata("idea/testData/inspectionsLocal/simplifyNegatedBinaryExpression")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@@ -14187,81 +14187,6 @@ public class IntentionTestGenerated extends AbstractIntentionTest {
}
}
@TestMetadata("idea/testData/intentions/simplifyAssertNotNull")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class SimplifyAssertNotNull extends AbstractIntentionTest {
public void testAllFilesPresentInSimplifyAssertNotNull() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/intentions/simplifyAssertNotNull"), Pattern.compile("^([\\w\\-_]+)\\.(kt|kts)$"), TargetBackend.ANY, true);
}
@TestMetadata("comments.kt")
public void testComments() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/comments.kt");
doTest(fileName);
}
@TestMetadata("commentsNoMessage.kt")
public void testCommentsNoMessage() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/commentsNoMessage.kt");
doTest(fileName);
}
@TestMetadata("complicatedMessageLambda.kt")
public void testComplicatedMessageLambda() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/complicatedMessageLambda.kt");
doTest(fileName);
}
@TestMetadata("eqNull.kt")
public void testEqNull() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/eqNull.kt");
doTest(fileName);
}
@TestMetadata("errorFunctionInContext.kt")
public void testErrorFunctionInContext() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/errorFunctionInContext.kt");
doTest(fileName);
}
@TestMetadata("falseAssert.kt")
public void testFalseAssert() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/falseAssert.kt");
doTest(fileName);
}
@TestMetadata("noMessage.kt")
public void testNoMessage() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/noMessage.kt");
doTest(fileName);
}
@TestMetadata("otherVariable.kt")
public void testOtherVariable() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/otherVariable.kt");
doTest(fileName);
}
@TestMetadata("qualifiedAccess.kt")
public void testQualifiedAccess() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/qualifiedAccess.kt");
doTest(fileName);
}
@TestMetadata("withMessage.kt")
public void testWithMessage() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/withMessage.kt");
doTest(fileName);
}
@TestMetadata("withMessageLambdaOutside.kt")
public void testWithMessageLambdaOutside() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/simplifyAssertNotNull/withMessageLambdaOutside.kt");
doTest(fileName);
}
}
@TestMetadata("idea/testData/intentions/simplifyBooleanWithConstants")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)