Fixed arrays and static storage
Status: proposal, documentation only. This contract extends SPEC.md and the M3 static rules; it
is not a claim that the compiler supports these features today. It serves the smallest-first rules
in EMBEDDED.md, the target layout in M0-DESIGN.md, the shared-state model in M3-MMIO.md §2.5,
and the cooperative-task constraints in M6-TASKS.md. The initial useful subset deliberately
avoids resource-bearing elements, general constant evaluation, heap allocation and exposed pointers.
Source contract
[T; N]is an owned, inline fixed array. Add;as a token only within this syntax; existing statements remain semicolon-free.Nis a positiveusizeliteral or a name resolving to aconstof typeusizewith a literal value. Resolve it before layout and monomorphization; reject runtime expressions, negative values, zero, type parameters as lengths, and values not representable in the targetusize. Length is part of type identity. Zero-length arrays are rejected in v1, including in nested types; empty slices remain valid.- Start with scalar
u8,bool,i32,u32,i64,u64,usize,isizeelements. Array of array, struct, enum, slice, handle, arena or other owner elements is rejected in v1. This limits initialization, copy and ownership analysis; expand only with explicit layout and drop rules. - Fixed arrays are not struct fields in v1:
struct Pair { v: [u8; 2] }is rejected at type check with E080, pointing at the[of the field type; use a slice, a static, or a local array instead. [value; N]initializes every element from one compile-time scalar literal or named scalarconstof exactly the element type (context permits fitting integer literals).[e0, e1, ...]is an explicit nonempty list of scalar expressions, evaluated once each left to right; its count determines N and must match any annotation. Both forms require contextual element type in v1. Repeat never duplicates a resource or repeats an effect. Static initializers accept only the repeat form or explicit lists of compile-time scalar literals/constants.constretains its current literal-only definition; no general const arithmetic is added.let a: [u8; 16] = [0; 16]reserves inline fixed-frame storage, initialized on each execution of the declaration;varallows element writes. A missing local initializer, includinglet a: [u8; 16], is an error. No element-by-element definite-initialization exception exists. Frame storage ceases at function return and is charged to the function and call-chain stack.static NAME: [u8; 16] = [0; 16]is immutable andstatic var NAME: [u8; 16]is mutable. Omitted initializer is permitted only forstatic varof the supported scalar/array types and means full zero initialization, includingfalsefor bool; it never means uninitialized memory.static var NAME: [u8; 16] = [1; 16]uses a constant image. Immutable static requires an initializer. All mutable static storage is in RAM: all-zero initial values use.bss, nonzero values use.data; immutable constant objects use.rodata(or read-only mapped equivalent). Storage exists once for the program lifetime, beforemain, not once per call. An explicit all-zero initializer has the same semantics as the omitted initializer. Static scalar support andstatic varspelling match M3;static mutis not Kern syntax.- Follow current module visibility and naming rules:
pubmay expose a declaration only where M3 access analysis can see all users. No user-visible address, pointer cast,&STATIC, whole static-array value, reference to a static element, or implicit conversion of static storage to a slice is allowed. Indexed scalar reads/writes andlen(NAME)are allowed. Immutable statics follow the same no-view restriction for a uniform initial rule.
Representation, operations and ABI
For supported scalar T use the existing slice element representation, not local-slot size:
u8/bool stride and alignment 1; other scalar stride is its target storage size, rounded up to
its alignment, using the existing profile's element layout. On 64-bit hosted targets the latter
uses an 8-byte slot; on 32-bit targets a 64-bit value uses two 4-byte slots and 4-byte element
alignment as in M0. A static array of 64-bit elements has an 8-byte-aligned base under M3; its
8-byte stride keeps each element 8-byte aligned. Local arrays use the ordinary element alignment.
Array size is checked N * stride; add padding when placing an array, never between elements beyond stride.
This extends M0's slot model without changing existing scalar or slice layout. Align every frame
and static base appropriately, and round the full call frame to the target ABI stack alignment.
Do not silently pack other element types or assume a 64-bit value fits a single MCU slot.
len(a) is a compile-time usize constant N (no memory read). a[i] evaluates the index once,
checks i < N before calculating the address, and loads a value; a[i] = v checks the same way
and requires a mutable place. Preserve SPEC's RHS-before-destination evaluation for assignment.
a[lo..hi] for a local array checks lo <= hi <= N with each bound evaluated once, then
produces the existing half-open borrowed []T descriptor, (base + lo * stride, hi - lo).
Empty ranges are valid. for element in a is a read-only iteration in index order; mutation uses
indexed loops. Bounds failure traps with file and line using existing trap semantics, even on MCU;
only proven-redundant checks may be eliminated. len, checked access and subslicing also apply to
borrowed array parameters. Arrays are not slices: they own inline storage, have type-level length,
and do not gain an implicit allocation or an implicit slice conversion.
Arrays are owned values. Whole-array initialization and assignment transfer ownership and
invalidate the source, as with existing owners; any future array return must do the same; the implementation copies the inline bytes to the
destination without allocation. Array values need no free; automatic storage ends with its scope.
This is a logical move, not permission for an old view to survive. &mut a[i] is a scoped exclusive
borrow of a local element; immutable array views and exclusive element or slice borrows follow the
existing provenance and overlap checks. Conservatively treat dynamically indexed elements and
sub-slices as overlapping the whole array in v1. A live view prevents moving the array, mutation
that conflicts with it, and its escape beyond the owner's lifetime; a view returned from a function
must be derivable from an allowed input borrow, never a local. Mutable sub-slice access requires an
explicit exclusive borrow in the existing &mut call convention; no writable alias is manufactured
from an immutable slice. Prove supported borrow cases with ownership fixtures before enabling them.
Function array parameters use the existing source convention: a: [T; N] borrows read-only,
a: &mut [T; N] borrows exclusively, and a: own [T; N] consumes with move a. Lower borrowed
parameters to one internal pointer to the inline object, with length known from the type; this is a
Kern ABI rule, not the AAPCS rule for a C array parameter. Lower own by-value only after reserving
and copying into a distinct callee-owned destination; reject own array parameters and array
returns in v1, regardless of size, rather than silently passing a shared pointer or creating a
large hidden frame copy. Ordinary locals can move between equally typed locals if frame budget allows.
&mut a[i] uses the same scalar-reference ABI as existing references. On Thumb, these internal
pointers consume r0–r3 then stack under the M0 AAPCS convention; preserve 8-byte stack alignment
and the existing result/error conventions. Existing Thumb MVP currently rejects reference
parameters and stack arguments; implement or explicitly reject each before accepting such programs.
Hosted backends use their existing target calling conventions. No C ABI interoperability is promised.
Static access, interrupts and tasks
Treat each static array as one indivisible access cell for M3's transitive per-context analysis,
including accesses through called functions; distinct indices do not imply disjointness. static var
may contain only supported scalars. No static view, &mut element, returned reference, captured
reference, or reference stored in an arena is permitted, even inside critical. Direct read/write
is the only access. Per M3 §2.5, task-context accesses need critical if any handler accesses the
cell; handler accesses need it if any other handler accesses it. A single access context requires
none. Immutable statics are read-only everywhere, including contracts. This contract does not
make critical optional where M3 requires it, nor add a raw-pointer escape.
M6 §2.7 extends M3: a static var reached from two task contexts, or from a task and a
handler, requires critical around every access; one task context alone needs none. critical
forbids yields and loop polls, so it also protects task-to-task compound operations that must remain
atomic. Multi-access invariants must stay within one critical section; protecting individual accesses
does not make a sequence atomic. Context and transitive call summaries must enforce this rule. No
static borrow can cross a yield because no static borrow is permitted at all.
Initialization, limits and code generation
All accepted reads observe initialized elements. Local list/repeat initialization must finish before
binding becomes readable; a failing expression traps and cannot expose a partially initialized array.
Statics have constant images only; no constructors, lazy initialization, allocation or user code in
startup. Reject N * stride, alignment, offsets, image sizes or address additions that overflow the
target address space or file format; reject objects that do not fit the selected memory profile,
including .data, .bss, alignment, heap, reserved task/ISR stacks and main stack. Flash accounting
includes vectors, text, rodata, padding and the .data load image. RAM accounting includes .data,
.bss, padding and all reserved stacks; enforce disjoint ranges and stack collision checks.
A local occupies ceil(aligned_bytes / target_slot_bytes) frame slots, not one slot for the array
header. Include parameters, padding and all existing local allocations in the calculation. For the
current native Thumb emitter, reject when profile.frame(total_bytes) > 504, including after ABI
rounding: this is the existing 126 four-byte-slot limit, not 126 arrays or 126 bytes. Also enforce
the target's stack/call-chain budget where available. Large arrays belong in statics; no compiler
fallback to an arena. If a later backend extends frame addressing, changing this cap is a separate,
tested change, not implicit permission to exceed board RAM.
Hosted AArch64/x64 emit aligned frame objects, normal OS image sections and checked indexed
loads/stores. Use the platform's normal executable relocation/addressing model; PIC/ASLR requirements
remain intact. Hosted .bss is zero-filled by the loader. On bare metal emit a flash load image for
.data, its RAM execution address, and NOBITS .bss; reset copies exactly the data range then
zeros exactly the bss range before main, with no overlap with stack. Do not rely on a QEMU ELF
loader's RAM initialization as a substitute for reset: test a cold, deliberately nonzero RAM image.
For fixed-address Thumb-2 images resolve symbols at image construction: emit movw/movt low/high
halves for RAM or flash addresses and perform checked internal fixups. The final executable has
no runtime relocations, GOT, dynamic loader or literal-pool range dependency; assembler/image fixups
at build time are expected and are not runtime relocations. Check address range and alignment, and
use byte loads/stores for u8/bool, correct multiword operations for 64-bit elements. RV32 needs
its own resolved address sequence and equivalent alignment, checks and reset contract; this design
does not claim the native RV32 backend exists. Bounds failure calls the existing board trap/exit
path, not an OS syscall. Code and data emission order, padding and symbols must be deterministic.
Current src/thumb_gen.rs and compiler/src/thumbgen/subset.kn reject bracket syntax; their reset
path calls main directly. The direct ELF32 writers already describe RAM .data/.bss, but their
current QEMU-oriented RAM segment is not by itself a real flash load image plus reset copy. Extend
both writer and startup together, including program headers/load addresses and budget checks; test
both -kernel behavior and the real flash/RAM contract. The direct assembler already resolves
#:lower16:/#:upper16: symbols. Stage0 and self-hosted compilers must agree on acceptance,
diagnostics, layout, semantics and generated output. Require byte-identical assembly and ELF for
the same native target/profile where the existing native parity gate requires it; do not require
unrelated hosted targets or different compiler versions to produce identical machine code. Existing
non-feature hosted golden hashes must remain unchanged, or any deliberate change be separately
explained and approved in its implementation change.
No-heap sieve acceptance program
The following is proposed Kern, not runnable with the current compiler. It uses M3's spelling
and a single task context. It counts primes below 4096; zeros mean potentially prime. It requires
print/print_int on the QEMU semihosting console and no heap capability.
const LIMIT: usize = 4096
static var FLAGS: [u8; LIMIT]
fn main() {
var i: usize = 2
while i * i < LIMIT {
if FLAGS[i] == 0 {
var j = i * i
while j < LIMIT {
FLAGS[j] = 1
j += i
}
}
i += 1
}
var count: usize = 0
var last: usize = 0
for k in 2..LIMIT {
if FLAGS[k] == 0 {
count += 1
last = k
}
}
print_int(count)
print(" primes, last ")
print_int(last)
print("\n")
}
Expected QEMU stdout, exactly 564 primes, last 4093\n, and successful exit; this is an acceptance
expectation, not a measured run. FLAGS costs exactly 4096 bytes of .bss and zero initializer
bytes in flash; heap = 0. For an STM32F103-style 20 KiB RAM / 64 KiB flash profile with a 2 KiB
main stack, the fixed subtotal is 6144 bytes RAM, leaving 14336 bytes for any ISR stack, other
statics, padding and reserve. Flash is text + vectors + rodata + data load image: the design sets a
provisional <= 8 KiB flash gate, to be measured, not a claim of current size. Use the M3 QEMU
profile's declared 4 MiB RAM/flash and stack reserves for CI; validate the real 20 KiB profile with
its actual linker map. The 50,000,000-byte hosted benchmark cannot fit either the 20 KiB board or
that QEMU profile. This 4096-byte example matches the existing C size reference, exercises indexed
mutation, reads, bounds, startup zeroing and static sizing, and demonstrates useful work without a
hidden allocator. Reset FLAGS before a second invocation if the example is later made callable twice.
Impact map
| Surface | Required implementation work |
|---|---|
src/ast.rs, lex.rs, parse.rs | Array type/length and literal nodes, semicolon token, static declarations, symbol resolution, const lengths and locations. |
src/check.rs, ownership.rs, generic.rs, walk.rs | Type identity/layout validation, static initializer rules and visibility, ownership/move/view paths, M3 context/effect checks, traversal and clone/monomorphization. |
src/gen.rs, src/gen/*, src/x64.rs, src/a64.rs, src/thumb_gen.rs, src/thumb.rs | Inline frame storage, initialization/copies, checked places/ranges, target ABI and section/address emission; Thumb startup, instruction/fixup support. |
src/profile.rs, src/layout.rs, src/elf32.rs, src/elf.rs, src/macho.rs | Per-target element/array layout and frame reporting, section alignment and flash/RAM load mapping; image and memory budgets. |
src/format.rs, src/rules.rs, src/test_hash.rs | Round-trip new syntax; declaration naming/structure; stable semantic test hashes and dependency/affected-test invalidation including const changes. |
compiler/src/parser, syntax, model, lexer | Mirror syntax, declaration records, walkers, type identity and token handling; syntax is a walker over model records, not a separate parser. |
compiler/src/typing, ownership, generic, effects, contracts | Mirror checking, region provenance, context safety, const resolution and diagnostics. |
compiler/src/backend, thumbgen, thumb, elf32, image | Mirror hosted/native places, frames, bounds, initializers, sections, fixups and startup; ELF load addresses and deterministic image ordering. |
compiler/src/format, rules, testhash, api, inspect, layoutreport | Formatter/rules parity; test dependency hashing, public API type spelling and static mutability; correct sizes and diagnostics. |
| Tests, docs and API | Parser/formatter, type/ownership rejection, runtime/traps, image inspection, board budgets, QEMU cold boot, hosted goldens, self-host parity; update SPEC.md, kern api and public language docs as implementation lands. |
Alternatives
| Choice | Result |
|---|---|
| Arena only (today) | Explicit lifetime and useful variable-capacity data, but current arena requires an allocation provider and cannot express a statically reserved 4 KiB buffer on a no-heap target without new backing-storage machinery. |
| Static alone | Direct fixed buffers solve the demo, but no reusable fixed-frame value or array type for drivers and APIs; static syntax still needs a coherent element layout and checks. |
| Fixed arrays as sugar over a hidden arena | Adds hidden allocation, initialization and lifetime/aliasing failure modes; violates bounded, no-heap semantics. Reject. |
| Inline fixed arrays plus explicit statics | Recommended: one representation and bounds model, fixed frame for small temporary values, explicit one-time storage for large buffers. Ship the restrictions above first. |
Phases and gates
Each phase has matching stage0 and self-host work before it is called complete; when bootstrapping, land gated intermediate work without advertising support. Existing feature and non-feature tests remain green. New diagnostics must match in code, location and meaning across compilers.
- Syntax and type. Parse/format both literals, lengths and declarations; type identity, const
resolution, scalar restriction and full initialization. Positive parse/round-trip fixtures;
reject runtime N, non-
usizeconst, zero, overflow, unsupported element and missing local initializer/uninitialized read. No target silently accepts unsupported execution. - Hosted layout. Frame arrays, repeat/list initialization, moves, checked indexing/assignment, local sub-slices and iteration on AArch64/x64. Check byte/word stride, alignment, evaluation order, bounds including empty sub-slices, move-after-view and conflicting borrows; reject array by-value parameters/returns and dangling local view. Verify existing hosted golden hashes.
- Native codegen. Implement supported local subset and checked element access in both Thumb generators; test 504-byte rounded frame boundary and oversized rejection, byte and word indexing, traps and no external assembler. Borrowed parameter support is accepted only when its ABI is implemented; otherwise reject it. RV32 requires its own equivalent implementation and tests.
- Static and startup. Constant images, sections, deterministic addresses and memory budgets on hosted and Thumb; test mutable zero/nonzero and immutable values across calls, cold boot copy and zero with poisoned RAM, alignment, image headers, flash/RAM overflows, no runtime relocations, ISR/critical context rules and rejection of every escaping static view or reference. Test a real flash load image, not only a loader-initialized RAM segment.
- No-heap sieve. Build the exact program above with
heap = 0; inspect map and generated image for no allocator, assert.bssand stack/flash budgets, run QEMU and compare stdout/exit. Exercise out-of-bounds separately. Validate RV32 only when its backend and runner support the same contract. - Self-host parity. Run
.cip/build-kern.sh,.cip/unit.sh,sh tests/run.sh --host-only build/kern,.cip/features.sh build/kern,sh scripts/mcu-native.sh, andsh tests/test_selfhost_cli.sh build/kern-stage0 --host-only; extend native corpus with the new cases and compare stage0/self-host assembly and ELF bytes, diagnostics and deterministic repeated builds. Add formatter, API, affected-test and golden fixtures. Record actual commands, target profile, hashes, output, section sizes and measured budgets; no QEMU pass implies physical board qualification.
Decisions to confirm
| Decision | Recommendation | Consequence |
|---|---|---|
| Literal spelling | Both [value; N] and [e0, e1], with a contextual element type | Small repetitive and explicit initializers; semicolon is a type/literal delimiter only. |
| Zero length | Reject arrays of length zero in v1 | Simpler distinct storage and borrowing; zero-length slices still work. |
| Zero default | Only omitted static var defaults to zero; locals and immutable statics require initialization | No uninitialized reads or hidden per-call zeroing. |
| Mutable static spelling | static var, consistent with M3 | Access-context and no-view rules apply; static mut is rejected. |
| By-value parameters/returns | Reject in v1; borrowed arrays use an internal pointer | No unbounded hidden copies or ABI ambiguity; add owned transfer only with explicit stack and ABI tests. |
| Sub-slices | Permit checked, scoped local-array views; ban all static views | Reuses slice ABI and ownership checks without leaking shared static state across critical sections. |
| Types | Scalar elements first, including properly aligned wide scalars | Covers buffers and counters while avoiding aggregate/resource lifetime semantics. |