Kern
On this page

M0 — 32-bit target model design

Status: design for EMBEDDED.md phase M0 (EMBEDDED.md:96). Documentation only; no code in this change. The plan text says M0 is "32-bit target model, usize, i32/u32, 4-byte slots, capability diagnostics" and its acceptance is kern check rejecting files/processes on --target thumbv7em-none with E170.

Today the language is 64-bit only: Ty has I64/U64/U8/Bool/Slice/Struct (src/ast.rs:5), every value is one or two 8-byte words (src/gen.rs:328), every address is 8 * word (src/gen.rs:78, src/gen.rs:339, src/gen/stmt.rs:308), and SPEC.md:3-4 states "All targets use little-endian, 64-bit words."

This document fixes the model, the ABI, the change surface, the order of work, the diagnostic namespace, and the acceptance gates. It deliberately does not describe how to encode Thumb-2 or RV32 (that is M1/M5) and does not change any .kn semantics.


0. Decisions at a glance

#QuestionDecision
D1usize/isizeNominal types, width = target word (32 or 64). Not aliases of u32/u64.
D2i32/u32Nominal, available on every target; on 64-bit they occupy one 8-byte slot.
D3i64/u64 on 32-bitKept, emulated as two words; wide = off profile switch for small boards (E175).
D4Pointer-sized spellingusize is the only word type in source: len, indexes, ranges, capacities, arg_count.
D5SlotSlot = one target word. 64-bit: 8 bytes (unchanged). 32-bit: 4 bytes.
D6Slice(ptr, len) = 2 slots; len is usize on both targets.
D7LayoutOne scalar per slot, no packing, no padding; alignment = slot size. 64-bit layout is unchanged.
D832-bit ABIAAPCS: r0-r3 then stack, sret in r0, result r0:r1, error flag r2, 8-byte frame alignment.
D9CastsChecked value conversions on every target; narrowing traps, never truncates.
D10Capabilitieskern.target grants a fixed set; the pass lives in src/check.rs + compiler/src/typing; E170-E175 now, E176-E179 reserved.
D11Hosted outputFrozen tests/golden/ hashes of kern asm on 3 targets must not change, including across the usize migration.
D12Target namesthumbv7m-none, thumbv7em-none, riscv32imac-none; the existing three keep their names.

1. Type model

1.1 The three candidate models

ModelSlice on MCUCostVerdict
A. Keep u64 as the word(ptr64, len64) = 16 BEvery index/length compare, add and range is emulated 64-bit; two words per length; 64-bit slot even where 32 bits sufficeRejected. Violates EMBEDDED.md:40-41 and the "bounded by construction" rule (EMBEDDED.md:28): a 20 KiB part spends twice the RAM on every slice and every length.
B. usize as a target alias (usize ≡ u64 on 64-bit, ≡ u32 on 32-bit)(ptr32, len32) = 8 BZero source migration; one meaning per targetViable, but the same source changes width silently, kern api and diagnostics print target-dependent types, and nothing stops a 64-bit counter from entering index math on MCU.
C. usize/isize nominal(ptr32, len32) = 8 BOne mechanical migration of existing sources that annotate lengths/indexes as u64Chosen.

1.2 Recommendation and justification

Introduce usize and isize as first-class nominal types whose width is a property of the target profile, and i32/u32 as ordinary fixed-width types. usize is 32 bits on thumbv7m-none/thumbv7em-none/riscv32imac-none, 64 bits on the three hosted targets.

Against the ten rules (EMBEDDED.md:26-47):

  1. Bounded by construction (rule 1). A slice becomes 8 bytes and an index compare becomes one instruction. Model A spends 16 bytes per slice and ~2 instructions per bounds check on a part with 20 KiB of RAM.
  2. Static memory is the default (rule 2). []usize has 4-byte elements on MCU: a 4096-entry offset table costs 16 KiB with word indices and 32 KiB with 64-bit ones, on a part with 20 KiB in total.
  3. 32-bit first (rule 7). The rule names usize explicitly: "on MCU targets the pointer and usize are 32 bits, slots are 4 bytes, and slices are (ptr32, len32)". Model B honours the width but not the name: a program that says u64 gets 32-bit behaviour, which is exactly the C size_t trap the project exists to avoid.
  4. Capabilities, not platforms (rule 8). The usize migration is also the audit that finds every place a length is treated as a 64-bit quantity — the same places a capability check has to reason about (buffer sizes, read_file results, arg_count).
  5. Errors are values / no hidden cost (rules 4-5). A nominal type lets the checker reject let n: u64 = len(s) everywhere, instead of only on the target where it is expensive. The error is the cheapest possible time to learn it.

The cost is real and must be paid once: existing sources that write var i: u64 = 0 and compare it with len(s) become usize. In this repository that is examples/slices.kn:12,21,35,55,74,115,134,143, compiler/src/** (348 len( call sites, 272 for … in u64(0)..), tests/**. It is mechanical, it is verified by the existing 414-case harness, and on 64-bit targets it produces byte-identical assembly because usize and u64 have the same representation there (see §4.1). Model B would postpone this work and pay it again later with interest, on a larger code base.

isize is introduced in the same step for symmetry (isize = signed word). Nothing in the runtime needs it yet — the language has no pointer subtraction — so M0 only has to make it parse, lay out, and convert. Deferring it would leave usize without a signed counterpart and force a second breaking change when a signed word is needed (e.g. a seek-style API).

1.3 Width table

Type64-bit target32-bit targetNotes
u8, bool1 byte as a slice element; 1 slot as a local/fieldsameesz already special-cases this (src/gen.rs:326)
i32, u321 slot (8 B); value kept canonical in the slot1 slot (4 B)D2, D7
usize, isize1 slot (8 B)1 slot (4 B)D1
i64, u641 slot (8 B)2 slots (8 B), low word firstD3
pointer (internal)1 slot1 slotnever in source
slice2 slots (16 B)2 slots (8 B)(ptr, len)
Arena3 slots (src/parse.rs:45)3 slotsheader words are all word-sized
Handle[T]2 slots (src/parse.rs:45)2 slots
structsum of field slotssum of field slotsno padding (src/parse.rs:763-789)
enum1 + largest payload1 + largest payloadsrc/parse.rs:779-785

SPEC.md:34-37 and the example block at SPEC.md:42-45 must say that pointer-sized integers are written usize/isize, and that 64-bit integers remain available on every target.

1.4 i64/u64 on 32-bit: what it costs

They stay available (rule 7: "i64/u64 remain available but are not the default"). The cost is concentrated in five places:

Operation32-bit cost
add / sub2 instructions (adds+adc, subs+sbc) plus the overflow branch; 2x the flags work
compare2 instructions (cmp + sbc/sbcs); a bool result needs a conditional sequence
multiplyumull/smull (2 cycles on M4), or __aeabi_lmul on M3 — ~40-80 B of linked code
divide / modulo__aeabi_ldivmod — ~120-250 B of linked code, ~100 cycles; M3 has no hardware divide at all
storage2 slots in every struct/slice element; 2 argument words (the 6-word limit, src/gen/stmt.rs:296, is reached twice as fast)

Therefore: implement i64/u64 on 32-bit in M1 as a separate two-word codegen path with library calls for mul/div/mod, and give the profile a wide flag. Default wide = on; wide = off rejects 64-bit integers at type-check time with E175 so a 64 KiB board can opt out with evidence from kern size (O2). clock_ns() -> u64 (SPEC.md:205) is the one runtime API that genuinely needs 64 bits; it is a hosted capability and unavailable on none targets, so it does not force wide = on.

1.5 How pointer-sized values are written

One rule, no exceptions: a value that is a count of bytes, elements, slots or addresses in the target is usize. Concretely, after M0:

  • len(slice) -> usize (src/check.rs:380 today returns U64).
  • arg_count() -> usize (src/check.rs:303).
  • alloc[Element](count: usize) and alloc(count: usize) (src/check.rs:383).
  • arena(capacity: usize), arena_alloc[Element](&mut a, count: usize) (src/check.rs:136, src/check.rs:149).
  • truncate(move owner, length: usize) (src/check.rs:375).
  • s[index: usize], s[lo..hi: usize] (src/check.rs:451, src/check.rs:457-458).
  • for i in lo..hi — both limits become usize (today any integer: src/check.rs:641-651).
  • for x in s — the hidden cursor and length are usize (today U64: src/check.rs:638-639).

Builtins that exist only on hosted targets keep their current signatures (spawn_process -> i64, clock_ns -> u64, file_kind -> u64, process_id -> i64, exit_process(i64), src/check.rs:286-350). They are unreachable on none targets by construction (§5), so their width is not an MCU concern and changing them would be churn.

i64(value), u64(value), u8(value) gain siblings i32, u32, usize, isize (SPEC.md:75, table at src/check.rs:395).

1.6 Canonical value invariant (needed by both backends)

Every scalar in a slot is canonical after every operation:

  • u8, u32, usize: zero-extended to the slot width.
  • i32, isize: sign-extended to the slot width.
  • i64 on 32-bit: a pair (lo, hi) of 32-bit words in little-endian order, lo at the lower address.

Both hosted backends get this almost for free: AArch64 W-register writes zero the top 32 bits (src/gen.rs:17, AW), and x86-64 32-bit writes zero the upper half (src/x64.rs:22-29 already maps eax/width 32). A signed 32-bit value needs the matching sxtw/movsxd at the point it enters a 64-bit slot. This invariant is what makes usize ≡ u64 codegen identical on 64-bit targets (§4.1), and it is why 32-bit comparisons and bounds checks can reuse the existing 64-bit cmp/jcc paths unchanged: a canonical value compares correctly at either width.


2. ABI and layout

2.1 Slot model

A slot is one target word. The profile supplies it:

profile.word_bytes      = 8 on macos-arm64 | linux-arm64 | linux-x64
                        = 4 on thumbv7m-none | thumbv7em-none | riscv32imac-none
profile.stack_align     = 16 (64-bit, today: src/gen/stmt.rs:308, compiler/src/backend/state.kn:14)
                        = 8  (32-bit AAPCS)
profile.arg_words       = 6 (both; AA32 passes the rest on the stack)

The five functions that must become profile-aware (the whole seam):

Seam64-bit today32-bitWhy it is the seam
shift(p, words)o + 8*wo + 4*wsrc/gen.rs:78; every field/element address
alloc_mem(words)mem += 8*wordsmem += 4*wordssrc/gen.rs:339
esz(type)8*words except u8/bool4*words except u8/boolsrc/gen.rs:326; slice stride
words(type)slice 2, struct words, else 1same, plus i64/u64 = 2src/gen.rs:328, src/parse.rs:771
frame rounding(mem + 8*next + 15) & !15(mem + 4*next + 7) & !7src/gen/stmt.rs:308

Everything else is expressed in words and stays correct if those five are correct.

2.2 Composite layout

  • Struct: fields in declaration order, each at the next slot boundary, no padding, no reordering. offs stays a word index (src/ast.rs:55, src/parse.rs:767-786); only the byte multiplier changes.
  • Enum: slot 0 is the variant index, payload starts at slot 1, size = 1 + largest variant (src/parse.rs:779-785). Unchanged on both targets.
  • Slice: 2 slots. ptr is a real 32-bit address on MCU; len is a usize and can never exceed 0xFFFF_FFFF, which is a free invariant on MCU (no object is larger than RAM).
  • Alignment: alignment of a type = its slot size, capped at the word. On 32-bit everything is 4-byte aligned, including i64. Never emit LDRD: two LDRs are as fast on M3/M4 and avoid the pair alignment rule entirely.
  • Arena: header is 3 slots (src/parse.rs:45). Its internal 8-byte alignment mask (src/gen/arena.rs:27, src/gen/arena.rs:161: and x11, x11, #-8) becomes the word mask on 32-bit. SPEC.md:145-146 ("aligned to eight bytes") changes to "aligned to the target word".

Consequence, stated openly: a struct { a: u32, b: u32 } is 16 bytes on 64-bit and 8 bytes on 32-bit, and []u32 has 8-byte elements on 64-bit. That is the existing "one scalar per slot" rule with a per-target slot, not a new packing rule. Byte packing is decisions D-D and D-G in §7.

2.3 Calls, arguments, returns, traps

Item64-bit (unchanged)32-bit
integer argsx86 rdi,rsi,rdx,rcx,r8,r9; ARM x0-x5 (src/gen.rs:25-32); ≤6 words, E092 (src/gen/stmt.rs:296, src/gen/expr.rs:425)AAPCS r0-r3, then caller stack; ≤6 words, same E092
slice arg2 words2 words (2 registers)
aggregate argby reference (&mut/is_ref)same
aggregate returnhidden pointer: x8 on arm64 (src/gen.rs:32), rax on x64 (src/gen.rs:27; the caller emits mov rax, rsp before the call)hidden pointer in r0 per AAPCS (D-E); r0 is then unavailable, so at most 3 argument words stay in r0-r3 and the rest go on the stack (the 6-word source limit does not change)
scalar/slice returnx0:x1 or rax:rdx (src/gen/expr.rs:506-515)r0:r1
fallible flagx2 / r11 (src/gen.rs:32, src/gen.rs:27)r2
trapcold stub per (kind,file) calling kern_trap with write+exit syscalls (src/gen/runtime.rs:34-47)one kern_trap_hook(kind: u32, line: u32) board hook; text table in .rodata
callee-savedx19-x28 saved in pairs (src/gen/stmt.rs:326-341)r4-r11 saved with stmdb/ldmia

The 6-word source limit is kept on all targets even though AA32 can spill, for two reasons: the 64-bit output must not change, and 6 words is enough for two slices plus two scalars — more than any MCU call in the plan. Raising it is a separate, additive change (§7 D-H).

For M1 the code generator emits Thumb-2 assembly text and --cc (src/main.rs:191-206) hands it to clang --target=armv7em-none-eabi -ffreestanding -nostdlib -T <script>. No new encoder is required in M1; src/a64.rs, src/x64.rs, src/macho.rs and src/elf.rs stay 64-bit-only until M5.

2.4 Checked arithmetic on 32-bit

The trap set does not change: overflow, bounds, assert, div, cast, precondition, postcondition (src/gen.rs:38). Per width:

Typeadd/submuldiv/modshift
u32, usizeadds/subs + b.csumull + high-word zero checkudiv (M4) or __aeabi_uidiv (M3); trap on 0trap on count ≥ 32
i32, isizeadds/subs + b.vssmull + asr #31 comparesdiv/__aeabi_idiv; trap on 0 and on MIN / -1trap on count ≥ 32
u8adds + compare 255 (unchanged, src/gen.rs:266)mul + compare 255as todaytrap on count ≥ 8
i64/u642-word adds+adc / subs+sbc + carry/overflowumull/smull pair, library call if neededlibrary calltrap on count ≥ 64

SPEC.md:184 ("trap on counts >=64") becomes "shift counts must be less than the width of the operand type". Bit builtins (SPEC.md:182-184) become generic over the unsigned integer types (u8, u32, usize, u64) with both operands required to match, instead of u64 only. Both are normative SPEC changes and each needs a trap fixture per width.

2.5 Casting rules

Casts stay checked value conversions (SPEC.md:75-77): a cast either preserves the value or traps with cast at the source location. There is no truncating cast and no bit reinterpretation in the language; MMIO and hashing use explicit bit_* builtins instead.

From → ToResult
widening unsigned (u8→u32/usize/u64, u32→u64)never traps
widening signed (i32→i64, isize→i64)sign-extend, never traps
narrowing (u64→u32, i64→i32, usize→u32, u32→u8)traps if the value is out of range
signed→unsigned of any widthtraps if negative (today: src/gen/expr.rs:370-374)
unsigned→signed of any widthtraps above the signed maximum
usize ↔ u32identity on 32-bit, range check on 64-bit
usize ↔ u64identity on 64-bit, range check on 32-bit

Two consequences to state in SPEC: (a) a program that casts a 64-bit value to usize is portable only if the value fits 32 bits, which is exactly what the MCU can represent; (b) u8(x) on x86-64 currently compares against 255 (src/gen/expr.rs:368-374) — the same code path generalises to every narrowing.

2.6 Overflow and literal rules

  • The default type of an unannotated integer literal becomes the target int: i64 on 64-bit (unchanged, src/check.rs:253), i32 on 32-bit. Literal adaptation already pushes the expected type down (src/check.rs:218-224), so this only affects let x = 0 and similar inference.
  • Literal range checks (src/check.rs:254, src/check.rs:736, compiler/src/typing/expressions.kn:151-166) gain I32, U32, USIZE, ISIZE arms; usize literals are checked against the profile width, so let a: usize = 4294967296 is E022 on MCU and fine on 64-bit (a target-dependent fixture, §6).

3. Impact map

3.1 stage0 (src/, Rust bootstrap compiler)

FileWhat is thereChange64-bit-only?
src/lex.rskeywords, literals (src/lex.rs:45-63)none — type names are identifiersn/a
src/ast.rsTy (:5), is_int (:9), StructDef.offs/words (:55)add I32, U32, Usize, Isize; is_int; new is_signed, is_wordno
src/parse.rstype names (:93), builtin Arena/Handle words (:45), layout (:763-789)accept four names; layout takes word_bytes and counts i64/u64 as 2 on 32-bitno
src/check.rs54 builtin ids (:4-57), io_builtin (:67), tyname (:82), literal default (:253), builtin signatures (:286-350), casts (:395), len (:380), index/range (:451-458), check (:694)len/alloc/index/range → usize; cast table +4 rows; literal ranges; new caps pass (§5)no
src/gen.rsTarget (:6), arch (:22), shift (:78), cc (:91), arith (:242-320), esz (:326), words (:328), alloc_mem (:339), runtime gating (:477-480)new Target variants + Profile; 22 sites hard-coding == Ty::I64 become is_signed(ty); width-aware arithno (must stay bit-identical for hosted)
src/gen/stmt.rsfunc (:270), arg limit (:296), sret (:301), frame (:308), range sign (:242), word copy (:185)profile slot bytes; i64 two-slot store/load; signedness from type, not == I64no
src/gen/expr.rsmwords (:272), call (:302), casts (:365-380), E092 (:425), print_int choice (:483), return registers (:506-515)new cast rows; i64 pairs; print_int by widthno
src/gen/arena.rs8-byte alignment masks (:27, :161)word alignment from profileno
src/gen/runtime.rskern_trap/kern_print with write/exit (:34-47), print_i64/u64 (:57-73)add a none runtime (hook, no syscalls); 32-bit print helpersnew file
src/gen/os.rs, system.rs, process.rs, directory.rssyscall runtimes, currently emitted on demand (src/gen.rs:477-480)no change; they must simply never be emitted for none64-bit only
src/gen/jit.rs, src/test_mem.rsmacOS in-memory image (mmap/dlsym)no change64-bit only
src/a64.rsA64 text assembler (:525)none for M0: it is already width-generic (sf at :42, W-register immediate check at :265) and accepts the w forms i32 needs64-bit only until M5
src/x64.rsx86-64 text assembler (:384), 64/32/8-bit widths (:22-29)none for M064-bit only until M5
src/macho.rsMach-O arm64 writer (:1-6)none; must reject embedded targets with a clear messageyes
src/elf.rsELF64 writer, machine 183/62 (:72-74), write_exe (:122)none in M0; M5 adds ELF32 + EM_ARM=40/EM_RISCV=24364-bit only until M5
src/project.rsloader (:18-40), ty_str (:283)read kern.target next to kern.rules; print usize in api signaturesno
src/rules.rs53-rule table (:12-13), Cfg (:124)no change. Capability errors are not rules; rules are disableable (SPEC.md:241) and capabilities must not beno
src/format.rstoken-based printer (:38)no change — usize is an identifierno
src/main.rscompile (:48-53), host (:68), usage (:73), spec (:79-81), --target (:95-105), output path (:177-186), cc flags (:191-206)parse 3 new targets; thread the profile into front/check; split compile so check stops generating assembly (today gen::gen runs at :52 before the check branch at :176, so check cannot work on a target without a backend); new layout subcommand; a clear "codegen lands in M1" error for noneno
src/test_hash.rscall graph (:159), builtin map (:167)reuse for E174 (recursion) and as the input to the caps passno
tests/run.sh (3 targets), errors/, traps/, wide/, feature suitesnew tests/embedded/ + tests/run_embedded.sh; new fixtures (§6)—
SPEC.md:3-4 words, :34 types, :75 casts, :184 shifts, :215 target ids, :227-231 CLIrewrite these six passages—

Type surface size, for planning: ~217 Ty:: match sites across 13 files (check.rs 88, ownership.rs 29, parse.rs 23, gen/expr.rs 17, gen.rs 14, generic.rs 12, gen/stmt.rs 10, test_hash.rs 6, project.rs 6, rules.rs 5, contracts.rs 4, ast.rs 2, test_audit.rs 1). Adding four variants is mostly exhaustive-match arms; only gen* needs semantics.

3.2 Self-hosted compiler (compiler/src/)

PathWhat is thereChange64-bit-only?
model/kinds.knI64=2, U64=3, U8=4 (:3-11)append I32=12, U32=13, USIZE=14, ISIZE=15; never renumber (test hashes include kinds, testhash/types.kn:75)no
model/records.knType.words/bytes (:107-109)keep both; bytes becomes profile-dependentno
parser/types.kntype names (:113-125)four new spellingsno
typing/layout.kninteger_type (:14), bytes = words * 8 (:60), field_layout (:66-88)bytes = words * word_bytes; i64/u64 = 2 on 32-bitno
typing/expressions.knliteral fits (:151-166), index/subslice U64 (:91-95), default I64 (:151)new ranges; usize for indices; target int defaultno
typing/builtins.kncast mapping (:36-51), LEN/bit/kind → U64 (:95-99)LEN/ARG_COUNT → USIZE; +4 cast ids at the end of builtins/names.kn (IMAGE_CLOSE = 1073741877)no
typing/statements.knfor cursors U64 (:101-102)USIZEno
typing/check.knpass list (:5-60)call the new caps pass after the function loop; reuse testhash/graph.kn:158 components for E174no
backend/state.kntarget ids (:6-10), STACK_ALIGNMENT/FRAME_HEADER (:14-16), allocate words*8 (:90-101), frame_size (:105)target id ↔ profile table; slot bytes; alignmentno
backend/functions.knparameter words, + word * 8 (:59), 6-word limit (:66-79)slot bytes; profile arg wordsno
backend/calls.knarguments + position * 8 (:43,46,73), element bytes (:161-180)slot bytesno
backend/expressions.knfield/index offsets (:46-47,95,113)slot bytesno
backend/machine.knbyte_register (:193), copy_slots (:206-211), argument_register (:252-279), result_register (:280), error_register (:293)add the 32-bit register set (r0-r12, lr, sp) and AAPCS orderno
backend/arithmetic.knsigned/width decisions (158 lines)width-aware; i64 pair pathno
arm64/*.kn (9 files), x64/*.kn (6 files)assembly text emitters; arm64/model.kn:5-11 already carries widthno change for M0; a thumb emitter is new in M164-bit only
native/build.kntarget dispatch (:12-24)reject none targets with "code generation lands in M1" (not E170)64-bit only
elf/build.knmachine/class (:54-60)unchanged until M5 (clang links M1)64-bit only
macho/build.kn(:4)unchangedyes
options/parse.kntarget names (:73-76,146-157), target() > 2 guard (:76)three new names; explicit_target for kern.target precedenceno
driver/compile.knassembly (:95), host-target run guard (:156), banner (:211-214)profile plumbed to backend.generateno
toolchain/build.knclang flags per target (:39-67)--target=armv7m-none-eabi / armv7em-none-eabi / riscv32-unknown-elf, -ffreestanding -nostdlib -Tno
spec/print.kn19 chunks, 447 linesregenerate from the new SPEC.md (byte-compared by tests/test_selfhost_cli.sh:30-31)—
rules/*.kn53 rulesno changeno
testhash/types.knhashes words/bytes (:92)unchanged data; see testcache noteno
testcache/cache.knversion hash: compiler + timeout + flags (:79-102)add the target id to version() before any MCU test caching, so a 32-bit run can never reuse a 64-bit resultno

Self-hosted type surface: 65 model.I64/U64/U8 sites in 18 files, and 23 * 8 offset sites in backend/. That, plus the five seams, is the complete mechanical surface.

3.3 What stays 64-bit-only

These are deliberately not touched by M0, and their incompatibility must be an explicit, tested error message rather than a wrong binary:

  • src/macho.rs and compiler/src/macho/* — no 32-bit Apple target exists.
  • src/elf.rs and compiler/src/elf/build.kn — ELF64 only until M5; M1 links with clang.
  • src/a64.rs, src/x64.rs, compiler/src/arm64/*, compiler/src/x64/* — A64/x86-64 encoders until M5 replaces them with Thumb-2/RV32 encoders for embedded targets.
  • src/gen/jit.rs, src/test_mem.rs, compiler/src/testimage/* — in-memory macOS test images.
  • src/gen/os.rs, system.rs, process.rs, directory.rs, compiler/src/runtime* — syscall runtimes. They are already emitted per feature flag (src/gen.rs:477-480), which is the lowering half of the capability model; the check in §5 is the source half.

Everything else — ast, parse, layout, check, generic, ownership, contracts, format, rules, testhash, testcache, project, options, driver — must be word-size-generic, because it is the part that decides whether portable Kern code is accepted.

3.4 The invariant that keeps hosted output identical

Adding Ty variants does not touch existing output because no existing program names them. The one change that does reach every program is len/index → usize (§1.5). It is neutral on 64-bit targets because usize and u64 are the same width and canonical form there, so the backend must lower both through one function (lanes(ty, profile)) and produce the same instructions. §4.1 turns that into a test.


4. Migration sequence

Nine steps, each independently mergeable. S0-S4 need no QEMU (every diagnostic, layout and capability rule is host-testable); S5-S8 are the M1 gates that need QEMU.

4.1 The byte-identical guarantee (mechanism)

  1. Freeze tests/golden/hosted.sha256: for each of examples/{core,enums,sieve,slices,wc}.kn and the examples/calc project, the SHA-256 of build/kern asm <path> --target <t> for macos-arm64, linux-arm64, linux-x64. Generate it on the commit before S1.
  2. tests/golden.sh regenerates and compares; it fails on any byte change.
  3. S1 and S3 must not move it (new types are unused by the corpus).
  4. S2 moves the sources but must not move the hashes: the migrated examples and calc must emit the same assembly as the frozen pre-migration sources. This is the strongest available statement that the usize change is a rename on 64-bit, and it is the moment a width bug would surface.
  5. tests/test_selfhost_cli.sh:25-26 already proves stage2 = stage3 = stage4 byte-for-byte; it stays unchanged and covers the self-hosted backend.

What cannot be tested on the host: runtime traps that only trigger at 32-bit width (usize(2^32) on MCU), stack depth, and MMIO. Those move to S5/S7 with QEMU. Everything in S0-S4 — every diagnostic, the whole layout, the whole capability model — is host-testable, which is the point of putting them first.

S0 — SPEC and profile skeleton (no behaviour change)

Write the type model into SPEC.md (:3-4, :34-37, :75, :184, :227-231) and regenerate compiler/src/spec/print.kn. Add Profile { word_bytes, stack_align, arg_words, wide, caps } with word_bytes = 8 and caps = ALL for the three hosted targets; thread it into front/check without using it. Gate: full harness, self-host proof, kern spec byte-equal.

S1 — i32/u32 on 64-bit targets

Add the two Ty variants, literal ranges, cast rows, is_signed, and make arith/cc width-aware using the existing n32 register names (src/gen.rs:102-104) and the fact that both assemblers already accept 32-bit operands (src/a64.rs:42,265, src/x64.rs:22-29). Gate: new fixtures + trap fixtures for i32 overflow, u32 wrap, i32::MIN / -1, shift counts; hosted output hashes unchanged (i32/u32 appear in no existing source).

S2 — usize/isize + the length migration

Add the two nominal types; change len, arg_count, index, subslice, range, alloc, arena*, truncate to usize; migrate examples/, tests/, and compiler/src/**. On 64-bit, usize lowers through the same 64-bit lane as u64. Gate: 414-case harness, all feature suites, self-host proof, and the golden hashes captured before S2 must still match after S2 (§4.1).

S3 — layout profile

words(type, profile) in src/parse.rs:763 and src/gen.rs:328; word_bytes in the five seams; kern layout <file|project> [--target] printing type, slots, bytes, align per type. This is also the step that splits compile() so check and layout stop calling gen (today gen::gen runs at src/main.rs:52 before the check branch at :176; the self-hosted driver does the same at compiler/src/driver/compile.kn:95). A none target has no backend until S5, and neither command may depend on one. Gate: a layout fixture table (§6.4) for all four target families — pure host test.

S4 — capability model and E170

kern.target parsing, the pass, the diagnostics, and kern check --target thumbv7em-none. Codegen for none targets fails with a plain message, not a diagnostic code.

The S3 split of compile() is what makes this testable with no backend. Gate: the E170-E175 fixture table and the total-map unit test (§5.4).

S5 — 32-bit codegen, hello

New Target::ThumbV7M/ThumbV7EM in gen.rs, a Thumb-2 text emitter, the none runtime (kern_trap_hook, reset/vectors, .data copy, .bss zero), and --cc with a linker script. Gate: hello under QEMU (§6.2) and the ELF32 checks. RV32 gets the same emitter treatment in M2, after the Thumb path proves the model.

S6 — i64/u64 two-word path

wide profile flag; i64 in slices, structs, arguments and returns; mul/div via compiler-rt (__aeabi_lmul, __aeabi_ldivmod) with the wide = off escape (E175). Gate: arithmetic fixtures for all widths on QEMU, plus a size measurement that the tests record as the wide budget.

SysTick, a UART/GPIO MMIO write, a 4-tick blink that proves progress, and build/embedded-size.json committed as the M2 baseline. Gate: §6.3.

S8 — M1 handoff

tests/run_embedded.sh wired as the embedded CIP job, and the ABI frozen by a call-convention fixture (a function with two slices and a u32, called from a none target, verified to pass 5 words in r0-r3+stack).


5. Capability diagnostics E170-E179

5.1 Where the grant lives

A project declares a target profile in kern.target at the project root, beside kern.rules (src/rules.rs:211-229 is the existing pattern to copy):

target = "thumbv7em-none"
memory = { flash = 64K, ram = 20K, heap = 0, stack = 2K }
capabilities = [gpio, uart, systick]
wide = on

Rules of resolution, in order: an explicit --target on the command line selects the profile; otherwise target = in kern.target does; otherwise the host target. capabilities, memory and wide are read from kern.target when it exists and are ignored on hosted targets (which grant every capability). A -none target with no kern.target gets capabilities = [], heap = 0, wide = on. kern.target may not name a different target family from --target (hosted vs none), which is E171. Single-file programs have no project root, so they get those defaults and must pass --target explicitly.

5.2 The builtin → capability table (the normative list)

console = a byte sink provided by the board (UART/semihosting).

CapabilityBuiltinsNotes
(none — always allowed)len, is_null, null_handle, free, truncate, arena, arena_alloc, arena_new, arena_get, arena_set, bit_and, bit_or, bit_xor, bit_not, shift_left, shift_right, i64, u64, u8, i32, u32, usize, isize, target_idpure, no OS, no heap
console (E170)print, print_int, print_errorprint_error needs a debug sink distinct from stdout
heap (E170 + E172)allocalloc is the only dynamic allocator; arena is static
fs (E170) + heap (E172)read_file, try_read_file, read_dirall return owned bytes
fs (E170)write_file, make_dir, remove_dir, remove_file, rename_file, make_executable, file_kind, link_kindno heap
env (E170) + heap (E172 for the owned ones)get_env, current_dir, executable_path, resolve_pathowned results
env (E170)arg, arg_countborrowed; no heap
time (E170)clock_ms, clock_ns, sleep_msSysTick-backed on MCU
process (E170)spawn_process, wait_process, process_status, stop_process, process_id, exit_processsingle-address-space part has no processes
image (E170)image_open, image_spawn, image_closemacOS only today (SPEC.md:211-214)

5.3 The codes

CodeMeaningEmitted by
E170the builtin needs a capability this target does not grant; message names the capability and the kern.target line to addcapability pass
E171kern.target is missing, malformed, or contradicts --target (unknown key/capability, bad size suffix, memory.heap > 0 without heap)profile loader, before checking
E172the operation needs a heap and the profile has heap = 0 (distinct from E170: a board may grant fs yet have no heap)capability pass
E173test io or inputs [...] on a target without fstest runner admission (src/test_runner.rs, compiler/src/runner)
E174recursion in a profile that forbids it; message names the cyclecapability pass, reusing the call graph (src/test_hash.rs:159, compiler/src/testhash/graph.kn:158)
E175a 64-bit integer in a profile with wide = offtype checker (literal/type use)
E176reserved — MMIO address outside the declared memory map (M3)
E177reserved — interrupt fn signature/vector-table violation (M3)
E178reserved — static call-chain stack exceeds memory.stack (M2)
E179reserved — feature unsupported for the target (floats, image_* off macOS)

E170 is the single code the plan promises (EMBEDDED.md:43, EMBEDDED.md:96); the capability name is in the message, not the code, because the existing diagnostics carry one msg/fix pair (src/diag.rs:2-5) and one code per capability would multiply fixture files for no extra information.

Precedence, stated once: E171 before E170 before E172. A malformed profile stops the build before any checking; a missing capability is reported before the heap question, because granting fs is the fix a user must make first; E172 only fires when the capability is granted and memory.heap = 0.

The block is free: CONCURRENCY.md:124-133 claims E161-E166 for tasks and channels, so E170-E179 is the next unassigned decade and E167-E169 stay reserved.

Example (what M0 must print):

{"file":"src/main.kn","line":4,"col":5,"code":"E170","msg":"`read_file` needs the `fs` capability, which `thumbv7em-none` does not grant","fix":"add `fs` to `capabilities` in kern.target, or remove the call"}

5.4 Where the check belongs

  • stage0: a new pass caps::check(&prog, &profile) called from compile() in src/main.rs:48-53 after check() and contracts::lower(), before rules::enforce(). It walks statements and expressions for EK::Call(_, _, id) with id >= B_PRINT (src/check.rs:4) and looks the id up in one table capability_of(id) -> Option<Cap> placed next to io_builtin/untracked_builtin (src/check.rs:67-68). A unit test asserts the table is total over B_PRINT..=B_IMAGE_CLOSE, so a new builtin cannot be added without a capability decision.
  • self-hosted: compiler/src/typing/caps.kn, called at the end of typing/check.kn:5-70 (after the function loop, where check_func has resolved builtin ids). The builtin id range is builtins.BASE.. (compiler/src/builtins/names.kn:3).
  • Why not in codegen: kern check must reject without generating code, the message must be source-located, and gen is the wrong layer to decide policy. Why not a rule: rules are user-disableable (SPEC.md:241, src/rules.rs:2); a capability grant is a safety property.
  • --target handling of a none target produces a plain CLI message ("code generation for thumbv7em-none lands in M1"), never a diagnostic code, so fixtures can distinguish "not implemented" from "not permitted".

6. Acceptance

6.1 M0 exit criteria (all host-testable)

sh .cip/build-kern.sh                                                       # stage0 + self-hosted
sh .cip/unit.sh                                                             # stage0 #[test]s
sh tests/run.sh --host-only build/kern                                      # 414 cases, 3 targets
sh .cip/features.sh build/kern                                              # all feature suites
sh tests/golden.sh                                                          # hosted asm unchanged
sh tests/run_embedded.sh --check build/kern                                 # E170-E175 + layout tables
build/kern check tests/embedded/hello --target thumbv7em-none                # must exit 0
build/kern check tests/embedded/caps/fs_none.kn --target thumbv7em-none      # must exit 1 with E170

6.2 QEMU hello (M1 gate that M0's model must make reachable)

# build: Thumb-2 assembly text + clang, no libc
build/kern build tests/embedded/hello --target thumbv7em-none --cc
# expect: tests/embedded/hello/build/hello-thumbv7em-none

llvm-readelf -h tests/embedded/hello/build/hello-thumbv7em-none   # Class ELF32, Machine ARM
llvm-nm  tests/embedded/hello/build/hello-thumbv7em-none | grep -c __libc_  # 0

qemu-system-arm -M mps2-an385 -cpu cortex-m3 -nographic -monitor none \
    -semihosting-config enable=on,target=native \
    -kernel tests/embedded/hello/build/hello-thumbv7em-none
# expect stdout: "hello from kern\n" and exit code 0 via SYS_EXIT (ADP_Stopped_ApplicationExit)

(qemu-system-arm must be on PATH; on macOS it comes from brew install qemu. The same build runs under -M netduinoplus2 -cpu cortex-m4 when the M4 profile is added in M2.)

tests/embedded/hello/src/main.kn is the smallest program that uses the model: one []u8 literal (8-byte slice), len (a usize), one usize loop and one print. kern.target grants [uart].

build/kern build tests/embedded/blink --target thumbv7em-none --cc
# `timeout` is GNU coreutils; on a stock macOS use `gtimeout` from `brew install coreutils`
timeout 10 qemu-system-arm -M mps2-an385 -cpu cortex-m3 -nographic -monitor none -serial stdio \
    -semihosting-config enable=on,target=native \
    -kernel tests/embedded/blink/build/blink-thumbv7em-none > out 2>&1
test "$(tr -d '\r' < out)" = "KERN-BLINK-4"     # four SysTick ticks, then semihosting exit

The blink toggles the CMSDK APB GPIO data register at a compile-time MMIO address on each SysTick interrupt and mirrors every toggle to the UART, so the test's observable is the UART line; it halts after 4 ticks. A real LED is board work (M7, hardware-in-the-loop); QEMU proves the SysTick path, the interrupt entry, and the MMIO write, which is what M0's decisions have to make possible. Size gate: kern size tests/embedded/blink --target thumbv7em-none must stay inside the EMBEDDED.md:146-150 budget (3 KiB flash / 1 KiB RAM).

6.4 Type-check fixture table

Each fixture is a first line // target: <name> (or // target: any) and // expect: <code> or // expect: ok, driven by tests/run_embedded.sh --check.

FixtureTargetExpectWhat it pins down
types/word_equals_len.kn — let n: usize = len(s)anyoklen returns usize
types/len_is_not_u64.kn — let n: u64 = len(s)anyE021usize is nominal; the fix suggests u64(len(s))
types/index_needs_word.kn — s[u64(0)]anyE021indexes are usize, not u64
types/word_literal_64.kn — let a: usize = 4294967296thumbv7em-noneE022word-width literal check
types/word_literal_64_ok.kn — same sourcelinux-x64okthe check is profile-driven
types/i32_range.kn — let a: i32 = 2147483648anyE022new literal range
types/u32_slot.kn — struct S { a: u32, b: u32 }thumbv7em-noneok + layout 8 B4-byte slots
types/u32_slot_64.kn — same sourcelinux-x64ok + layout 16 Bslot model on 64-bit
types/slice_shape.kn — fn f(s: []u64)thumbv7em-noneok + slice 8 B, elem 8 B(ptr32,len32), 2-slot u64
types/i64_survives.kn — let a: i64 = 4294967296; assert a + 1 == 4294967297thumbv7em-noneok (S6)emulation semantics
types/i64_overflow.kn — let a: i64 = 9223372036854775807; a + 1anytrap overflow (S6)two-word overflow detection
types/u32_wrap.kn — let a: u32 = 4294967295; a + 1anytrap overflowchecked 32-bit arithmetic
types/u32_shift.kn — shift_left(u32(1), 32)anytrap bounds (as today, src/gen/expr.rs:316)width rule (SPEC.md:184)
types/cast_narrow.kn — u32(4294967296)anytrap castno truncation
types/cast_word.kn — let big: u64 = 4294967296; usize(big)thumbv7em-nonetrap cast (S6)32-bit narrowing
caps/fs_none.kn — read_file("x")thumbv7em-noneE170fs forbidden
caps/process_none.kn — spawn_process("x", args, "")thumbv7em-noneE170process forbidden
caps/print_no_console.kn — print("x"), no uart grantthumbv7em-noneE170console is a capability
caps/print_granted.kn — same, capabilities = [uart]thumbv7em-noneokgrants work
caps/alloc_no_heap.kn — alloc(4), capabilities = [heap], memory.heap = 0thumbv7em-noneE172heap grant without memory
caps/test_io_none.kn — test io "x" {...}thumbv7em-noneE173tests need a filesystem
caps/recursion_none.kn — fn a(){b()} fn b(){a()}thumbv7em-noneE174recursion profile rule
caps/wide_off.kn — let a: u64 = 1, wide = offthumbv7em-noneE175profile switch
caps/bad_target.kn + kern.target with capabilities = [wifi]thumbv7em-noneE171profile validation

Layout rows (ok + layout …) are asserted by kern layout, so they test the model without a backend. Trap rows marked trap run on the host where the width is the same (i32/u32 are 32-bit everywhere); the usize-specific trap row moves to M1/QEMU.


7. Open decisions

#DecisionRecommendationWhy
D-Ausize nominal vs target aliasNominal (§1.2)keeps one meaning per spelling; forces the width decision at the boundary; the migration is mechanical and hash-verified. Fallback if the migration must be split: land aliases for one release and make them nominal at the next break — but do not keep aliases permanently.
D-BDefault literal type on 32-biti32 (target int)i64 default would put every untyped counter in two words on MCU. Literal adaptation (src/check.rs:218-224) makes this invisible in typed contexts.
D-CKeep i64/u64 on MCUYes, emulated, wide profile flag default onrule 7 says they remain available; wide = off gives small boards an escape with a diagnostic instead of silently bloating.
D-D4-byte u32 slots on 64-bit tooNo, one scalar per 8-byte slot on 64-bitzero risk to the byte-identical guarantee; the cost only exists in programs that opt into 32-bit types on a 64-bit host. Revisit only if packed []u32 storage is needed.
D-EAggregate-return ABI on 32-bitAAPCS: hidden pointer in r0interop with compiler-rt and any future C entry point; our own functions are the only other callers. Cost: an aggregate-returning call loses one argument register (3 words in r0-r3), which the 6-word source limit absorbs.
D-Ftarget_id() width and valuesKeep u64, append 3=thumbv7m, 4=thumbv7em, 5=riscv32imacit is a pure identifier, hosted-only in practice, and changing its type breaks SPEC.md:215 for no gain.
D-GPack u8/u32 struct fieldsNo packing in M0one scalar per slot is the existing rule; packing needs bitfield-style offsets and changes hosted layout. []u8 is the compact container.
D-HRaise the 6-word argument limitNo in M0; make it profile data so M3 can raise it for 32-bit onlykeeps 64-bit output fixed; AA32 can spill, so the option stays cheap later.
D-ITarget namesthumbv7m-none, thumbv7em-none, riscv32imac-none, existing three unchangedmatches the plan's thumbv7em-none; thumbv7m is the M3 QEMU board and has no hardware divide, which is a real ABI/size factor.
D-JWhere the 6-word check livesMove it to the checker (currently codegen: src/gen/stmt.rs:296, src/gen/expr.rs:425)kern check should reject what kern build rejects, and after S3 splits compile() a codegen-only check would disappear from kern check entirely. The limit also becomes profile data.

8. Non-goals and consequences

  • No floats. EMBEDDED.md:65 keeps them absent; i32/usize do not open that door.
  • No pointer type in source. usize is a count, not an address; there is no arithmetic on addresses, which is what keeps none-target code auditable.
  • No new linear-memory model. alloc stays hosted-only until M2's static heap; arenas are the portable structure.
  • No change to ownership, generics, contracts, or rules. They are width-agnostic; 65 type-kind sites and ~217 Ty:: sites are exhaustive-match updates only.
  • The self-hosted compiler stays a hosted program. It is compiled for 64-bit targets and never needs --target thumbv7em-none; only user programs and the MCU runtime must be portable. This is why the usize migration in compiler/src/** is a rename, not a port.
  • No concurrency surface. CONCURRENCY.md tasks/channels are M6; the only M0 commitments they rely on are that a channel capacity and buffer length are a usize (CONCURRENCY.md:36, :58), that task stacks are sized in usize words (CONCURRENCY.md:61), and that sleep_ms sits behind the time capability (E170) because the MCU scheduler's timer list is SysTick-driven (CONCURRENCY.md:66).
  • Two compilers, one language. Every syntax/type rule in this document must land in both src/ and compiler/src/, because the bootstrap uses stage0 to check and build the self-hosted compiler (tests/test_selfhost_cli.sh:17-19). Codegen may differ per target: stage0 may lack the Thumb backend while the self-hosted compiler has it, because the compiler's own build never targets MCU.

Source: M0-DESIGN.md in the repository.