Convert intention "a..b-1 -> a until b" into weak warning inspection

So #KT-17895 Fixed
This commit is contained in:
Ilya Zorin
2017-05-25 18:25:11 +03:00
committed by Mikhail Glukhikh
parent 0fd42bc747
commit 5e265b3d17
26 changed files with 242 additions and 157 deletions
@@ -0,0 +1,5 @@
<html>
<body>
This inspection reports calls to 'rangeTo' or the '..' operator instead of calls to 'until'.
</body>
</html>
@@ -1,5 +0,0 @@
<html>
<body>
This intention replaces calls to 'rangeTo' or the '..' operator with calls to 'until' and offsets the upper bound by 1.
</body>
</html>
+8 -5
View File
@@ -1403,11 +1403,6 @@
<category>Kotlin</category>
</intentionAction>
<intentionAction>
<className>org.jetbrains.kotlin.idea.intentions.ReplaceRangeToWithUntilIntention</className>
<category>Kotlin</category>
</intentionAction>
<intentionAction>
<className>org.jetbrains.kotlin.idea.intentions.ReplaceUntilWithRangeToIntention</className>
<category>Kotlin</category>
@@ -2188,6 +2183,14 @@
language="kotlin"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.ReplaceRangeToWithUntilInspection"
displayName="'rangeTo' or the '..' call can be replaced with 'until'"
groupName="Kotlin"
enabledByDefault="true"
level="WEAK WARNING"
language="kotlin"
/>
<referenceImporter implementation="org.jetbrains.kotlin.idea.quickfix.KotlinReferenceImporter"/>
<fileType.fileViewProviderFactory filetype="KJSM" implementationClass="com.intellij.psi.ClassFileViewProviderFactory"/>
@@ -0,0 +1,89 @@
/*
* 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.
* 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.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.getArguments
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
private val REGEX_RANGE_TO = """kotlin.(Char|Byte|Short|Int|Long).rangeTo""".toRegex()
class ReplaceRangeToWithUntilInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitExpression(expression: KtExpression) {
super.visitExpression(expression)
if (expression !is KtBinaryExpression && expression !is KtDotQualifiedExpression) return
val fqName = expression.getCallableDescriptor()?.fqNameUnsafe?.asString() ?: return
if (!fqName.matches(REGEX_RANGE_TO)) return
if (expression.getArguments()?.second?.isMinusOne() != true) return
holder.registerProblem(
expression,
"'rangeTo' or the '..' call can be replaced with 'until'",
ProblemHighlightType.WEAK_WARNING,
ReplaceWithUntilQuickFix()
)
}
}
}
class ReplaceWithUntilQuickFix : LocalQuickFix {
override fun getName() = "Replace with until"
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as KtExpression
val args = element.getArguments() ?: return
element.replace(KtPsiFactory(element).createExpressionByPattern(
"$0 until $1",
args.first ?: return,
(args.second as? KtBinaryExpression)?.left ?: return)
)
}
}
private fun KtExpression.isMinusOne(): Boolean {
if (this !is KtBinaryExpression) return false
if (operationToken != KtTokens.MINUS) return false
val right = right as? KtConstantExpression ?: return false
val context = right.analyze(BodyResolveMode.PARTIAL)
val constantValue = ConstantExpressionEvaluator.getConstant(right, context)?.toConstantValue(right.getType(context) ?: return false)
val rightValue = (constantValue?.value as? Number)?.toInt() ?: return false
return rightValue == 1
}
}
@@ -1,83 +0,0 @@
/*
* 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.openapi.editor.Editor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
private fun KtExpression.getCallableDescriptor() = getResolvedCall(analyze())?.resultingDescriptor
private fun KtExpression.getArguments() = when (this) {
is KtBinaryExpression -> this.left to this.right
is KtDotQualifiedExpression -> this.receiverExpression to this.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression()
else -> null
}
private val REGEX_RANGE_TO = """kotlin.(Char|Byte|Short|Int|Long).rangeTo""".toRegex()
class ReplaceRangeToWithUntilIntention : SelfTargetingIntention<KtExpression>(
KtExpression::class.java,
"Replace with 'until' function call"
) {
override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean {
if (element !is KtBinaryExpression && element !is KtDotQualifiedExpression) return false
val fqName = element.getCallableDescriptor()?.fqNameUnsafe?.asString() ?: return false
if (!fqName.matches(REGEX_RANGE_TO)) return false
return element.getArguments()?.second?.isMinusOne() == true
}
override fun applyTo(element: KtExpression, editor: Editor?) {
val args = element.getArguments() ?: return
element.replace(KtPsiFactory(element).createExpressionByPattern("$0 until $1",
args.first ?: return,
(args.second as? KtBinaryExpression)?.left ?: return))
}
private fun KtExpression.isMinusOne(): Boolean {
if (this !is KtBinaryExpression) return false
if (operationToken != KtTokens.MINUS) return false
val right = right as? KtConstantExpression ?: return false
val context = right.analyze(BodyResolveMode.PARTIAL)
val constantValue = ConstantExpressionEvaluator.getConstant(right, context)?.toConstantValue(right.getType(context) ?: return false)
val rightValue = (constantValue?.value as? Number)?.toInt() ?: return false
return rightValue == 1
}
}
class ReplaceUntilWithRangeToIntention : SelfTargetingIntention<KtExpression>(KtExpression::class.java, "Replace with '..' operator") {
override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean {
if (element !is KtBinaryExpression && element !is KtDotQualifiedExpression) return false
val fqName = element.getCallableDescriptor()?.fqNameUnsafe?.asString() ?: return false
return fqName == "kotlin.ranges.until"
}
override fun applyTo(element: KtExpression, editor: Editor?) {
val args = element.getArguments() ?: return
element.replace(KtPsiFactory(element).createExpressionByPattern("$0..$1 - 1", args.first ?: return, args.second ?: return))
}
}
@@ -0,0 +1,44 @@
/*
* 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.openapi.editor.Editor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
internal fun KtExpression.getCallableDescriptor() = getResolvedCall(analyze())?.resultingDescriptor
internal fun KtExpression.getArguments() = when (this) {
is KtBinaryExpression -> this.left to this.right
is KtDotQualifiedExpression -> this.receiverExpression to this.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression()
else -> null
}
class ReplaceUntilWithRangeToIntention : SelfTargetingIntention<KtExpression>(KtExpression::class.java, "Replace with '..' operator") {
override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean {
if (element !is KtBinaryExpression && element !is KtDotQualifiedExpression) return false
val fqName = element.getCallableDescriptor()?.fqNameUnsafe?.asString() ?: return false
return fqName == "kotlin.ranges.until"
}
override fun applyTo(element: KtExpression, editor: Editor?) {
val args = element.getArguments() ?: return
element.replace(KtPsiFactory(element).createExpressionByPattern("$0..$1 - 1", args.first ?: return, args.second ?: return))
}
}
@@ -0,0 +1,18 @@
<problems>
<problem>
<file>test.kt</file>
<line>3</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">'rangeTo' or the '..' call can be replaced with 'until'</problem_class>
<description>'rangeTo' or the '..' call can be replaced with 'until'</description>
</problem>
<problem>
<file>test.kt</file>
<line>8</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">'rangeTo' or the '..' call can be replaced with 'until'</problem_class>
<description>'rangeTo' or the '..' call can be replaced with 'until'</description>
</problem>
</problems>
@@ -0,0 +1 @@
// INSPECTION_CLASS: org.jetbrains.kotlin.idea.inspections.ReplaceRangeToWithUntilInspection
@@ -0,0 +1,9 @@
fun foo() {
val n = 10
for (i in 0 .. n - 1) {}
}
fun bar() {
val n = 10
for (i in 0.rangeTo(n - 1)) {}
}
@@ -0,0 +1 @@
org.jetbrains.kotlin.idea.inspections.ReplaceRangeToWithUntilInspection
@@ -1,5 +1,5 @@
// WITH_RUNTIME
// IS_APPLICABLE: false
// PROBLEM: none
fun foo(a: Float) {
1f<caret>..a - 1
@@ -1,5 +1,5 @@
// WITH_RUNTIME
// IS_APPLICABLE: false
// PROBLEM: none
fun foo(a: Int) {
for (i in 0..a - 2<caret>) {
@@ -1,5 +1,5 @@
// WITH_RUNTIME
// IS_APPLICABLE: false
// PROBLEM: none
fun foo(a: Int) {
for (i in 0..a<caret>) {
@@ -1,7 +1,7 @@
// WITH_RUNTIME
fun foo(a: Int) {
for (i in 0..a - 1<caret>) {
for (i in 0..<caret>a - 1) {
}
}
@@ -1,7 +1,7 @@
// WITH_RUNTIME
fun foo(a: Int) {
for (i in 0 until a<caret>) {
for (i in 0 until a) {
}
}
@@ -1,7 +1,7 @@
// WITH_RUNTIME
fun foo(a: Long) {
for (i in 1L..a - 1L<caret>) {
for (i in 1L<caret>..a - 1L) {
}
}
@@ -1,7 +1,7 @@
// WITH_RUNTIME
fun foo(a: Long) {
for (i in 1L until a<caret>) {
for (i in 1L until a) {
}
}
@@ -1,5 +1,5 @@
// WITH_RUNTIME
// IS_APPLICABLE: false
// PROBLEM: none
fun foo(a: Int) {
for (i in 0..a + 1<caret>) {
@@ -1,7 +1,7 @@
// WITH_RUNTIME
fun foo(a: Int) {
for (i in 0.rangeTo(a - 1)<caret>) {
for (i in <caret>0.rangeTo(a - 1)) {
}
}
@@ -1,7 +1,7 @@
// WITH_RUNTIME
fun foo(a: Int) {
for (i in 0 until a<caret>) {
for (i in 0 until a) {
}
}
@@ -1 +0,0 @@
org.jetbrains.kotlin.idea.intentions.ReplaceRangeToWithUntilIntention
@@ -299,6 +299,12 @@ public class InspectionTestGenerated extends AbstractInspectionTest {
doTest(fileName);
}
@TestMetadata("replaceRangeToWithUntil/inspectionData/inspections.test")
public void testReplaceRangeToWithUntil_inspectionData_Inspections_test() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspections/replaceRangeToWithUntil/inspectionData/inspections.test");
doTest(fileName);
}
@TestMetadata("spelling/inspectionData/inspections.test")
public void testSpelling_inspectionData_Inspections_test() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspections/spelling/inspectionData/inspections.test");
@@ -209,4 +209,55 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
doTest(fileName);
}
}
@TestMetadata("idea/testData/inspectionsLocal/replaceRangeToWithUntil")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class ReplaceRangeToWithUntil extends AbstractLocalInspectionTest {
public void testAllFilesPresentInReplaceRangeToWithUntil() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/inspectionsLocal/replaceRangeToWithUntil"), Pattern.compile("^([\\w\\-_]+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("closedRange.kt")
public void testClosedRange() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/replaceRangeToWithUntil/closedRange.kt");
doTest(fileName);
}
@TestMetadata("minusTwo.kt")
public void testMinusTwo() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/replaceRangeToWithUntil/minusTwo.kt");
doTest(fileName);
}
@TestMetadata("notMinusOne.kt")
public void testNotMinusOne() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/replaceRangeToWithUntil/notMinusOne.kt");
doTest(fileName);
}
@TestMetadata("operator.kt")
public void testOperator() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/replaceRangeToWithUntil/operator.kt");
doTest(fileName);
}
@TestMetadata("operatorLong.kt")
public void testOperatorLong() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/replaceRangeToWithUntil/operatorLong.kt");
doTest(fileName);
}
@TestMetadata("plusOne.kt")
public void testPlusOne() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/replaceRangeToWithUntil/plusOne.kt");
doTest(fileName);
}
@TestMetadata("rangeTo.kt")
public void testRangeTo() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspectionsLocal/replaceRangeToWithUntil/rangeTo.kt");
doTest(fileName);
}
}
}
@@ -13512,57 +13512,6 @@ public class IntentionTestGenerated extends AbstractIntentionTest {
}
}
@TestMetadata("idea/testData/intentions/replaceRangeToWithUntil")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class ReplaceRangeToWithUntil extends AbstractIntentionTest {
public void testAllFilesPresentInReplaceRangeToWithUntil() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/intentions/replaceRangeToWithUntil"), Pattern.compile("^([\\w\\-_]+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("closedRange.kt")
public void testClosedRange() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/replaceRangeToWithUntil/closedRange.kt");
doTest(fileName);
}
@TestMetadata("minusTwo.kt")
public void testMinusTwo() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/replaceRangeToWithUntil/minusTwo.kt");
doTest(fileName);
}
@TestMetadata("notMinusOne.kt")
public void testNotMinusOne() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/replaceRangeToWithUntil/notMinusOne.kt");
doTest(fileName);
}
@TestMetadata("operator.kt")
public void testOperator() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/replaceRangeToWithUntil/operator.kt");
doTest(fileName);
}
@TestMetadata("operatorLong.kt")
public void testOperatorLong() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/replaceRangeToWithUntil/operatorLong.kt");
doTest(fileName);
}
@TestMetadata("plusOne.kt")
public void testPlusOne() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/replaceRangeToWithUntil/plusOne.kt");
doTest(fileName);
}
@TestMetadata("rangeTo.kt")
public void testRangeTo() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/replaceRangeToWithUntil/rangeTo.kt");
doTest(fileName);
}
}
@TestMetadata("idea/testData/intentions/replaceSingleLineLetIntention")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)