M3: MMIO, interrupts and hardware capabilities
Status: design, not implemented. This document is the M3 contract; it adds no code.
Prerequisites: M0 (32-bit model, u32/i32, usize, capability plumbing), M1 (external
toolchain + QEMU) and M2 (freestanding runtime, vectors, reset, .data/.bss, trap hook).
Parent plan: EMBEDDED.md. Design law: every feature must run on a single-core MCU with a few
tens of kilobytes of RAM, a few hundred kilobytes of flash and no operating system.
0. The whole surface
M3 adds six language forms:
| Form | Kind | Purpose |
|---|---|---|
read8/read16/read32(ADDR) | builtin expression | one volatile load from a constant address |
write8/write16/write32(ADDR, value) | builtin statement | one volatile store to a constant address |
fence() | builtin statement | compiler + hardware memory barrier |
interrupt fn name() [priority N] { ... } | declaration | an entry point called by the vector table |
critical { ... } | statement | mask maskable interrupts, restore on exit |
static [var] NAME: Type [= literal] | declaration | fixed storage with no exposed address |
It also adds a target profile, kern.target, that declares memory, peripheral address ranges,
vectors and the capability set. A seventh, optional builtin, raise(vector) (§5.2), exists only to
make interrupt tests deterministic; it is not required by the core design and may ship in M3.2.
It does not add unsafe, a pointer type, a reference to a device, pointer arithmetic,
integer-to-address conversion, a register abstraction layer, a HAL, DMA, caches, an MPU or
concurrency primitives. There is no expression whose value is an address. Every address is either a
literal or a constant, checked against the profile before code generation.
The safety argument is small enough to state in one paragraph:
A program can touch a device only through a fixed-width access whose address is a compile-time constant inside a peripheral range that the target profile declares and grants. It can run concurrently with nothing except interrupt handlers it declares itself. Handlers and task code share data only through
static varscalars and fixed arrays, and every access to one is either inside a handler or insidecritical. Therefore there is no forged address, no data race to prove away, and no undefined behaviour.
1. Volatile MMIO
1.1 Surface and types
read8(address: u32) -> u8
read16(address: u32) -> u16
read32(address: u32) -> u32
write8(address: u32, value: u8)
write16(address: u32, value: u16)
write32(address: u32, value: u32)
- All targets are little-endian; a
read32is four bytes, little-endian. - Widths are exact. There is no implicit widening, narrowing or sign extension; a wrong type is the
ordinary
E021type error.read16needsu16, which M3 adds to M0's integer set (see §7). writeNreturnsvoidand is used as a statement.readNreturns an unsigned bit pattern.- A read may be discarded on purpose with
_ = read32(STATUS). This still performs the load, which matters for read-to-clear status registers. Thediscarded_resultrule already requires the explicit_ =, so no rule exception is needed. - There is no 64-bit access. Every register on these targets is at most 32 bits; a 64-bit device access would be two bus cycles and is not atomic.
readN/writeN are reserved builtin names, like print and len. A user declaration with one of
these names is rejected, as it is for existing builtins.
1.2 Addresses are constants, not values
The address argument is a constant expression, not an expression of type u32 that happens to
be constant. The grammar is deliberately tiny:
address := INTEGER
| CONST_NAME
| address + address
| address - address
CONST_NAMEis anALL_CAPSconstant of typeu8/u16/u32/u64whose value fits in 32 bits, includingboard.*constants generated from the profile (§3.1).+and-are evaluated at check time with overflow checks and a non-negative 32-bit result.- A local, parameter, field, slice element, function call or
staticis not a constant expression.let addr = 0x40013800followed byread32(addr)isE171. - A constant expression may fold to the same value as a variable, but the checker does not care about values: the form must be constant. This is what makes the guarantee local and cheap.
The profile generates one constant per peripheral base and, optionally, one per named register:
use board
const LED_SET: u32 = 32
const LED_RESET: u32 = 2097152
fn set_led(on: bool) {
if on {
write32(board.GPIOA_BSRR, LED_SET)
} else {
write32(board.GPIOA_BSRR, LED_RESET)
}
}
board is an implicit module on a none target; use board imports it like any other module.
board.GPIOA_BSRR is a plain u32 constant. It is not an address value, a handle or a token: it is
an integer, and the only thing that can consume it is an address position that validates it. A local
u32 cannot be substituted, even at the same numeric value.
1.3 The profile range is the guard
kern.target declares every peripheral as a half-open interval:
peripheral usart1 {
capability = uart
range = 0x40013800..0x40013C00
registers = { SR = 0x00, DR = 0x04, BRR = 0x08, CR1 = 0x0C }
}
For every access the checker proves, in this order:
- The target is a
nonetarget. A hosted target has no declared peripherals:E170. - The address is a constant expression: otherwise
E171. - The address fits in 32 bits and the interval
[address, address + width)lies entirely inside exactly one declared peripheral range: otherwiseE172. address % width == 0: otherwiseE173.- The range's capability is in the profile's
capabilitieslist: otherwiseE170.
The order matters for the diagnostic: an address in a known but ungranted peripheral reports the capability, not a generic out-of-range error.
Ranges are validated when the profile loads:
- ranges must not overlap each other, flash or RAM (
E179); - a range must be at least one byte and fully inside the 32-bit address space;
- a capability name must be a known name (§3.2), and every peripheral's capability must be known;
- the reserved core window (NVIC, SCB, MPU and debug) must not be declared; SysTick is the one exposed core block.
Core peripherals are reserved. The runtime owns the NVIC, SCB, MPU and debug blocks. A profile
may not declare them, so user code cannot disable interrupts behind critical, change the vector
table base, or write the MPU. SysTick is the one core block exposed as a normal peripheral with the
systick capability. This is the single most valuable property of the range model: critical is
the only way a program can change interrupt masking.
The profile also validates memory against the board's load addresses, so a peripheral range can
never alias RAM. This is what makes "no forged pointer" more than a slogan: even a program that
guessed a RAM address could not wrap it in a read32, because RAM is not in any peripheral range,
and locals move at run time anyway.
1.4 Ordering and volatile
Every readN and writeN is an observable event. Think of the program as producing a single
sequence of events per core; the compiler's job is to preserve the events and their order.
The compiler may:
- fold the address expression to an immediate;
- hoist the address computation and the value expression, including pure arithmetic and pure calls that cannot trap;
- reorder pure, non-trapping computation freely around an event;
- keep a non-MMIO value in a register across an event only if that value cannot change (for example, a local with no address taken). Since a volatile access is modelled as an opaque call that may read and write all memory, address-taken locals and statics are reloaded.
The compiler may not:
- cache an MMIO read in a register across another MMIO access, a call,
critical, a handler entry or exit, orfence(); - fold two reads of the same address into one;
- eliminate a read whose result is unused (
_ = read32(X)must still load); - eliminate a write because a later write overwrites it;
- merge two writes to the same address (set/clear alias registers such as
BSRRdepend on both); - widen, narrow, split or combine accesses;
- speculate an access onto a path where the source does not execute it;
- move an access across
fence(),critical, an interrupt entry/exit, a trap, or a call whose body is not visible.
A read executes exactly once per dynamic execution of the source expression, and a write exactly once. There is no "as-if" freedom for these events.
The IR represents them as opaque operations:
VolatileLoad { width, address } MayRead = all, MayWrite = none, NoCSE, NoDCE, Ordered
VolatileStore { width, address, value } MayRead = none, MayWrite = all, NoDCE, Ordered
Fence MayRead = all, MayWrite = all, Ordered
Ordered means the optimizer's scheduler treats them like calls: no motion across them. This is
stronger than the architecture requires and costs nothing measurable on an MCU at -Os.
fence() is the explicit hardware barrier for the cases the language cannot see:
- Cortex-M:
dsb sy(a followingisbwhere instruction synchronisation matters); - RV32:
fence iorw, iorw.
critical entry and exit imply a compiler barrier and the appropriate hardware fence, so a
critical also orders MMIO. A peripheral clock enable followed by a register write normally needs
no explicit fence() on these parts, but code that depends on write-buffer completion before an
interrupt enable or a DMA start should use one. DMA itself is out of M3.
Two further rules follow from the hardware:
- An aligned 8/16/32-bit access is single-copy atomic on Cortex-M and RV32. An unaligned one may
not be, which is why
E173forbids unaligned MMIO. - Two different MMIO addresses may alias the same register (set/clear aliases, FIFO data ports). The compiler must not assume that distinct addresses are independent; the "opaque call" model already gives that.
1.5 Why not []u8, and why no pointer type
A slice is the wrong tool in every dimension:
| Property | []u8 | readN/writeN |
|---|---|---|
| Address | a run-time pointer plus length | a compile-time constant, never a value |
| Creation | alloc, read_file, sub-slice, literal | impossible: no address-producing expression |
| Bounds | run-time checks against len | compile-time range check |
| Ownership | owned or borrowed, with free/lifetime rules | no owner, no lifetime, no cleanup |
| Volatility | ordinary memory: cacheable, foldable, reorderable | observable event, never cached or folded |
| Aliasing | ordinary aliasing rules | may alias other device addresses; no assumption |
| Length | a u64/usize in the value | fixed by the builtin name |
| Failure | traps at run time | rejected at compile time |
Even if a slice could be aimed at 0x40013800, it would carry a run-time pointer and a length,
be bounds-checked against a meaningless length, be freeable, be cacheable, and be indistinguishable
from heap memory. None of that is acceptable for a device register.
A raw pointer type would fix the address but import the entire problem set: provenance, null,
arithmetic, aliasing, lifetime, const-ness, and an escape hatch that is effectively unsafe.
Because the language never needs to name an address at run time, none of that is necessary. The
address is consumed by the compiler, not by the program.
The same reasoning rules out Mmio[T] as the primary interface: it is a value that holds an
address, which is exactly the thing we do not want to exist. See §7 for the one case where a
zero-sized peripheral token is a reasonable later addition.
1.6 Diagnostics for addresses
| Code | Trigger | Example fix |
|---|---|---|
E171 | the address is not a constant expression | use board.USART1_SR, not a local |
E172 | the address is outside every declared range, or does not fit in 32 bits | declare the range, or use the board constant |
E173 | the access is not naturally aligned for its width | use read32 at a 4-byte boundary, or read8 for a byte lane |
E170 | the range is known but its capability is not granted, or the target is hosted | add the capability to kern.target |
Example:
fn bad(address: u32) -> u32 {
return read32(address)
}
error[E171]: MMIO address is not a compile-time constant
--> src/main.kn:2:19
|
2 | return read32(address)
| ^^^^^^^ use a board constant such as `board.USART1_SR`
2. Interrupts
2.1 interrupt fn
use board
const USART_RXNE: u32 = 32 // STM32 USART_SR.RXNE
interrupt fn usart1() priority 5 {
let status = read32(board.USART1_SR)
if bit_and(status, USART_RXNE) != 0 {
let byte = read8(board.USART1_DR)
write8(board.USART1_DR, byte)
}
}
interrupt fnis a declaration form, not an expression. The handler is an entry point: it is never called by name. A direct call isE174.- The name must exactly match a vector name declared by the board profile (snake_case). There is
one handler per vector; a second one is
E175. - Handlers may live in any module. They are found by scanning all modules, not by module path.
priority Nis optional; without it the profile's default priority for that vector applies.Nis in0 .. 2^priority_bits - 1. The profile fixes the convention as "0 is the most urgent", matching ARM; a RISC-V board maps that number to its own level numbering in the runtime. Out of range isE175.- A handler cannot be
pub(E174). It is not callable, so it has no API surface; the vector table references the symbol regardless of module privacy. - A handler cannot have type parameters, parameters, a return value, an error type or contracts
(
E174). It may containreturnwith no value.
The ABI is an ordinary AAPCS/RISC-V calling convention function that happens to be entered from an exception, with these additions:
| Item | Cortex-M3/M4 | RV32 (ESP32-C3) |
|---|---|---|
| Saved by hardware | r0-r3, r12, lr, pc, xPSR (+ FP frame if enabled) | nothing |
| Saved by the generated stub | EXC_RETURN (lr), 8-byte stack alignment | mepc, mstatus, ra, t0-t6, a0-a7 |
| Saved by the handler prologue | callee-saved r4-r11, lr as used | callee-saved s0-s11, ra as used |
| Return | bx lr with EXC_RETURN (or pop {pc}) | restore mepc/mstatus, mret |
| Stack | MSP; a task's PSP once M6 exists | the current task stack; no switch in M3 |
| Floating point | no FP in M3; FPU disabled, lazy stacking off | no FPU |
| Result | none | none |
| Allocation | none, transitively | none, transitively |
The stub is compiler-generated and is the only assembly M3 needs. It keeps the hardware frame and
the compiler's own prologue separate, so a handler is written and checked exactly like a normal
function. No user code writes a vector, a naked function or inline assembly. The Cortex-M shape
is:
uart0_vector:
push {r0, lr} @ keep the 8-byte alignment, save EXC_RETURN
bl kern_uart0 @ the user handler; ordinary AAPCS prologue saves r4-r11
pop {r0, pc} @ EXC_RETURN in pc: exception return
The RV32 stub is the same idea with mepc, mstatus and the caller-saved registers saved around
the call, and mret on exit; the board runtime chooses the trap stack and the interrupt-matrix
dispatch.
A handler is infallible: it has no error type, so try is impossible and fail is E174.
Calls to fallible functions must use match and handle the error arm locally. An assert or a
contract failure traps through the board trap hook, which must itself be ISR-safe; the default hook
uses one semihosting/UART write and halts, and is documented as best-effort if the interrupted
device is the console.
2.2 Vector table and priorities
The profile declares vectors as board data:
vector systick { number = 15, priority = 15 }
vector usart1 { number = 53, priority = 5 }
vector exti0 { number = 22, priority = 6 }
number is the ARM exception number (16 + IRQn) or the board-defined interrupt-source ID on
RISC-V. The profile is authoritative; the numbers in this document are illustrative.
The backend emits one table at the image base:
.vectors:
.word __stack_top
.word Reset_Handler
.word NMI_Handler # default: kern_default_handler
...
.word SysTick_Handler # the user's `interrupt fn systick`
...
.word USART1_Handler # the user's `interrupt fn usart1`
...
.word kern_default_handler # every unclaimed slot
- Slot 0 is the initial stack pointer, slot 1 the reset handler, slots 2-15 the system exceptions,
and from slot 16 the external interrupts. The table is sized to the highest declared vector, so
it is complete; a stray interrupt lands in
kern_default_handler. kern_default_handlerprintsunhandled irq Nwhen a console exists and halts. It never returns silently, which would loop forever on a level-triggered source.- Priorities are written once in
Reset_Handler, before.datais copied and beforemain. The runtime groups all bits as preemption priority (no subpriority split in M3). - On RISC-V the "table" is a dispatch table plus
mtvecand the ESP32-C3 interrupt matrix setup. The language contract is identical: one handler per source, no arguments, no return. - A user profile cannot move the table or replace an entry. A handler can claim only a vector that
the board profile lists as user-assignable; the system vectors (
HardFault,NMIand the fault vectors) are board policy. A profile may expose a fault vector, butcriticaldoes not maskNMIorHardFault(§2.3).
Reset order is fixed: set sp, set vector base where needed, configure priorities, copy .data,
zero .bss, run static initialisers (there are none beyond .data), call main. If main returns,
the runtime exits through the board's exit path (semihosting or halt).
2.3 critical
fn uptime_ms() -> u64 {
var snapshot: u64 = 0
critical {
snapshot = TICKS
}
return snapshot
}
critical { ... }is a statement. It masks every maskable interrupt on the current core, runs the block, and restores the previous mask state. It is not a lock and has no owner.- Nesting is allowed and is naturally correct because the implementation saves and restores the old
state rather than counting:
- Cortex-M:
mrs r0, PRIMASK; cpsid ion entry,dsb; msr PRIMASK, r0; isbon exit; - RV32: read and clear
mstatus.MIEon entry, restore it on exit, withfencebefore the restore.
- Cortex-M:
criticalmasks maskable interrupts only. On Cortex-M,NMIandHardFaultare not maskable; the configurable-priority fault handlers are masked like other interrupts. On RV32, the machine trap path follows the same rule. AnNMIorHardFaultcan therefore still observe a half-updatedstatic var; a fault handler must not read applicationstatic varstate. The model does not claim atomicity against faults, only against interrupts.- A
criticalmay contain MMIO, calls, loops,if/match, and nestedcriticalblocks. It must not contain an operation that can block indefinitely or allocate:sleep_ms, channel/task operations, file or console I/O, andallocareE176. Acriticalis a bounded region. - Early exits that leave the block (
return,fail,break/continuethat target an outer loop) areE176in M3. The workaround is a local flag read after the block. This keeps codegen a straight-line mask/restore pair and avoids a hidden cleanup protocol; §7 revisits it. criticalin a contract predicate isE160(contracts are read-only and side-effect free).- On a hosted target
criticalis a compiler barrier only; there are no interrupts to mask, and this lets shared-state logic be unit-tested on the host. Onnoneit masks. - An empty
critical {}is an empty block and the existingempty_blockrule applies.
2.4 Atomics: mask, do not lock
M3 has no Atomic, no Shared, no compare-and-swap and no lock-prefixed instruction. On a
single-core MCU:
- An aligned 32-bit load or store is indivisible relative to an interrupt. A read-modify-write is not: an interrupt between the load and the store loses an update.
- The primitive that makes a read-modify-write safe is therefore
critical, which masks. On Cortex-M0 there is noLDREX/STREXat all; on M3/M4 there is, but masking is fewer instructions and works uniformly on both cores. - RISC-V has
Aextensions on some parts, but ESP32-C3 is RV32IMC (noA), so the same argument applies.
The future Atomic[T] (C6, after M3) will lower its read-modify-write operations to a mask/op/unmask
sequence on MCU targets, and its plain load/store to a single aligned access. It is a library
convenience over critical, not a new memory model. M3 deliberately ships the primitive first so
that the concurrency plan can be evaluated against real interrupt code.
2.5 Shared state and static var
Handlers cannot receive parameters, return values or borrowed data, and no function value can be registered. Therefore the only way an interrupt handler and task code share data is static storage. M3 makes that visible:
static var TICKS: u64 = 0
static var QUEUE: [u8; 64]
Rules:
static(immutable) is readable from anywhere, including contracts. Its initializer is a literal, so it lives in.rodataor.datawith no startup code.static varmay hold a scalar or a fixed array of scalars. It may not hold an owning value, a slice, an arena, a handle or a struct with an owning field (E176). A borrow or sub-slice of astatic vararray is also rejected, because the view could escape thecriticalregion. Scalars are naturally aligned; au64static is 8-byte aligned even on a 32-bit target.- For every
static var, the checker collects its access contexts: the task context and eachinterrupt fnthat can reach an access. The rules are:- a task-context access requires
criticalif any handler accesses the cell, because a handler can preempt a task between a load and a store; - a handler access requires
criticalif any other handler accesses the cell, because a higher-priority handler can preempt a lower one (equal-priority handlers do not preempt, but the rule conservatively ignores priority); - a cell with exactly one access context needs no
critical. The checker computes aneeds_criticalsummary per function and reportsE176at the first access or call that violates the rule.
- a task-context access requires
- The address of a
staticis never exposed. There is no&STATIC, so a static cannot be turned into a slice or a device address.
This is a genuine data-race freedom argument, not a convention. Consider the cell TICKS in §4.3:
the only handler context is SysTick, so the handler's TICKS += 1 needs no critical; the task
context also accesses it, so uptime_ms must use critical. Add a second handler that reads
TICKS, and both handler accesses would need critical. There are no other threads, and two
contexts can only interleave in the direction the rule checks. The cost is a little ergonomics for
a cell shared with a handler; the benefit is a checkable model with no atomics.
2.6 Interaction with the cooperative scheduler
M3 predates the scheduler (M6), but the contract is fixed now:
- Interrupts are the only preemption. Tasks are cooperative; a task yields only at a blocking call or the loop back-edge poll. An interrupt handler can preempt a task at any instruction.
- A handler never calls a scheduler operation, never yields, never blocks, never allocates and never
switches stacks. It may set a
static varflag, push one byte into astatic varring, or bump a counter. A handler access needscriticalonly when another handler also touches the cell; the task side usescriticalwhenever any handler touches it (§2.5). - The scheduler's ready queue and timer list are ordinary task-side data protected by
criticalwhen a handler can touch them. The recommended pattern is that a handler publishes one word (a flag or a ring index) and the scheduler observes it; the handler does not walk a task list. - The loop back-edge poll is emitted only in task code. It is suppressed in
interrupt fnand in every function reachable from one, so a loop inside a handler cannot call the scheduler. - An idle task uses
wfi; the interrupt that wakes it returns to the idle loop, which re-checks the ready queue. There is no context switch inside the handler in M3; a later M6 phase may defer one with PendSV, still without running user handler code on a task stack it does not own. - An interrupt uses the current stack. The compiler reports the deepest handler frame and the
profile reserves
isr_stack; with tasks, every task stack must include that headroom. sleep_msin a handler isE177for the same reason it cannot block: it would sleep the interrupted context with interrupts in an unknown state.
2.7 ISR-safety is a transitive effect
A handler may call ordinary functions. The checker computes, for every function, whether it is ISR-safe:
- does not allocate (directly or transitively);
- does not perform console, file, process or image I/O;
- does not block (
sleep_ms, channel/task operations); - does not raise a software interrupt;
- does not touch a
static varoutsidecriticalexcept a cell that is private to that handler (no other handler and no task accesses it); - has no
failpath and notrythat would need an error return.
A call from an interrupt fn to a non-ISR-safe function is E177, naming the offending callee and
the reason. This reuses the call-graph summary machinery that already powers read-only contract
predicates, so it is one more summary bit-set, not a new analysis framework.
A handler may call a pure function, clock_ns, fence, another critical block, MMIO, and any
function whose summaries are clean. It may not call print, alloc, sleep_ms, spawn_process,
read_file, the future channel operations, or a function that does.
3. Capability model
3.1 kern.target
A project may contain kern.target next to kern.rules. Built-in board profiles ship with the
compiler, so most projects only select one with --target/--board; a single-file MCU build uses a
built-in profile, and a custom board writes a file. A none build with no board at all is E179.
The syntax is a small declaration language, not TOML, so both compilers can parse it with the same
hand-written style as kern.rules:
# kern.target: STM32F103C8 "blue pill"
format = 1
target = "thumbv7m-none"
board = "stm32f103"
runner = "none" # "qemu" | "none"; HIL is an external --runner
trap = "uart" # "semihosting" | "uart" | "halt"
console = "usart1" # a peripheral name, or "semihosting"
priority_bits = 4
memory = {
flash = 64K, flash_base = 0x08000000,
ram = 20K, ram_base = 0x20000000,
heap = 0, stack = 2K, isr_stack = 512,
}
capabilities = [gpio, uart, systick, rcc]
peripheral rcc {
capability = rcc
range = 0x40021000..0x40021400
registers = { CR = 0x00, CFGR = 0x04, APB2ENR = 0x18 }
}
peripheral gpioa {
capability = gpio
range = 0x40010800..0x40010C00
registers = { CRL = 0x00, CRH = 0x04, IDR = 0x08, ODR = 0x0C, BSRR = 0x10 }
}
peripheral usart1 {
capability = uart
range = 0x40013800..0x40013C00
registers = { SR = 0x00, DR = 0x04, BRR = 0x08, CR1 = 0x0C }
}
peripheral systick {
capability = systick
range = 0xE000E010..0xE000E020
registers = { CSR = 0x00, RVR = 0x04, CVR = 0x08, CALIB = 0x0C }
}
vector systick { number = 15, priority = 15 }
vector usart1 { number = 53, priority = 5 }
vector exti0 { number = 22, priority = 6 }
Rules:
format,target,board,memoryandcapabilitiesare required; other keys are optional. Whitespace inside{ ... }and[ ... ]is insignificant, trailing commas are allowed, and a profile may break a long line. Unknown keys, sections or capability names areE179, so a typo cannot silently grant nothing.memorysizes acceptKandM(powers of 1024).heap = 0is the default;stackis the main stack;isr_stackis the headroom reserved above the current stack for the deepest handler chain.heap + stack + isr_stack <= ramis checked (E179).flash_base/ram_baseare required in a custom profile; every built-in profile sets them. Peripheral ranges must be disjoint from[flash_base, +flash)and[ram_base, +ram)(E179).- A
registersentry is a byte offset fromrange.lo. It generatesboard.<PERIPHERAL>_<REGISTER>constants (uppercase, for exampleboard.GPIOA_BSRR,board.USART1_SR). Every peripheral also getsboard.<PERIPHERAL>_BASE, and every vector getsboard.<VECTOR>_VECTOR(its number, forraise). Theboardmodule is implicit and reserved onnonetargets; a user module with that name isE179. registersis optional. It exists to give names to the addresses the board support code uses; it is not an SVD import and it does not grant anything. A missing register can still be reached with a literal offset, subject tomagic_numberstyle rules.console = "semihosting"is valid only whensemihostingis incapabilities.- A
vectorblock is user-assignable unless it setsuser = false. The default istruefor external vectors and SysTick, andfalseforNMIand the fault vectors. Auser = falsevector stays in the table but always useskern_default_handler. runnerselects a built-in runner only. A project cannot put a shell command in the profile; a HIL runner is an explicit--runner <path>on the command line.
kern.target is authoritative. If --target/--board are also given and disagree with the file,
the build fails with E179 rather than silently using a different memory map. A build that passes
because it silently switched boards is exactly the failure the capability model exists to prevent.
3.2 Capabilities and builtins
The known capability names in M3 are:
gpio uart systick rcc semihosting
spi, i2c, adc, pwm, timer, dma and usb are reserved for later profiles and are
E179 if used before they are implemented, which keeps a profile from claiming support that does
not exist.
| Feature | Requirement | Failure |
|---|---|---|
readN/writeN | address in a granted peripheral range | E170/E172/E173 |
interrupt fn v | vector v declared, user-assignable, its capability granted | E175/E170 |
raise(v) (optional test aid) | v is a declared, user-assignable vector; task or test context only | E175/E177 |
critical, fence | core feature, no capability | — |
clock_ms, clock_ns, sleep_ms | systick | E170 |
print, print_int, print_error | console peripheral capability, or semihosting | E170 |
alloc, free (heap path), arena, arena_alloc, arena_new, truncate | heap > 0 | E170 |
arena_get, arena_set, null_handle, is_null, len, checked conversions, bit builtins | no capability; the arena must already exist | — |
read_file, write_file, read_dir, try_read_file, path operations | none on none | E170 |
spawn_process, wait_process, process_status, stop_process | none on none | E170 |
get_env, current_dir, executable_path, arg, arg_count | none on none | E170 |
image_open, image_spawn, image_close | none on none | E170 |
exit_process, target_id | always; exit maps to semihosting/halt | — |
test io, inputs [...], --audit | none on none | E178 |
Every builtin not in this table is unavailable on none and reports E170; the table is the
complete list, so a new hosted builtin cannot appear on an MCU by accident.
Notes:
- MMIO has no separate
mmiocapability. The peripheral range is the permission; grantinguartgrants every register in the UART window. This is deliberately coarse: register-level access control is not knowable without an SVD, and a driver is trusted once the device is granted. printmaps to the declared console. If the console issemihosting, it uses the semihosting write call and requiressemihosting; if it isusart1, it uses that peripheral and requiresuart. The console is never implicit, so a program cannot accidentally grab a UART that a driver owns.target_id()gains3 = thumbv7m,4 = thumbv7em,5 = riscv32(IMC or IMAC). It identifies the build target family, as it does on hosted targets, and needs no capability.freeon a static/arena value is a type error as before; the heap gate only affectsalloc.
The same features on a hosted target:
| Feature | Hosted | none |
|---|---|---|
readN/writeN | E170 (no declared peripherals) | range-checked |
fence | compiler barrier | compiler + hardware barrier |
interrupt fn | E170 (no vector table) | profile vector |
critical | compiler barrier only | mask/restore |
static / static var | ordinary static storage | shared-state rule |
test io, inputs | supported | E178 |
This keeps the hosted corpus and its tests unchanged, and lets shared-state logic be exercised on the host without pretending that a host has interrupt priority.
3.3 Default profiles
All numbers below are profile data; the profile file is authoritative. They are grouped so a reader can see the shape, not so they can be copied into a new board without checking the datasheet.
QEMU mps2-an385 (Cortex-M3, the CI default)
format = 1
target = "thumbv7m-none"
board = "qemu-mps2-an385"
runner = "qemu"
trap = "semihosting"
console = "semihosting"
priority_bits = 3
memory = { flash = 4M, flash_base = 0x00000000, ram = 4M, ram_base = 0x20000000,
heap = 0, stack = 4K, isr_stack = 1K }
capabilities = [gpio, uart, systick, semihosting]
Peripherals: CMSDK uart0 at 0x40004000, uart1 at 0x40005000, gpio0/gpio1 at
0x40028000/0x40029000, dual timer at 0x40002000, plus the core systick. The UART registers
are DATA = 0x00, STATE = 0x04, CTRL = 0x08, INTSTATUS = 0x0C, BAUDDIV = 0x10,
INTENSET = 0x14, INTENCLR = 0x18; the GPIO block has DATA = 0x00, DATAOUT = 0x04,
OUTENSET = 0x10 and the interrupt registers. Vectors: systick = 15, uart0 = 20, gpio0 = 22.
QEMU models these devices well enough for register read-back and interrupt delivery, which is why
this is the default M3 gate.
A second CI profile, qemu-sifive-e (riscv32imac-none), exercises the RV32 backend with the
SiFive UART at 0x10013000, GPIO at 0x10012000, CLINT and PLIC. ESP32-C3 is not an upstream QEMU
machine; it needs the Espressif QEMU fork or hardware-in-the-loop.
STM32F103 (Cortex-M3, 64 KiB flash / 20 KiB RAM)
format = 1
target = "thumbv7m-none"
board = "stm32f103"
runner = "none"
trap = "uart"
console = "usart1"
priority_bits = 4
memory = { flash = 64K, flash_base = 0x08000000, ram = 20K, ram_base = 0x20000000,
heap = 0, stack = 2K, isr_stack = 512 }
capabilities = [gpio, uart, systick, rcc]
Peripherals: rcc 0x40021000, gpioa 0x40010800, gpiob 0x40010C00, usart1 0x40013800,
systick 0xE000E010. Vectors: systick = 15, usart1 = 53, exti0 = 22. The NVIC/SCB window is
not declared, so user code cannot reprogram masking or the vector base.
STM32F407 (Cortex-M4F, 1 MiB / 128 KiB)
format = 1
target = "thumbv7em-none"
board = "stm32f407"
runner = "none"
trap = "uart"
console = "usart1"
priority_bits = 4
memory = { flash = 1M, flash_base = 0x08000000, ram = 128K, ram_base = 0x20000000,
heap = 0, stack = 4K, isr_stack = 1K }
capabilities = [gpio, uart, systick, rcc]
Peripherals: rcc 0x40023800, gpioa 0x40020000, usart1 0x40011000, systick. The 64 KiB
CCM RAM at 0x10000000 is not in the profile; it is not DMA-capable and is a later region key.
The FPU is disabled in M3, matching the FPU-less profile in EMBEDDED.md.
ESP32-C3 (RV32IMC, 400 KiB SRAM)
format = 1
target = "riscv32imc-none"
board = "esp32c3"
runner = "none"
trap = "uart"
console = "uart0"
priority_bits = 3
memory = { flash = 4M, flash_base = 0x42000000, ram = 400K, ram_base = 0x3FC80000,
heap = 0, stack = 4K, isr_stack = 1K }
capabilities = [gpio, uart, systick]
Peripherals: uart0 0x60000000, gpio 0x60004000, systimer 0x60023000 (the systick
capability maps to SysTimer on this part, so clock_ms and sleep_ms have one implementation on
both architectures). Vectors are interrupt-source IDs from the board file, dispatched through the
interrupt matrix by the runtime. ESP32-C3 is single-core; no SMP story is implied.
3.4 Tests on none targets
There is no OS, no process isolation and no host filesystem. The test machinery therefore changes shape, not meaning:
test "name" { ... }is supported. The compiler builds one test image containing every selected test in source order and a generated runner. The runner replacesmainas the entry point (somaindoes not run), calls each test, printskern-test: ok <name>orkern-test: FAIL <name>through the harness channel, and exits with the failure count (0 = success). Thekern-test:prefix keeps harness lines distinct from a program'sprint.- MMIO is allowed in a
teston anonetarget. The pure-test rule exists to keep host tests deterministic and cacheable; on an MCU there is no cache and the device is the subject. The effect checker gives MMIO ahardwareclass that is legal in a test only onnone. test iois rejected (E178). It exists to exercise the host OS, and everynonetarget has no OS by design. Accepting it through semihosting would smuggle a host filesystem into the MCU profile and break the capability model.inputs [...]is rejected (E178) for the same reason. Frozen-input hashing is a host filesystem concept.--auditis rejected (E178). Compiling and running mutants needs process isolation and a host filesystem; a later HIL audit is a separate project.--liststill works (it is static).- The cache is disabled and
--jobsis ignored. One image runs once.--no-cacheis accepted and has no effect. Test timeouts are the runner's wall-clock timeout; the 100 msmax_test_msrule is host-only, and anonetest that needs a clock usesclock_ms. - Each test starts from the image's initial static state. Before each test the runner copies the
.dataload image and zeroes.bss, keeping its own counters in a smallnoinitblock. Tests are order-independent, and a test that needs a configured peripheral configures it itself. - The semihosting channel is a harness facility, not a capability. Program code cannot call it
directly; only the generated test runner, the trap hook and the exit path can. A program's
printstill needs a console capability.
A trap in a test prints trap: <kind> at <file>:<line> and exits 1, matching the hosted trap
format, so the same tests/traps expectations can be reused where they make sense.
test fn helpers work normally. The rule that a test must reach an assertion and a project function
still applies; a register read-back assertion satisfies it and constant_assert sees a value that
depends on the device.
3.5 Diagnostics E170-E179
| Code | Stage | Meaning | Fix |
|---|---|---|---|
E170 | check | a builtin, vector or peripheral needs a capability the target did not grant, or the feature does not exist on this target | add the capability to kern.target, or remove the use |
E171 | check | MMIO address is not a compile-time constant | use a board.* constant or an integer literal |
E172 | check | MMIO address is outside every declared peripheral range, or does not fit in 32 bits | declare the range, or fix the constant |
E173 | check | MMIO access is not naturally aligned for its width | use an aligned address or a narrower width |
E174 | check | interrupt fn violates the handler ABI (parameters, result, error, contracts, pub, direct call, fail) | make it a plain fn, or remove the offending part |
E175 | check | vector is unknown, duplicated, not user-assignable, or its priority is out of range | use a board vector name, one handler per vector |
E176 | check | critical misuse: a non-local exit, a blocking/allocating operation, or a static var access outside a critical context | restructure the block, or wrap the access |
E177 | check | an interrupt fn reaches an operation that is not ISR-safe (allocation, I/O, blocking, software interrupt) | move the work to a task, or use a flag |
E178 | check | a host-only test feature (test io, inputs, --audit) on a none target | use a plain test, or run it on a hosted target |
E179 | load/check | invalid kern.target (unknown key/capability, overlapping ranges, bad memory, board name, flag mismatch) | fix the profile |
The codes are contiguous and reserved for M3. Hosted diagnostics stay as they are; a hosted build
normally sees only E170/E178 from this block (plus E179 for a malformed profile), because the
other forms are rejected earlier or are legal as compiler barriers (critical, fence, static).
4. Sketches
These are source sketches, not compiled by the M3 harness. They show the intended shape and the
capability requirements; the runnable versions live in tests/embedded/ with expect files.
4.1 Blink a GPIO (STM32F103; gpio, rcc, systick)
use board
const LED_SET: u32 = 32 // PA5, low half of BSRR
const LED_RESET: u32 = 2097152 // PA5, high half of BSRR
const PA5_OUTPUT_2MHZ: u32 = 2097152
const CLOCK_ENABLE_GPIOA: u32 = 4
fn main() {
write32(board.RCC_APB2ENR, bit_or(read32(board.RCC_APB2ENR), CLOCK_ENABLE_GPIOA))
// simplified: a real initialiser masks the PA5 field before writing CRL
write32(board.GPIOA_CRL, PA5_OUTPUT_2MHZ)
var on = false
while true {
if on {
write32(board.GPIOA_BSRR, LED_SET)
} else {
write32(board.GPIOA_BSRR, LED_RESET)
}
on = !on
_ = sleep_ms(500)
}
}
BSRR is write-only in effect: the set and reset halves are separate events, which is exactly why
the compiler may not merge or eliminate the two writes. Reading ODR instead would be a cached
value and a different device interaction; the sketch deliberately uses BSRR.
4.2 UART echo with an interrupt (QEMU uart0; uart)
use board
const UART_RX_FULL: u32 = 2 // CMSDK STATE.RXFULL
const UART_TX_EMPTY: u32 = 4 // CMSDK STATE.TXEMPTY
const UART_RX_INT: u32 = 2 // CMSDK INTENSET.RXINT
const UART_ENABLE: u32 = 3 // CTRL.TXEN | CTRL.RXEN
interrupt fn uart0() priority 5 {
let status = read32(board.UART0_STATE)
if bit_and(status, UART_RX_FULL) != 0 {
let byte = read8(board.UART0_DATA)
while bit_and(read32(board.UART0_STATE), UART_TX_EMPTY) == 0 {
continue
}
write8(board.UART0_DATA, byte)
}
}
fn main() {
write32(board.UART0_CTRL, UART_ENABLE)
write32(board.UART0_INTENSET, UART_RX_INT)
while true {
continue
}
}
The TXE spin is bounded by the UART baud rate and is acceptable for an echo. A production driver keeps a one-byte static buffer and enables TXE only while a byte is pending; the ring-buffer pattern is in §4.4. The handler never allocates, never prints and never yields, so it is ISR-safe by construction.
4.3 SysTick handler (STM32F103; systick)
use board
const SYSTICK_RELOAD_1MS: u32 = 7999 // 8 MHz / 1000 - 1
const SYSTICK_ENABLE: u32 = 7
const ONE_SECOND_MS: u64 = 1000
static var TICKS: u64 = 0
interrupt fn systick() priority 15 {
TICKS += 1
}
fn uptime_ms() -> u64 {
var snapshot: u64 = 0
critical {
snapshot = TICKS
}
return snapshot
}
fn main() {
write32(board.SYSTICK_RVR, SYSTICK_RELOAD_1MS)
write32(board.SYSTICK_CVR, 0)
write32(board.SYSTICK_CSR, SYSTICK_ENABLE)
var last: u64 = 0
while true {
let now = uptime_ms()
if now >= last + ONE_SECOND_MS {
last = now
print("one second\n") // console comes from the profile
}
}
}
TICKS is 64-bit, so a task read is two words and can tear if the handler runs between them; the
critical block is what makes the snapshot consistent. TICKS += 1 itself is safe because only
the handler writes it; if a higher-priority handler also wrote it, that write would need critical
as well. The handler is an entry point, so unused_function must not flag it. The console setup
(USART1 clock, pins and baud rate) is omitted; the profile declares usart1 as the console.
4.4 A critical section shared with an ISR (ring buffer; uart)
use board
const CAPACITY: u32 = 64
const UART_RX_FULL: u32 = 2
static var HEAD: u32 = 0
static var TAIL: u32 = 0
static var QUEUE: [u8; 64]
fn push(byte: u8) -> bool {
var accepted = false
critical {
let next = (HEAD + 1) % CAPACITY
if next != TAIL {
QUEUE[next] = byte
HEAD = next
accepted = true
}
}
return accepted
}
fn pop() -> u8 {
var byte: u8 = 0
critical {
if TAIL != HEAD {
TAIL = (TAIL + 1) % CAPACITY
byte = QUEUE[TAIL]
}
}
return byte
}
interrupt fn uart0() priority 5 {
if bit_and(read32(board.UART0_STATE), UART_RX_FULL) != 0 {
let byte = read8(board.UART0_DATA)
if !push(byte) {
return // queue full: drop the byte, RXFULL is already cleared
}
}
}
fn main() {
while true {
let byte = pop()
if byte != 0 {
write8(board.UART0_DATA, byte)
}
}
}
push and pop both access static var inside critical, so the same functions are legal from
the handler and from the task. If push had read HEAD outside the block, the checker would
report E176 at the task call, not at the handler call. The [u8; 64] array is a fixed array from
M3; indexes use usize (u32 on none) after M0. The sentinel 0 in pop is a simplification; a
real driver returns a (byte, ok) pair or a small enum.
5. Testing
5.1 QEMU semihosting
The primary M3 gate is mps2-an385 on Cortex-M3, with qemu-sifive-e for RV32 once M1/M2 support it.
kern build tests/embedded/blinky --target thumbv7m-none --board qemu-mps2-an385
qemu-system-arm -M mps2-an385 -cpu cortex-m3 -nographic \
-semihosting-config enable=on,target=native \
-kernel build/blinky.elf
- The trap hook and the test runner use ARM semihosting
SYS_WRITE0for output andSYS_EXIT_EXTENDED(reasonADP_Stopped_ApplicationExit) so the failure count is the process exit code. A target without the extended call usesSYS_EXITwith 0/1 and prints the count in the final summary. A trap exits 1 withtrap: ...on stdout. -semihosting-configis explicit; no profile may enable it implicitly for a real board.- The runner has a wall-clock timeout (default 10 s per image) and treats a timeout as a failure.
tests/run_embedded.shbuilds each case, runs QEMU, checks the exit code, thekern-test:lines and theexpectfile, and prints onePASS/FAILline per case. It does not use Docker because QEMU and the ARM/RISC-V toolchain are host tools; CI installs them in theembeddedjob.- The hosted harness (
tests/run.sh --host-only) is untouched and must stay green. M3 adds a separateembeddedjob, not a new case type in the host loop.
5.2 Register-level assertions
A test on none can assert device state directly. Safe read-back registers on the QEMU board:
test "gpio data is readable" {
write32(board.GPIO0_DATA, 1)
assert read32(board.GPIO0_DATA) == 1
write32(board.GPIO0_DATA, 0)
assert read32(board.GPIO0_DATA) == 0
}
test "uart control keeps its bits" {
write32(board.UART0_CTRL, 3)
assert read32(board.UART0_CTRL) == 3
}
Use registers that are specified as read/write mirrors (CMSDK GPIO DATA, UART CTRL/BAUDDIV,
dual-timer LOAD). Do not assert on write-only, read-to-clear or free-running registers; those need
a behavioural test (interrupt delivered, byte echoed, counter advanced). This distinction is part
of the test guidance, not a language rule.
For handlers, raise(board.<VECTOR>_VECTOR) (M3.2) injects a software interrupt so a test can
exercise the handler without a device stimulus. It is a test aid, not a way to call the handler:
the handler still runs only through the vector path, with the real ABI and priority.
5.3 What needs hardware-in-the-loop
QEMU proves the language, the ABI, the vector table, the linker layout and the driver logic against the devices it models. It does not prove:
| Behaviour | Why QEMU is insufficient | Gate |
|---|---|---|
| STM32 RCC/clock tree, flash wait states | QEMU does not model STM32 RCC or flash | HIL |
| Real UART baud rate, framing, flow control | QEMU's UART is a model, not a baud generator | HIL |
| Interrupt latency and priority preemption on silicon | QEMU timing is not the core's timing | HIL |
| ESP32-C3 interrupt matrix, SysTimer, GPIO | no upstream C3 machine | HIL / vendor QEMU |
Deep sleep, wfi wake, power | not modelled | HIL |
| Electrical behaviour, pin mux, external devices | out of scope | board bring-up |
| DMA, caches, MPU | out of M3 | later |
QEMU also does not model STM32 peripherals: the mps2-an385 board has CMSDK devices, not STM32
ones. An STM32 profile can be compiled and its runtime/vector logic checked on QEMU, but its
register behaviour needs HIL. The HIL job is one STM32F103 and one ESP32-C3, flashed with OpenOCD or
esptool, running the same test image and reporting over UART in the kern-test: format. It is a
nightly/manual gate, not a per-commit gate, and it never replaces the QEMU gate.
5.4 Optional: a host bus model
A later M3.x option is kern test --target thumbv7m-none --emulate: compile for the host but lower
readN/writeN through a table-backed bus model, so ring-buffer and driver logic can be tested in
milliseconds without QEMU. It is not required for M3 and it must never be presented as a substitute
for the QEMU gate: it cannot test vectors, priorities or masking. If it is added, critical is a
compiler barrier and the bus model records accesses in order, which makes the volatile ordering
rules themselves testable.
6. Files and impact
6.1 Stage0 (Rust)
| File | Change |
|---|---|
src/lex.rs | keywords interrupt, critical, static; priority is contextual after an interrupt signature. read8/read16/read32/write8/write16/write32/fence stay identifiers resolved as builtins. |
src/ast.rs | Ty::U16; Func.is_interrupt and Func.priority; SK::Critical; a StaticDef table and Prog.statics; the new builtin names in is_builtin; target-profile types if they live here rather than in src/target.rs. |
src/parse.rs | parse interrupt fn name() [priority N], critical {}, static [var] NAME: Type [= literal]; keep read32(...) as an ordinary call. |
src/check.rs | builtin signatures and new B_READ8..B_WRITE32, B_FENCE ids; u16 rules; constant-address evaluation; range/capability/alignment checks (E170-E173); handler ABI and vector checks (E174/E175); critical and shared-static checks (E176); ISR-safety summaries (E177); width-generic bit builtins. |
src/target.rs (new) | kern.target parser and validator, built-in profiles, the generated board symbol table, flag/file reconciliation, E179. |
src/effects.rs (new) | purity, allocation, blocking, console and shared-static summaries; ISR-safe closure. Alternatively extend the call-graph walk in src/contracts.rs; a separate file keeps check.rs from growing. |
src/ownership.rs | critical early-exit checks (or emit them from check.rs); static var types are non-owning and cannot be borrowed as a slice. |
src/rules.rs | exempt interrupt fn from unused_function (and from unused_pub/untested_pub_fn, which are moot if handlers cannot be pub); treat critical as a block for empty_block; adjust magic_number's fix text to point at board.* constants. No new quality rules: the ISR constraints are correctness checks, not style. |
src/format.rs | canonical formatting for the three new forms and for priority. |
src/gen.rs, src/gen/expr.rs, src/gen/stmt.rs | target variants for Thumb/RV32 (M0); volatile load/store with the ordering model; fence; critical prologue/epilogue; static data emission; handler prologue/epilogue and the loop-poll suppression. |
src/gen/board.rs (new) | vector table, reset, priority setup, default handler, semihosting/halt trap path, linker-script symbols and board startup. Keeping it out of gen.rs matches the existing per-feature split. |
src/gen/support.rs, src/gen/runtime.rs | emit MCU runtime only when the target is none; no hosted helpers in an MCU image; the trap hook and exit path are board-selected. |
src/main.rs | `--target thumbv7m-none |
src/project.rs | locate and load kern.target; reserve the board module on none. |
src/test_runner.rs, src/test_hash.rs, src/test_inputs.rs, src/test_audit.rs | one-image none test mode, E178 for test io/inputs/--audit, no cache/jobs, harness channel. |
src/contracts.rs | MMIO, fence and critical are impure in contract predicates (E160). |
src/walk.rs | walk critical and static declarations for the analyses and rules. |
src/elf.rs, src/a64.rs, src/x64.rs | no change in M3. none builds use clang/LLD in M1-M3; the direct Thumb/RV32 encoders and ELF32 writer are M5. |
6.2 Self-hosted compiler (Kern)
| Area | Files | Change |
|---|---|---|
| Lexer | compiler/src/lexer/token.kn, scan.kn | keyword ids and scanning for interrupt, critical, static; contextual priority. |
| Model | compiler/src/model/kinds.kn, records.kn, program.kn, tables.kn | function flags/priority, static definitions, critical node/list, target-profile tables, board symbols. |
| Parser | compiler/src/parser/functions.kn, declarations.kn, statements.kn | the three forms; priority clause. |
| Typing | compiler/src/typing/builtins.kn, functions.kn, check.kn, statements.kn, new compiler/src/typing/target.kn | builtin signatures, u16, handler ABI, critical/static rules, address and capability checks. |
| Effects | compiler/src/effects/analyze.kn, validate.kn | hardware class, ISR-safe summaries, critical context, none test admission. |
| Backend | compiler/src/backend/generate.kn, machine.kn, state.kn, data.kn, statements.kn, expressions.kn, functions.kn; new vectors.kn, startup.kn | volatile ops, fences, static data, critical, handler stubs, vector table, reset and priorities; 32-bit register/stack rules from M0. |
| Runtime | new compiler/src/runtime_mcu/*, compiler/src/runtime/emit.kn | trap hook, semihosting, exit, SysTick, board startup; parallel to runtime_arm/runtime_x64. |
| Rules | compiler/src/rules/functions.kn, used.kn, table.kn | unused_function exemption for handlers; no new rule ids. |
| Format | compiler/src/format/* | the three forms and priority. |
| Spec | compiler/src/spec/print.kn | must match SPEC.md byte for byte. |
| Target data | new compiler/src/target/* (or a generated builtin.kn) | the same profiles as stage0, with a parity test. |
| Runner/cache/inputs | compiler/src/runner/*, testcache/*, inputs/load.kn, testimage/* | none one-image run, no cache/jobs/audit, E178. |
| CLI/driver | compiler/src/cli/*, driver/*, toolchain/* | target/board flags, profile discovery, clang/LLD invocation, linker script, QEMU runner. |
6.3 Spec, tests, examples and CI
| Path | Change |
|---|---|
SPEC.md | targets and the none profile; static; MMIO builtins and address rule; interrupt fn and ABI; critical; capability model; E170-E179; test behaviour on none. |
compiler/src/spec/print.kn | regenerate from SPEC.md; the self-host proof compares them. |
README.md, EMBEDDED.md | follow-up status and user-facing tables. Not part of this document-only commit, but required before M3 ships. |
targets/*.target (new) | canonical built-in profiles; embedded by both compilers and compared by a parity test. |
tests/embedded/<case>/ (new) | src/main.kn, kern.target, expect with ok lines, flash/RAM budget and runner. |
tests/run_embedded.sh (new) | build, run QEMU, check output/exit/size, one PASS line per case. |
tests/test_mmio.sh (new) | E170-E179 fixtures, including non-constant, out-of-range and unaligned addresses, handler ABI errors, unknown vectors, critical exits, ISR-unsafe calls, profiles. |
tests/errors/E17*.kn (new) | one fixture per diagnostic, in the existing // expect: format. |
tests/projects/* (new) | profile errors (E179) and a project with a valid kern.target. |
examples/mcu/ (new) | the four sketches, kept out of the hosted examples/*.kn loop. |
.cip/pipeline.json, .cip/impact.sh | an embedded job with QEMU (not queue-safe until the image ships QEMU), path claims for targets/* and tests/embedded/*; hosted jobs unchanged. |
bench/bench.py | optional compile-time measurement for none; runtime benchmarks are not meaningful under QEMU. |
6.4 Phased sequence
Each phase is gated on stage0 and on the hosted corpus staying byte-identical. M3.0-M3.4 land in stage0 first for fast iteration; M3.5 brings the self-hosted compiler to feature parity and is the hard gate before M4. No phase is considered shipped until the hosted suite passes in both compilers.
| Phase | Deliverable | Acceptance |
|---|---|---|
| M3.0 | kern.target parser/validator, built-in profiles, board constants, capability plumbing, E179; new keywords and AST, but MMIO/handlers still rejected | hosted suite unchanged; profile fixtures pass; kern check rejects a bad profile and a use without a grant |
| M3.1 | readN/writeN/fence, address evaluation, range/capability/alignment checks (E170-E173), volatile IR and Thumb/RV32 lowering; u16 and width-generic bit builtins | QEMU register read-back test; non-constant/out-of-range/unaligned fixtures; size budget for the smallest image |
| M3.2 | interrupt fn, vector table, reset/priorities, handler ABI, critical, E174-E176 | QEMU UART echo and SysTick handler; priority override test; no allocation in the image |
| M3.3 | static/static var, shared-state rule, critical-context analysis, ISR-safety summaries, E177 | ring-buffer test shared by a handler and a task; ISR-safety fixtures; stack/ISR report |
| M3.4 | STM32F103/F407/ESP32-C3/QEMU profiles, none test runner, E178, run_embedded.sh, size report, HIL harness | kern test under QEMU; flash/RAM budgets; optional HIL smoke on one board |
| M3.5 | self-hosted implementation, SPEC.md parity, byte-identical bootstrap | tests/test_selfhost_cli.sh --host-only and the embedded suite through stage3; full feature suites in both compilers |
6.5 Size budgets
M3 uses the EMBEDDED.md budgets and adds three M3-specific cases. The numbers are baselines,
enforced at M3.4 and tightened at M4; a regression over 5% fails.
| Image | Flash | RAM | Notes |
|---|---|---|---|
empty main + vectors/reset | 1 KiB | 256 B | table, reset, .data/.bss |
| blinky + SysTick | 3 KiB | 1 KiB | no console |
| UART echo + interrupt | 3.5 KiB | 1 KiB | handler + driver |
| critical ring buffer | 4 KiB | 1.5 KiB | 64-byte queue |
| test image, 4 register tests | 5 KiB | 2 KiB | harness + assertions |
The image must also show no allocator symbols: nm has no kern_alloc, malloc, mmap or
free unless the profile declares a heap, and readelf shows .vectors at the profile's load
address. Those two checks are part of run_embedded.sh, not a manual review.
6.6 Risks
- Optimizer/volatile drift. O1/O2 are on the critical path; a scheduler that moves a volatile op is a silent, hardware-only bug. Mitigation: the IR properties in §1.4, an optimizer fixture that asserts event order, and a QEMU test that counts accesses to a read-sensitive register.
- QEMU is not a board. It validates the language and runtime, not STM32 peripherals or timing. Mitigation: state it in every test report, keep HIL for the behaviours in §5.3, and never tune a driver's timing against QEMU.
- ISR stack. A deep handler chain can overflow a 2 KiB main stack. Mitigation: per-function
stack reporting,
isr_stackin the profile, and a startup canary in debug images. - Type churn.
u16and width-generic bit builtins touch M0's checker, layout and both backends. Mitigation: land them in M3.0 behind the existing integer tests; they are small and independent of MMIO. - Module privacy and vectors. A handler in a private module must still be linkable. The
compiler resolves handlers before codegen;
kern apiandunused_functionmust agree. Mitigation: handlers are roots in the call graph and are excluded from API output. - Profile drift. Hand-written register constants can disagree with a datasheet. Mitigation: range checks catch out-of-peripheral values; an SVD importer is a later tool, not a language feature.
- Capability strictness. Bring-up often wants "just one register" outside the profile.
Mitigation: edit the profile, which is reviewable; do not add an
--allow-undeclaredescape, because it would invalidate the central claim. - The
boardmodule is magic. It is a reserved name with generated contents. Mitigation: document it, reject a userboardmodule with a clearE179, and keep the generated surface only constants. - Semihosting is a host escape. It is used only by the harness/trap/exit path, never by
program code. Mitigation: gate it behind
capabilitiesforprint, and keep it out oftest io. - Both compilers. Every phase doubles. Mitigation: the hosted corpus must stay identical from M3.0, and M3.5 blocks M4 until the self-hosted compiler passes the embedded suite.
7. Open decisions and recommendations
7.1 Constant-address builtins vs Mmio[T]
Options. (a) read32(ADDR)/write32(ADDR, v) with a constant address. (b) A generic
Mmio[T] value created from a constant base, with load/store methods.
Recommendation: (a). It is smaller in every dimension: no new type, no constructor, no
monomorphisation, no lifetime or aliasing rule for a value that holds an address, and no way to
store, copy, compare or forge the address. The check is local to the call, so diagnostics point at
the access, and the optimizer sees one volatile op rather than a load through an abstract object.
Mmio[T] would still need a constant base and a declared range to be safe; once those exist, the
value adds only the ability to pass a peripheral around, which a module and board.* constants
already provide.
The one case for a token. If a driver must be generic over two instances of the same peripheral
(usart1 vs usart2) and cannot be monomorphised by a module, add a zero-sized Peripheral
token generated from the profile: fn write_byte(port: Peripheral[Usart], byte: u8). The token
contains no address; the type selects the constant range at compile time. This is a later,
additive change and does not weaken (a). Do not add an Mmio[T] that stores an address.
7.2 Interrupt attribute vs board manifest
Options. (a) interrupt fn usart1() in source, matched by name to a vector declared in
kern.target, with priority N in source. (b) The manifest names the handler function (for
example vector usart1 = board.usart1). (c) A separate source declaration that binds a vector to a
function.
Recommendation: (a). It keeps the manifest numeric and board-owned (numbers, default
priorities, capability), keeps the handler self-describing at its definition, and needs no
cross-file symbol reference from a config file into the module system. Duplicate and unknown names
are checked in one pass over the program. (b) would force the profile to understand modules,
visibility and symbol resolution, and would make a board file depend on source structure; (c)
adds a third declaration form and a second place to look for a handler. priority stays optional
so the board default is the common case.
7.3 critical vs atomics
Options. (a) critical only in M3; Atomic[T] later, lowered to masking. (b) Atomic[T] in
M3, with a memory-order model. (c) Lock-prefixed atomics (LDREX/STREX, AMO*).
Recommendation: (a). The hardware is single-core, the scheduler is cooperative, and the only
concurrency is a declared handler. Masking is three instructions, works on Cortex-M0 (no
LDREX/STREX) and on RV32IMC (no A), and matches the model in EMBEDDED.md. A memory-order
model is a large design that buys nothing until there are threads; Atomic can be a thin library
over critical when the concurrency work starts. Lock-prefixed instructions are unavailable or
slower on the target cores and do not compose with the scheduler.
7.4 Secondary decisions
| Decision | Recommendation | Reason |
|---|---|---|
read16/write16 type | add u16 in M3.0 | exact widths; zero-extending to u32 hides a truncation at the write |
| Address constants | generated board.* names, not per-project literals | one source of truth; magic_number stays useful; a typo is caught by the range |
MMIO in test on none | allow; no new test device form | the device is the subject; a new form adds syntax for no safety |
| Core peripheral window | reserved; not declarable | critical must be the only mask control; no vector-base or MPU writes |
fence() | explicit builtin, implicit in critical | one instruction when needed; no cost on every access |
Early exits from critical | forbid in M3 (E176) | straight-line mask/restore; revisit if real code needs it |
interrupt fn visibility | never pub, never callable | no API surface; the vector table is the only caller |
| Signed register values | unsigned only in M3 | no bit-preserving cast yet; i32(u32) is a checked conversion that would trap on bit 31 |
raise(vector) for tests | add in M3.2 | deterministic ISR tests without a peripheral stimulus; cheap on both cores |
static var of struct type | reject in M3 | field-wise critical tracking is a larger analysis; scalars and scalar arrays cover the patterns |
8. What M3 does not do
- No
unsafe, no pointer type, no reference to a device, no address arithmetic, noascast. - No DMA, cache maintenance, MPU, sleep modes or power management.
- No concurrency: no tasks, channels,
Atomic,Sharedor memory-order model. M6 builds on the contract in §2.6. - No direct Thumb-2/RV32 encoder or ELF32 writer; M3 uses the external toolchain from M1, and M5 removes it.
- No SVD import, pin-mux abstraction, HAL or driver framework. The profile and
board.*constants are the whole board interface. - No FPU context, no Xtensa, no SMP. ESP32-S3 remains after the RISC-V C3.
- No host simulation as a substitute for QEMU; the optional bus model in §5.4 is an addition, not a replacement.