diff --git a/docs/lang/syntax.md b/docs/lang/syntax.md index 72ec4fe6..41e14c03 100644 --- a/docs/lang/syntax.md +++ b/docs/lang/syntax.md @@ -149,6 +149,19 @@ If the declared size and the size deduced from the `` don't matc * `` is an array literal, see [Literals](./literals.md). Local arrays can have initial values only if they're const. +Each array has an associated constant defined that contains its length +and, if the indices are numeric, another constant that contains the last index of the array: + + array x[5] + x.length // equals 5 + x.lastindex // equals 4 + + enum e { ... } + array y[e] + y.length // equals e.count + // y.lastindex // doesn't exist + + TODO ### Function declarations diff --git a/src/main/scala/millfork/env/Environment.scala b/src/main/scala/millfork/env/Environment.scala index 13bcd4bc..53674752 100644 --- a/src/main/scala/millfork/env/Environment.scala +++ b/src/main/scala/millfork/env/Environment.scala @@ -1458,6 +1458,15 @@ class Environment(val parent: Option[Environment], val prefix: String, val cpuFa } if (length < 256) { addThing(ConstantThing(arrayName + ".length", lengthConst, b), stmt.position) + } else { + addThing(ConstantThing(arrayName + ".length", lengthConst, w), stmt.position) + } + if (length > 0 && indexType.isArithmetic) { + if (length <= 256) { + addThing(ConstantThing(arrayName + ".lastindex", NumericConstant(length - 1, 1), b), stmt.position) + } else { + addThing(ConstantThing(arrayName + ".lastindex", NumericConstant(length - 1, 2), w), stmt.position) + } } case _ => log.error(s"Array `${stmt.name}` has weird length", stmt.position) } @@ -1531,6 +1540,15 @@ class Environment(val parent: Option[Environment], val prefix: String, val cpuFa } if (length < 256) { addThing(ConstantThing(arrayName + ".length", NumericConstant(length, 1), b), stmt.position) + } else { + addThing(ConstantThing(arrayName + ".length", NumericConstant(length, 2), w), stmt.position) + } + if (length > 0 && indexType.isArithmetic) { + if (length <= 256) { + addThing(ConstantThing(arrayName + ".lastindex", NumericConstant(length - 1, 1), b), stmt.position) + } else { + addThing(ConstantThing(arrayName + ".lastindex", NumericConstant(length - 1, 2), w), stmt.position) + } } } }