Counter loop in Java is transformed to less effective loop in Kotlin #KT-19337 Fixed

This commit is contained in:
Toshiaki Kameyama
2017-08-21 18:44:51 +09:00
committed by Dmitry Jemerov
parent eefc6ebcc9
commit a6c2135851
8 changed files with 19 additions and 12 deletions
@@ -30,7 +30,7 @@ class A {
fun getSelected(): ArrayList<UsageInfo> {
val result = ArrayList<UsageInfo>()
for (i in 0..myChecked.length - 1) {
for (i in 0 until myChecked.length) {
if (myChecked[i]) {
result.add(myOverridingMethods.get(i))
}
@@ -206,10 +206,11 @@ class ForConverter(
if (indicesRange != null) return indicesRange
val startConverted = codeConverter.convertExpression(start)
return if (reversed)
DownToExpression(startConverted, convertBound(bound, if (inclusiveComparison) 0 else +1))
else
RangeExpression(startConverted, convertBound(bound, if (inclusiveComparison) 0 else -1))
return when {
reversed -> DownToExpression(startConverted, convertBound(bound, if (inclusiveComparison) 0 else +1))
bound !is PsiLiteralExpression && !inclusiveComparison -> UntilExpression(startConverted, convertBound(bound, 0))
else -> RangeExpression(startConverted, convertBound(bound, if (inclusiveComparison) 0 else -1))
}
}
private fun indicesIterationRange(start: PsiExpression, bound: PsiExpression, reversed: Boolean, inclusiveComparison: Boolean): Expression? {
@@ -265,6 +265,12 @@ class RangeExpression(val start: Expression, val end: Expression): Expression()
}
}
class UntilExpression(val start: Expression, val end: Expression): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, start).append(" until ").appendOperand(this, end)
}
}
class DownToExpression(val start: Expression, val end: Expression): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, start).append(" downTo ").appendOperand(this, end)
+1 -1
View File
@@ -48,7 +48,7 @@ private fun Expression.precedence(): Int? {
is BinaryExpression -> op.precedence
is RangeExpression, is DownToExpression -> 5
is RangeExpression, is UntilExpression, is DownToExpression -> 5
is IsOperator -> 8
+1 -1
View File
@@ -1,3 +1,3 @@
for (i in 0..N - 1) {
for (i in 0 until N) {
println(i)
}
@@ -4,7 +4,7 @@ internal class X {
internal class C {
fun foo(x: X) {
for (i in 0..x.length - 1) {
for (i in 0 until x.length) {
print(i)
}
}
@@ -6,7 +6,7 @@ internal class X {
internal class C {
fun foo(x: X) {
for (i in 0..x.size() - 1) {
for (i in 0 until x.size()) {
print(i)
}
}
+3 -3
View File
@@ -4,15 +4,15 @@ internal class Test {
println(i1)
val b: Byte = 1
for (i2 in 0..b - 1)
for (i2 in 0 until b)
println(i2)
val s: Short = 1
for (i3 in 0..s - 1)
for (i3 in 0 until s)
println(i3)
val l = 1L
for (i4 in 0..l - 1)
for (i4 in 0 until l)
println(i4)
val d = 1.0