diff --git a/src/main/scala/millfork/compiler/AbstractStatementCompiler.scala b/src/main/scala/millfork/compiler/AbstractStatementCompiler.scala index 020a521f..3190976e 100644 --- a/src/main/scala/millfork/compiler/AbstractStatementCompiler.scala +++ b/src/main/scala/millfork/compiler/AbstractStatementCompiler.scala @@ -229,6 +229,8 @@ abstract class AbstractStatementCompiler[T <: AbstractCode] { names) )) case (ForDirection.DownTo, _, _) => + // TODO: smarter countdown if end is not a constant + val endMinusOne = SumExpression(List(true -> f.end, false -> LiteralExpression(1, 1)), decimal = false).pos(p) compile(ctx, List( Assignment(vex, f.start).pos(p), IfStatement( @@ -236,7 +238,7 @@ abstract class AbstractStatementCompiler[T <: AbstractCode] { List(DoWhileStatement( f.body, List(decrement), - FunctionCallExpression("!=", List(vex, f.end)).pos(p), + FunctionCallExpression("!=", List(vex, endMinusOne)).pos(p), names ).pos(p)), Nil) diff --git a/src/test/scala/millfork/test/ForLoopSuite.scala b/src/test/scala/millfork/test/ForLoopSuite.scala index c09350c0..138fd20d 100644 --- a/src/test/scala/millfork/test/ForLoopSuite.scala +++ b/src/test/scala/millfork/test/ForLoopSuite.scala @@ -77,6 +77,30 @@ class ForLoopSuite extends FunSuite with Matchers { } } + test("For-downto 3") { + EmuCrossPlatformBenchmarkRun(Cpu.Mos, Cpu.Z80, Cpu.Intel8080, Cpu.Sharp)( + """ + | array output [55] @$c000 + | void main () { + | byte i + | output[0] = 0 + | output[1] = 0 + | output[5] = 0 + | output[6] = 0 + | for i,5,downto,1 { + | stuff() + | output[i] += 1 + | } + | } + | noinline void stuff() {} + """.stripMargin){m => + m.readByte(0xc000) should equal(0) + m.readByte(0xc001) should equal(1) + m.readByte(0xc005) should equal(1) + m.readByte(0xc006) should equal(0) + } + } + test("For-until") { EmuCrossPlatformBenchmarkRun(Cpu.Mos, Cpu.Z80, Cpu.Intel8080, Cpu.Sharp)( """