for loops

This commit is contained in:
2026-06-22 20:11:18 +02:00
parent 380b5943b3
commit 27f42dd253
15 changed files with 1369 additions and 22 deletions
+7 -5
View File
@@ -101,11 +101,11 @@
- the condition and update may be parenthesized independently for visual clarity
- update targets must already be declared and mutable; loops do not introduce implicit induction variables
- compound assignment (`+=`) remains deferred
- ranges (see section below)
- for loops (operates on iterable sequences). examples:
- ranges (implemented; see section below)
- for loops (implemented; operates on ranges, arrays, slices, and pointers-to-arrays). examples:
- `for items |item| { ... }` - capture just the `item` value in the array/slice (uses copy semantics, i.e. gets a `T`)
- `for items |&item| { ... }` - capture just the `item` value in the array/slice (uses (immutable) reference semantics, i.e. gets a `@T`)
- `for items |&mut item| { ... }` - capture just the `item` value in the array/slice (uses (mutable) reference semantics, i.e. gets a `@mut T`)
- `for (&items) |@item| { ... }` - capture a pointer to each array element; its `@T` / `@mut T` mutability follows the iterable
- `for items_slice |@item| { ... }` - slices already refer to backing storage and support pointer capture directly
- `for items |item, idx| { ... }` - capture `item` and its index index in the array/slice
- `for 0..10 |i| { ... }` - iterate over the range `0..10` (exclusive)
- `for 0..=10 |i| { ... }` - iterate over the range `0..10` (inclusive)
@@ -180,7 +180,9 @@ Ranges represent a sequence of values, commonly used in for loops, and is itself
# 0..n + 1 # ERROR: must parenthesize complex expressions
```
This rule keeps the grammar simple and forces clarity at the call site — no precedence rules to remember. Also, being a value type, ranges can be assigned to variables and passed around like any other value.
This rule keeps the grammar simple and forces clarity at the call site — no precedence rules to remember. Also, being a value type, ranges can be assigned to variables and passed around like any other value. Range bounds are evaluated once, must have compatible concrete integer types, and descending ranges are empty.
For-loop captures are immutable and scoped to the loop body. Sequence index captures are `usize`. Pointer capture uses `|@item|`; arrays must be passed by pointer (for example `&items`), while slices can be used directly. Sentinel elements are not included in iteration.
# A word on distinct types