Design decisions

106. Narrow 1D range-typed array and list elements to 32-bit storage (2026-11-21)

  • Decision. Narrow 1D range-typed arrays and lists ([V]lo..=hi, List<lo..=hi>, and domain-relative bounds [V]0..=V.count / [V]1..=V.count) to std::vector<uint32_t> (when 0 <= lo and hi <= u32::MAX, or domain-relative 0..=V.count / 1..=V.count) or std::vector<int32_t> (when i32::MIN <= lo and hi <= i32::MAX) across globals, locals/params, returns, and struct fields (Program::narrow_elems + scope::narrow_elems). A candidate stays narrow only if every flow (assignments, calls, returns, mut args, struct constructors, closure captures, slices/views, non-natural .sort) lands in a place with the same narrowed element width; any flow into plain [V]Int/List<Int> or mismatched width widens it to ll. Narrowed element reads widen via ll(...) before arithmetic so a[i] * a[j] cannot overflow 32-bit. stdlib/tree.cp's Rooted uses [V]0..=V.count for dep/k0/k1 and [V]1..=V.count for sz (far stays [V]Int), and expect_declared propagates declared field element ranges into [D] _ => ... comprehensions so Marks<D>.stamp ([D]0..=2_000_000_000) also narrows to std::vector<uint32_t>.
  • Why. Extends ranged scalar struct-field narrowing (Decision 55) to 1D arrays and lists, makes the stdlib docs' 4-byte-per-element storage claim (Marks<D>) true, and cuts memory on large trees (bench/trees/root_bench at n = 10^6: Rooted drops dep/sz/k0/k1 from 8 B to 4 B each, peak RSS ~123.7 MB / 0.35 s vs hand-written C++ 69.8 MB / 0.23 s). Stores are already validated by ExprKind::RangeCheck (Decision 100), so checked builds trap on out-of-range writes while release stays zero-cost.
  • Reverse. Return an empty map from scope::narrow_elems in crates/cpl-codegen/src/scope.rs (or clear Program::narrow_elems in crates/cpl-ir/src/lower/mod.rs) to emit all ranged arrays/lists as std::vector<ll>; optionally revert Rooted's dep/sz/k0/k1 fields in stdlib/tree.cp to [V]Int.