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
| # | Question | Decision |
|---|---|---|
| D1 | usize/isize | Nominal types, width = target word (32 or 64). Not aliases of u32/u64. |
| D2 | i32/u32 | Nominal, available on every target; on 64-bit they occupy one 8-byte slot. |
| D3 | i64/u64 on 32-bit | Kept, emulated as two words; wide = off profile switch for small boards (E175). |
| D4 | Pointer-sized spelling | usize is the only word type in source: len, indexes, ranges, capacities, arg_count. |
| D5 | Slot | Slot = one target word. 64-bit: 8 bytes (unchanged). 32-bit: 4 bytes. |
| D6 | Slice | (ptr, len) = 2 slots; len is usize on both targets. |
| D7 | Layout | One scalar per slot, no packing, no padding; alignment = slot size. 64-bit layout is unchanged. |
| D8 | 32-bit ABI | AAPCS: r0-r3 then stack, sret in r0, result r0:r1, error flag r2, 8-byte frame alignment. |
| D9 | Casts | Checked value conversions on every target; narrowing traps, never truncates. |
| D10 | Capabilities | kern.target grants a fixed set; the pass lives in src/check.rs + compiler/src/typing; E170-E175 now, E176-E179 reserved. |
| D11 | Hosted output | Frozen tests/golden/ hashes of kern asm on 3 targets must not change, including across the usize migration. |
| D12 | Target names | thumbv7m-none, thumbv7em-none, riscv32imac-none; the existing three keep their names. |
1. Type model
1.1 The three candidate models
| Model | Slice on MCU | Cost | Verdict |
|---|---|---|---|
A. Keep u64 as the word | (ptr64, len64) = 16 B | Every index/length compare, add and range is emulated 64-bit; two words per length; 64-bit slot even where 32 bits suffice | Rejected. 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 B | Zero source migration; one meaning per target | Viable, 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 B | One mechanical migration of existing sources that annotate lengths/indexes as u64 | Chosen. |
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):
- 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.
- Static memory is the default (rule 2).
[]usizehas 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. - 32-bit first (rule 7). The rule names
usizeexplicitly: "on MCU targets the pointer andusizeare 32 bits, slots are 4 bytes, and slices are(ptr32, len32)". Model B honours the width but not the name: a program that saysu64gets 32-bit behaviour, which is exactly the Csize_ttrap the project exists to avoid. - Capabilities, not platforms (rule 8). The
usizemigration 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_fileresults,arg_count). - 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
| Type | 64-bit target | 32-bit target | Notes |
|---|---|---|---|
u8, bool | 1 byte as a slice element; 1 slot as a local/field | same | esz already special-cases this (src/gen.rs:326) |
i32, u32 | 1 slot (8 B); value kept canonical in the slot | 1 slot (4 B) | D2, D7 |
usize, isize | 1 slot (8 B) | 1 slot (4 B) | D1 |
i64, u64 | 1 slot (8 B) | 2 slots (8 B), low word first | D3 |
| pointer (internal) | 1 slot | 1 slot | never in source |
| slice | 2 slots (16 B) | 2 slots (8 B) | (ptr, len) |
Arena | 3 slots (src/parse.rs:45) | 3 slots | header words are all word-sized |
Handle[T] | 2 slots (src/parse.rs:45) | 2 slots | |
| struct | sum of field slots | sum of field slots | no padding (src/parse.rs:763-789) |
| enum | 1 + largest payload | 1 + largest payload | src/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:
| Operation | 32-bit cost |
|---|---|
| add / sub | 2 instructions (adds+adc, subs+sbc) plus the overflow branch; 2x the flags work |
| compare | 2 instructions (cmp + sbc/sbcs); a bool result needs a conditional sequence |
| multiply | umull/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 |
| storage | 2 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:380today returnsU64).arg_count() -> usize(src/check.rs:303).alloc[Element](count: usize)andalloc(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 becomeusize(today any integer:src/check.rs:641-651).for x in s— the hidden cursor and length areusize(todayU64: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.i64on 32-bit: a pair(lo, hi)of 32-bit words in little-endian order,loat 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):
| Seam | 64-bit today | 32-bit | Why it is the seam |
|---|---|---|---|
shift(p, words) | o + 8*w | o + 4*w | src/gen.rs:78; every field/element address |
alloc_mem(words) | mem += 8*words | mem += 4*words | src/gen.rs:339 |
esz(type) | 8*words except u8/bool | 4*words except u8/bool | src/gen.rs:326; slice stride |
words(type) | slice 2, struct words, else 1 | same, plus i64/u64 = 2 | src/gen.rs:328, src/parse.rs:771 |
| frame rounding | (mem + 8*next + 15) & !15 | (mem + 4*next + 7) & !7 | src/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.
offsstays 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.
ptris a real 32-bit address on MCU;lenis ausizeand can never exceed0xFFFF_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 emitLDRD: twoLDRs 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
| Item | 64-bit (unchanged) | 32-bit |
|---|---|---|
| integer args | x86 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 arg | 2 words | 2 words (2 registers) |
| aggregate arg | by reference (&mut/is_ref) | same |
| aggregate return | hidden 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 return | x0:x1 or rax:rdx (src/gen/expr.rs:506-515) | r0:r1 |
| fallible flag | x2 / r11 (src/gen.rs:32, src/gen.rs:27) | r2 |
| trap | cold 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-saved | x19-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:
| Type | add/sub | mul | div/mod | shift |
|---|---|---|---|---|
u32, usize | adds/subs + b.cs | umull + high-word zero check | udiv (M4) or __aeabi_uidiv (M3); trap on 0 | trap on count ≥ 32 |
i32, isize | adds/subs + b.vs | smull + asr #31 compare | sdiv/__aeabi_idiv; trap on 0 and on MIN / -1 | trap on count ≥ 32 |
u8 | adds + compare 255 (unchanged, src/gen.rs:266) | mul + compare 255 | as today | trap on count ≥ 8 |
i64/u64 | 2-word adds+adc / subs+sbc + carry/overflow | umull/smull pair, library call if needed | library call | trap 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 → To | Result |
|---|---|
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 width | traps if negative (today: src/gen/expr.rs:370-374) |
| unsigned→signed of any width | traps above the signed maximum |
usize ↔ u32 | identity on 32-bit, range check on 64-bit |
usize ↔ u64 | identity 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:
i64on 64-bit (unchanged,src/check.rs:253),i32on 32-bit. Literal adaptation already pushes the expected type down (src/check.rs:218-224), so this only affectslet x = 0and similar inference. - Literal range checks (
src/check.rs:254,src/check.rs:736,compiler/src/typing/expressions.kn:151-166) gainI32,U32,USIZE,ISIZEarms;usizeliterals are checked against the profile width, solet a: usize = 4294967296is E022 on MCU and fine on 64-bit (a target-dependent fixture, §6).
3. Impact map
3.1 stage0 (src/, Rust bootstrap compiler)
| File | What is there | Change | 64-bit-only? |
|---|---|---|---|
src/lex.rs | keywords, literals (src/lex.rs:45-63) | none — type names are identifiers | n/a |
src/ast.rs | Ty (:5), is_int (:9), StructDef.offs/words (:55) | add I32, U32, Usize, Isize; is_int; new is_signed, is_word | no |
src/parse.rs | type 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-bit | no |
src/check.rs | 54 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.rs | Target (: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 arith | no (must stay bit-identical for hosted) |
src/gen/stmt.rs | func (: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 == I64 | no |
src/gen/expr.rs | mwords (:272), call (:302), casts (:365-380), E092 (:425), print_int choice (:483), return registers (:506-515) | new cast rows; i64 pairs; print_int by width | no |
src/gen/arena.rs | 8-byte alignment masks (:27, :161) | word alignment from profile | no |
src/gen/runtime.rs | kern_trap/kern_print with write/exit (:34-47), print_i64/u64 (:57-73) | add a none runtime (hook, no syscalls); 32-bit print helpers | new file |
src/gen/os.rs, system.rs, process.rs, directory.rs | syscall runtimes, currently emitted on demand (src/gen.rs:477-480) | no change; they must simply never be emitted for none | 64-bit only |
src/gen/jit.rs, src/test_mem.rs | macOS in-memory image (mmap/dlsym) | no change | 64-bit only |
src/a64.rs | A64 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 needs | 64-bit only until M5 |
src/x64.rs | x86-64 text assembler (:384), 64/32/8-bit widths (:22-29) | none for M0 | 64-bit only until M5 |
src/macho.rs | Mach-O arm64 writer (:1-6) | none; must reject embedded targets with a clear message | yes |
src/elf.rs | ELF64 writer, machine 183/62 (:72-74), write_exe (:122) | none in M0; M5 adds ELF32 + EM_ARM=40/EM_RISCV=243 | 64-bit only until M5 |
src/project.rs | loader (:18-40), ty_str (:283) | read kern.target next to kern.rules; print usize in api signatures | no |
src/rules.rs | 53-rule table (:12-13), Cfg (:124) | no change. Capability errors are not rules; rules are disableable (SPEC.md:241) and capabilities must not be | no |
src/format.rs | token-based printer (:38) | no change — usize is an identifier | no |
src/main.rs | compile (: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 none | no |
src/test_hash.rs | call graph (:159), builtin map (:167) | reuse for E174 (recursion) and as the input to the caps pass | no |
tests/ | run.sh (3 targets), errors/, traps/, wide/, feature suites | new 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 CLI | rewrite 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/)
| Path | What is there | Change | 64-bit-only? |
|---|---|---|---|
model/kinds.kn | I64=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.kn | Type.words/bytes (:107-109) | keep both; bytes becomes profile-dependent | no |
parser/types.kn | type names (:113-125) | four new spellings | no |
typing/layout.kn | integer_type (:14), bytes = words * 8 (:60), field_layout (:66-88) | bytes = words * word_bytes; i64/u64 = 2 on 32-bit | no |
typing/expressions.kn | literal fits (:151-166), index/subslice U64 (:91-95), default I64 (:151) | new ranges; usize for indices; target int default | no |
typing/builtins.kn | cast 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.kn | for cursors U64 (:101-102) | USIZE | no |
typing/check.kn | pass list (:5-60) | call the new caps pass after the function loop; reuse testhash/graph.kn:158 components for E174 | no |
backend/state.kn | target ids (:6-10), STACK_ALIGNMENT/FRAME_HEADER (:14-16), allocate words*8 (:90-101), frame_size (:105) | target id ↔ profile table; slot bytes; alignment | no |
backend/functions.kn | parameter words, + word * 8 (:59), 6-word limit (:66-79) | slot bytes; profile arg words | no |
backend/calls.kn | arguments + position * 8 (:43,46,73), element bytes (:161-180) | slot bytes | no |
backend/expressions.kn | field/index offsets (:46-47,95,113) | slot bytes | no |
backend/machine.kn | byte_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 order | no |
backend/arithmetic.kn | signed/width decisions (158 lines) | width-aware; i64 pair path | no |
arm64/*.kn (9 files), x64/*.kn (6 files) | assembly text emitters; arm64/model.kn:5-11 already carries width | no change for M0; a thumb emitter is new in M1 | 64-bit only |
native/build.kn | target dispatch (:12-24) | reject none targets with "code generation lands in M1" (not E170) | 64-bit only |
elf/build.kn | machine/class (:54-60) | unchanged until M5 (clang links M1) | 64-bit only |
macho/build.kn | (:4) | unchanged | yes |
options/parse.kn | target names (:73-76,146-157), target() > 2 guard (:76) | three new names; explicit_target for kern.target precedence | no |
driver/compile.kn | assembly (:95), host-target run guard (:156), banner (:211-214) | profile plumbed to backend.generate | no |
toolchain/build.kn | clang flags per target (:39-67) | --target=armv7m-none-eabi / armv7em-none-eabi / riscv32-unknown-elf, -ffreestanding -nostdlib -T | no |
spec/print.kn | 19 chunks, 447 lines | regenerate from the new SPEC.md (byte-compared by tests/test_selfhost_cli.sh:30-31) | — |
rules/*.kn | 53 rules | no change | no |
testhash/types.kn | hashes words/bytes (:92) | unchanged data; see testcache note | no |
testcache/cache.kn | version 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 result | no |
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.rsandcompiler/src/macho/*— no 32-bit Apple target exists.src/elf.rsandcompiler/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)
- Freeze
tests/golden/hosted.sha256: for each ofexamples/{core,enums,sieve,slices,wc}.knand theexamples/calcproject, the SHA-256 ofbuild/kern asm <path> --target <t>formacos-arm64,linux-arm64,linux-x64. Generate it on the commit before S1. tests/golden.shregenerates and compares; it fails on any byte change.- S1 and S3 must not move it (new types are unused by the corpus).
- S2 moves the sources but must not move the hashes: the migrated examples and
calcmust emit the same assembly as the frozen pre-migration sources. This is the strongest available statement that theusizechange is a rename on 64-bit, and it is the moment a width bug would surface. tests/test_selfhost_cli.sh:25-26already 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.
S7 — blink + size baseline
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).
| Capability | Builtins | Notes |
|---|---|---|
| (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_id | pure, no OS, no heap |
console (E170) | print, print_int, print_error | print_error needs a debug sink distinct from stdout |
heap (E170 + E172) | alloc | alloc is the only dynamic allocator; arena is static |
fs (E170) + heap (E172) | read_file, try_read_file, read_dir | all return owned bytes |
fs (E170) | write_file, make_dir, remove_dir, remove_file, rename_file, make_executable, file_kind, link_kind | no heap |
env (E170) + heap (E172 for the owned ones) | get_env, current_dir, executable_path, resolve_path | owned results |
env (E170) | arg, arg_count | borrowed; no heap |
time (E170) | clock_ms, clock_ns, sleep_ms | SysTick-backed on MCU |
process (E170) | spawn_process, wait_process, process_status, stop_process, process_id, exit_process | single-address-space part has no processes |
image (E170) | image_open, image_spawn, image_close | macOS only today (SPEC.md:211-214) |
5.3 The codes
| Code | Meaning | Emitted by |
|---|---|---|
| E170 | the builtin needs a capability this target does not grant; message names the capability and the kern.target line to add | capability pass |
| E171 | kern.target is missing, malformed, or contradicts --target (unknown key/capability, bad size suffix, memory.heap > 0 without heap) | profile loader, before checking |
| E172 | the operation needs a heap and the profile has heap = 0 (distinct from E170: a board may grant fs yet have no heap) | capability pass |
| E173 | test io or inputs [...] on a target without fs | test runner admission (src/test_runner.rs, compiler/src/runner) |
| E174 | recursion in a profile that forbids it; message names the cycle | capability pass, reusing the call graph (src/test_hash.rs:159, compiler/src/testhash/graph.kn:158) |
| E175 | a 64-bit integer in a profile with wide = off | type checker (literal/type use) |
| E176 | reserved — MMIO address outside the declared memory map (M3) | |
| E177 | reserved — interrupt fn signature/vector-table violation (M3) | |
| E178 | reserved — static call-chain stack exceeds memory.stack (M2) | |
| E179 | reserved — 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 fromcompile()insrc/main.rs:48-53aftercheck()andcontracts::lower(), beforerules::enforce(). It walks statements and expressions forEK::Call(_, _, id)withid >= B_PRINT(src/check.rs:4) and looks the id up in one tablecapability_of(id) -> Option<Cap>placed next toio_builtin/untracked_builtin(src/check.rs:67-68). A unit test asserts the table is total overB_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 oftyping/check.kn:5-70(after the function loop, wherecheck_funchas resolved builtin ids). The builtin id range isbuiltins.BASE..(compiler/src/builtins/names.kn:3). - Why not in codegen:
kern checkmust reject without generating code, the message must be source-located, andgenis 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. --targethandling of anonetarget produces a plain CLI message ("code generation forthumbv7em-nonelands 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].
6.3 Blink loop (S7 gate)
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.
| Fixture | Target | Expect | What it pins down |
|---|---|---|---|
types/word_equals_len.kn — let n: usize = len(s) | any | ok | len returns usize |
types/len_is_not_u64.kn — let n: u64 = len(s) | any | E021 | usize is nominal; the fix suggests u64(len(s)) |
types/index_needs_word.kn — s[u64(0)] | any | E021 | indexes are usize, not u64 |
types/word_literal_64.kn — let a: usize = 4294967296 | thumbv7em-none | E022 | word-width literal check |
types/word_literal_64_ok.kn — same source | linux-x64 | ok | the check is profile-driven |
types/i32_range.kn — let a: i32 = 2147483648 | any | E022 | new literal range |
types/u32_slot.kn — struct S { a: u32, b: u32 } | thumbv7em-none | ok + layout 8 B | 4-byte slots |
types/u32_slot_64.kn — same source | linux-x64 | ok + layout 16 B | slot model on 64-bit |
types/slice_shape.kn — fn f(s: []u64) | thumbv7em-none | ok + slice 8 B, elem 8 B | (ptr32,len32), 2-slot u64 |
types/i64_survives.kn — let a: i64 = 4294967296; assert a + 1 == 4294967297 | thumbv7em-none | ok (S6) | emulation semantics |
types/i64_overflow.kn — let a: i64 = 9223372036854775807; a + 1 | any | trap overflow (S6) | two-word overflow detection |
types/u32_wrap.kn — let a: u32 = 4294967295; a + 1 | any | trap overflow | checked 32-bit arithmetic |
types/u32_shift.kn — shift_left(u32(1), 32) | any | trap bounds (as today, src/gen/expr.rs:316) | width rule (SPEC.md:184) |
types/cast_narrow.kn — u32(4294967296) | any | trap cast | no truncation |
types/cast_word.kn — let big: u64 = 4294967296; usize(big) | thumbv7em-none | trap cast (S6) | 32-bit narrowing |
caps/fs_none.kn — read_file("x") | thumbv7em-none | E170 | fs forbidden |
caps/process_none.kn — spawn_process("x", args, "") | thumbv7em-none | E170 | process forbidden |
caps/print_no_console.kn — print("x"), no uart grant | thumbv7em-none | E170 | console is a capability |
caps/print_granted.kn — same, capabilities = [uart] | thumbv7em-none | ok | grants work |
caps/alloc_no_heap.kn — alloc(4), capabilities = [heap], memory.heap = 0 | thumbv7em-none | E172 | heap grant without memory |
caps/test_io_none.kn — test io "x" {...} | thumbv7em-none | E173 | tests need a filesystem |
caps/recursion_none.kn — fn a(){b()} fn b(){a()} | thumbv7em-none | E174 | recursion profile rule |
caps/wide_off.kn — let a: u64 = 1, wide = off | thumbv7em-none | E175 | profile switch |
caps/bad_target.kn + kern.target with capabilities = [wifi] | thumbv7em-none | E171 | profile 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
| # | Decision | Recommendation | Why |
|---|---|---|---|
| D-A | usize nominal vs target alias | Nominal (§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-B | Default literal type on 32-bit | i32 (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-C | Keep i64/u64 on MCU | Yes, emulated, wide profile flag default on | rule 7 says they remain available; wide = off gives small boards an escape with a diagnostic instead of silently bloating. |
| D-D | 4-byte u32 slots on 64-bit too | No, one scalar per 8-byte slot on 64-bit | zero 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-E | Aggregate-return ABI on 32-bit | AAPCS: hidden pointer in r0 | interop 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-F | target_id() width and values | Keep u64, append 3=thumbv7m, 4=thumbv7em, 5=riscv32imac | it is a pure identifier, hosted-only in practice, and changing its type breaks SPEC.md:215 for no gain. |
| D-G | Pack u8/u32 struct fields | No packing in M0 | one scalar per slot is the existing rule; packing needs bitfield-style offsets and changes hosted layout. []u8 is the compact container. |
| D-H | Raise the 6-word argument limit | No in M0; make it profile data so M3 can raise it for 32-bit only | keeps 64-bit output fixed; AA32 can spill, so the option stays cheap later. |
| D-I | Target names | thumbv7m-none, thumbv7em-none, riscv32imac-none, existing three unchanged | matches the plan's thumbv7em-none; thumbv7m is the M3 QEMU board and has no hardware divide, which is a real ABI/size factor. |
| D-J | Where the 6-word check lives | Move 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:65keeps them absent;i32/usizedo not open that door. - No pointer type in source.
usizeis a count, not an address; there is no arithmetic on addresses, which is what keepsnone-target code auditable. - No new linear-memory model.
allocstays 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 theusizemigration incompiler/src/**is a rename, not a port. - No concurrency surface.
CONCURRENCY.mdtasks/channels are M6; the only M0 commitments they rely on are that a channel capacity and buffer length are ausize(CONCURRENCY.md:36,:58), that task stacks are sized inusizewords (CONCURRENCY.md:61), and thatsleep_mssits behind thetimecapability (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/andcompiler/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.