KT-36685 "Convert to a range check" transform hex range to int if it is compared with "Less" or "Greater"

#KT-36685 Fixed
This commit is contained in:
Vladimir Dolzhenko
2020-02-17 14:43:37 +01:00
committed by GitHub
6 changed files with 43 additions and 3 deletions
@@ -111,10 +111,24 @@ class ConvertTwoComparisonsToRangeCheckInspection :
is KtConstantExpression -> {
val constantValue = ConstantExpressionEvaluator.getConstant(this, context)?.getValue(type) ?: return null
return when {
KotlinBuiltIns.isInt(type) -> (constantValue as Int + number).toString()
KotlinBuiltIns.isLong(type) -> (constantValue as Long + number).toString()
KotlinBuiltIns.isInt(type) -> (constantValue as Int + number).let {
val text = this.text
when {
text.startsWith("0x") -> "0x${it.toString(16)}"
text.startsWith("0b") -> "0b${it.toString(2)}"
else -> it.toString()
}
}
KotlinBuiltIns.isLong(type) -> (constantValue as Long + number).let {
val text = this.text
when {
text.startsWith("0x") -> "0x${it.toString(16)}"
text.startsWith("0b") -> "0b${it.toString(2)}"
else -> it.toString()
}
}
KotlinBuiltIns.isChar(type) -> "'${constantValue as Char + number}'"
else -> return null
else -> null
}
}
else -> return if (number >= 0) "($text + $number)" else "($text - ${-number})"
@@ -0,0 +1,4 @@
fun test(c: Int) {
if (<caret>c > 0b1101100000000000 && c < 0b1101110000000000) {
}
}
@@ -0,0 +1,4 @@
fun test(c: Int) {
if (c in 0b1101100000000001..0b1101101111111111) {
}
}
@@ -0,0 +1,4 @@
fun test(c: Int) {
if (<caret>c > 0xd800 && c < 0xdc00) {
}
}
@@ -0,0 +1,4 @@
fun test(c: Int) {
if (c in 0xd801..0xdbff) {
}
}
@@ -3438,6 +3438,11 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
KotlinTestUtils.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("idea/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck"), Pattern.compile("^([\\w\\-_]+)\\.(kt|kts)$"), null, true);
}
@TestMetadata("binary.kt")
public void testBinary() throws Exception {
runTest("idea/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/binary.kt");
}
@TestMetadata("char.kt")
public void testChar() throws Exception {
runTest("idea/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/char.kt");
@@ -3543,6 +3548,11 @@ public class LocalInspectionTestGenerated extends AbstractLocalInspectionTest {
runTest("idea/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/gtlteq.kt");
}
@TestMetadata("hexadecimal.kt")
public void testHexadecimal() throws Exception {
runTest("idea/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/hexadecimal.kt");
}
@TestMetadata("lteqgt.kt")
public void testLteqgt() throws Exception {
runTest("idea/testData/inspectionsLocal/convertTwoComparisonsToRangeCheck/lteqgt.kt");