lang: Type aggregate loop bindings as read-only

802eb248a1d252f9a5ddf4ced7799f6ba500ad5baf3a03fb73eb9ee54a71363b
A `for` binding of an aggregate element had a mutable pointer type,
although it holds the address of an element of a possibly read-only
container. When the binding crossed the blocks of an inner loop, the
block parameter was mutable while its argument was not, and the
verifier rejected the program.

The binding now has the type of an aggregate parameter: a read-only
address. The loop only reads the element, so no write needs it.

Assisted-by: Claude:opus-5.5
Alexis Sellier committed ago 1 parent 7efe9edd
lib/std/lang/lower.rad +3 -1
8248 8248
                    set rawData = try loadSlicePtr(self, containerReg);
8249 8249
                }
8250 8250
            }
8251 8251
            let mut valVar: ?Var = nil;
8252 8252
            if bindingName <> nil {
8253 +
                // An aggregate element is bound by its address in the container,
8254 +
                // which the loop only reads, as with a parameter.
8253 8255
                set valVar = try newVar(
8254 8256
                    self,
8255 8257
                    bindingName,
8256 -
                    try valTypeOf(self, *elemType),
8258 +
                    try paramTypeOf(self, *elemType),
8257 8259
                    false,
8258 8260
                    il::Val::Undef
8259 8261
                );
8260 8262
            }
8261 8263
            let idxVar = try newVar(
test/tests/for.record.inner.loop.rad added +28 -0
1 +
//! returns: 0
2 +
//! A loop over read-only records binds each record by address and reads its
3 +
//! fields in an inner loop, so the binding crosses the inner loop's blocks.
4 +
5 +
/// Record with an array field.
6 +
record Row: Copy {
7 +
    /// Cells.
8 +
    cells: [u32; 4],
9 +
}
10 +
11 +
/// Sum every cell of every row.
12 +
fn total(rows: &[Row]) -> u32 {
13 +
    let mut sum: u32 = 0;
14 +
    for row in rows {
15 +
        for i in 0 .. 4 {
16 +
            set sum += row.cells[i];
17 +
        }
18 +
    }
19 +
    return sum;
20 +
}
21 +
22 +
@default fn main() -> i32 {
23 +
    let rows: [Row; 2] = [Row { cells: [1, 2, 3, 4] }, Row { cells: [10, 20, 30, 40] }];
24 +
    assert total(&rows[..]) == 110;
25 +
    assert total(&rows[.. 1]) == 10;
26 +
    assert total(&rows[.. 0]) == 0;
27 +
    return 0;
28 +
}
test/verify/expected +0 -1
1 1
alloc.arena.trait Type
2 2
array.pointer Type
3 -
array.repeat.loop Mutability
4 3
array.slice.gen.index Type
5 4
array.slice Type
6 5
bool.comparison.slice.record.gen Slot
7 6
bool.comparison.slice Slot
8 7
bool.comparison.slice.union.gen Slot