KT-7443 Inspection + intention to replace assert (x != null) with "!!" or elvis

#KT-7443 Fixed
This commit is contained in:
Valentin Kipyatkov
2016-01-14 16:20:43 +03:00
parent 5ad4571ddf
commit 552359ce03
30 changed files with 397 additions and 0 deletions
@@ -0,0 +1,6 @@
<html>
<body>
This inspection detects an 'assert' calls that check that a variable declared above has non-null value.
Such asserts can be replaced with use of '!!' or '?:' operator in the variable initializer.
</body>
</html>
@@ -0,0 +1 @@
val v = something()<spot>!!</spot>
@@ -0,0 +1,2 @@
val v = something()
<spot>assert(v != null)</spot>
@@ -0,0 +1,6 @@
<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>
+12
View File
@@ -636,6 +636,11 @@
<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>
@@ -1163,6 +1168,13 @@
level="INFO"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.intentions.SimplifyAssertNotNullInspection"
displayName="Replace assert with '!!' or '?:'"
groupName="Kotlin"
enabledByDefault="true"
level="INFO"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.intentions.DeprecatedCallableAddReplaceWithInspection"
displayName="Add 'replaceWith' argument to 'deprecated' annotation"
groupName="Kotlin"
@@ -0,0 +1,123 @@
/*
* 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.idea.intentions
import com.intellij.codeInsight.CodeInsightUtilCore
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
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.quickfix.moveCaret
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.ShortenReferences
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
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 SimplifyAssertNotNullIntention : SelfTargetingOffsetIndependentIntention<KtCallExpression>(
KtCallExpression::class.java,
"Replace assert with '!!' or '?:'"
) {
override fun isApplicableTo(element: KtCallExpression): Boolean {
if ((element.calleeExpression as? KtNameReferenceExpression)?.getReferencedName() != "assert") return false
val arguments = element.valueArguments
if (arguments.size != 1 && arguments.size != 2) return false
val condition = arguments.first().getArgumentExpression() as? KtBinaryExpression ?: return false
if (condition.operationToken != KtTokens.EXCLEQ) return false
val value = condition.expressionComparedToNull() as? KtNameReferenceExpression ?: return false
val prevDeclaration = findVariableDeclaration(element) ?: return false
if (value.getReferencedNameAsName() != prevDeclaration.nameAsName) return false
if (prevDeclaration.initializer == null) return false
val bindingContext = element.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = element.getResolvedCall(bindingContext) ?: return false
if (!resolvedCall.isReallySuccess()) return false
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 (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)
val commentSaver = CommentSaver(element)
if (message == null) {
val newInitializer = KtPsiFactory(element).createExpressionByPattern("$0!!", initializer)
initializer.replace(newInitializer)
}
else {
val newInitializer = KtPsiFactory(element).createExpressionByPattern("$0 ?: kotlin.error($1)", initializer, message)
val result = initializer.replace(newInitializer)
val qualifiedExpression = (result as KtBinaryExpression).right as KtDotQualifiedExpression
ShortenReferences.DEFAULT.process(element.getContainingKtFile(),
qualifiedExpression.startOffset,
(qualifiedExpression.selectorExpression as KtCallExpression).calleeExpression!!.endOffset)
}
element.delete()
commentSaver.restore(declaration)
if (editor != null) {
val newInitializer = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(declaration).initializer!!
val offset = if (message == null)
newInitializer.endOffset
else
(newInitializer as KtBinaryExpression).operationReference.startOffset
editor.moveCaret(offset)
}
}
private fun findVariableDeclaration(element: KtCallExpression): KtVariableDeclaration? {
if (element.parent !is KtBlockExpression) return null
return element.siblings(forward = false, withItself = false).firstIsInstanceOrNull<KtExpression>() as? KtVariableDeclaration
}
private fun extractMessage(element: KtCallExpression): KtExpression? {
val arguments = element.valueArguments
if (arguments.size != 2) return null
return (arguments[1].getArgumentExpression() as? KtLambdaExpression)
?.bodyExpression
?.statements
?.singleOrNull()
}
}
@@ -66,6 +66,7 @@ object J2KPostProcessingRegistrar {
registerIntentionBasedProcessing(AnonymousFunctionToLambdaIntention()) { applyTo(it) }
registerIntentionBasedProcessing(RemoveUnnecessaryParenthesesIntention()) { applyTo(it) }
registerIntentionBasedProcessing(SimplifyForIntention()) { applyTo(it) }
registerIntentionBasedProcessing(SimplifyAssertNotNullIntention()) { applyTo(it, null) }
registerDiagnosticBasedProcessing<KtBinaryExpressionWithTypeRHS>(Errors.USELESS_CAST) { element, diagnostic ->
val expression = RemoveUselessCastFix.invoke(element)
@@ -0,0 +1 @@
org.jetbrains.kotlin.idea.intentions.SimplifyAssertNotNullIntention
@@ -0,0 +1,8 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0]
// now let's check it for null
<caret>assert(v != null /* null */, /* lazy message */ { "Should be not null" }) // 'v' should not be null
}
@@ -0,0 +1,8 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0] ?: error(/* null */ /* lazy message */"Should be not null")
// now let's check it for null
// 'v' should not be null
}
@@ -0,0 +1,8 @@
// INTENTION_TEXT: "Replace with '!!' operator"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0]
// now let's check it for null
<caret>assert(v != null /* null */) // 'v' should not be null
}
@@ -0,0 +1,8 @@
// INTENTION_TEXT: "Replace with '!!' operator"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0]!!<caret>/* null */
// now let's check it for null
// 'v' should not be null
}
@@ -0,0 +1,7 @@
// IS_APPLICABLE: false
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0]
<caret>assert(v != null, { val t = 1; "Should be not null: $t" })
}
@@ -0,0 +1,7 @@
// IS_APPLICABLE: false
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0]
<caret>assert(v == null)
}
@@ -0,0 +1,11 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// WITH_RUNTIME
class C {
fun error(message: String) { }
fun foo(p: Array<String?>) {
val v = p[0]
<caret>assert(v != null) { "message" }
}
}
@@ -0,0 +1,10 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// WITH_RUNTIME
class C {
fun error(message: String) { }
fun foo(p: Array<String?>) {
val v = p[0] <caret>?: kotlin.error("message")
}
}
@@ -0,0 +1,11 @@
// IS_APPLICABLE: false
// WITH_RUNTIME
class C {
fun assert(b: Boolean) { }
fun foo(p: Array<String?>) {
val v = p[0]
<caret>assert(v != null)
}
}
@@ -0,0 +1,7 @@
// INTENTION_TEXT: "Replace with '!!' operator"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0]
<caret>assert(v != null)
}
@@ -0,0 +1,6 @@
// INTENTION_TEXT: "Replace with '!!' operator"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0]!!<caret>
}
@@ -0,0 +1,8 @@
// IS_APPLICABLE: false
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v1 = p[0]
val v2 = p[1]
<caret>assert(v1 != null)
}
@@ -0,0 +1,9 @@
// IS_APPLICABLE: false
// WITH_RUNTIME
class C(val v: String?) {
fun foo(p: Array<String?>) {
val v = p[0]
<caret>assert(this.v != null)
}
}
@@ -0,0 +1,7 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0]
<caret>assert(v != null, { "Should be not null" })
}
@@ -0,0 +1,6 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0] <caret>?: error("Should be not null")
}
@@ -0,0 +1,7 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0]
<caret>assert(v != null) { "Should be not null" }
}
@@ -0,0 +1,6 @@
// INTENTION_TEXT: "Replace with '?: error(...)'"
// WITH_RUNTIME
fun foo(p: Array<String?>) {
val v = p[0] <caret>?: error("Should be not null")
}
@@ -7925,6 +7925,81 @@ 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$"), 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)
@@ -0,0 +1,13 @@
abstract class C {
void foo() {
String s1 = f();
assert s1 != null;
String s2 = g();
assert s2 != null : "g should not return null";
int h = s2.hashCode();
}
abstract void f(): String;
abstract void g(): String;
}
@@ -0,0 +1,11 @@
internal abstract class C {
fun foo() {
val s1 = f()!!
val s2 = g() ?: error("g should not return null")
val h = s2.hashCode()
}
internal abstract fun f()
internal abstract fun g()
}
@@ -316,6 +316,12 @@ public class JavaToKotlinConverterForWebDemoTestGenerated extends AbstractJavaTo
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("j2k/testData/fileOrElement/assertStatement"), Pattern.compile("^(.+)\\.java$"), true);
}
@TestMetadata("assertNotNull.java")
public void testAssertNotNull() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("j2k/testData/fileOrElement/assertStatement/assertNotNull.java");
doTest(fileName);
}
@TestMetadata("onlyCondition.java")
public void testOnlyCondition() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("j2k/testData/fileOrElement/assertStatement/onlyCondition.java");
@@ -316,6 +316,12 @@ public class JavaToKotlinConverterSingleFileTestGenerated extends AbstractJavaTo
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("j2k/testData/fileOrElement/assertStatement"), Pattern.compile("^(.+)\\.java$"), true);
}
@TestMetadata("assertNotNull.java")
public void testAssertNotNull() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("j2k/testData/fileOrElement/assertStatement/assertNotNull.java");
doTest(fileName);
}
@TestMetadata("onlyCondition.java")
public void testOnlyCondition() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("j2k/testData/fileOrElement/assertStatement/onlyCondition.java");