diff --git a/CHANGELOG.md b/CHANGELOG.md index 52f7a4d2..eaa2129b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,8 @@ * Fixed `@long` and `@long_be` array filters. +* Fixed for-each loops with non-constant arrays. + * 8080 and LR35902: fixed large stack variables. * Other bug fixes. diff --git a/docs/lang/syntax.md b/docs/lang/syntax.md index eec893e3..4e033588 100644 --- a/docs/lang/syntax.md +++ b/docs/lang/syntax.md @@ -312,11 +312,13 @@ for : [ ] { * `paralleluntil` – the same as `until`, but the iterations may be executed in any order - There is no `paralleldownto`, because it would do the same as `parallelto`. + There is no `paralleldownto`, because it would do the same as `parallelto` with swapped arguments. * `` – traverse enum constants of given type, in arbitrary order -* `` – traverse every value in the list +* `` – traverse every value in the list, in the given order. +Values do not have to be constant. +If a value is not a constant and its value changes while executing the loop, the behaviour is undefined. ### `break` and `continue` statements diff --git a/src/main/scala/millfork/node/Node.scala b/src/main/scala/millfork/node/Node.scala index 4399fc70..520b0a54 100644 --- a/src/main/scala/millfork/node/Node.scala +++ b/src/main/scala/millfork/node/Node.scala @@ -515,7 +515,7 @@ case class ForStatement(variable: String, start: Expression, end: Expression, di } case class ForEachStatement(variable: String, values: Either[Expression, List[Expression]], body: List[ExecutableStatement]) extends CompoundStatement { - override def getAllExpressions: List[Expression] = VariableExpression(variable) :: body.flatMap(_.getAllExpressions) + override def getAllExpressions: List[Expression] = VariableExpression(variable) :: (values.fold[List[Expression]](_ => Nil, identity) ++ body.flatMap(_.getAllExpressions)) override def getChildStatements: Seq[Statement] = body override def flatMap(f: ExecutableStatement => Option[ExecutableStatement]): Option[ExecutableStatement] = { diff --git a/src/test/scala/millfork/test/ForLoopSuite.scala b/src/test/scala/millfork/test/ForLoopSuite.scala index 40ce177c..d0e47171 100644 --- a/src/test/scala/millfork/test/ForLoopSuite.scala +++ b/src/test/scala/millfork/test/ForLoopSuite.scala @@ -351,7 +351,9 @@ class ForLoopSuite extends FunSuite with Matchers { | for p:[$c000, $c003, $c005, $c007]{ | p[0] = 34 | } - | for p:[$c001, $c004, $c006, $c008]{ + | word w + | w = $c004 + | for p:[$c001, w, $c006, w+4]{ | p[0] = 42 | } | }