Kern
On this page

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:

FormKindPurpose
read8/read16/read32(ADDR)builtin expressionone volatile load from a constant address
write8/write16/write32(ADDR, value)builtin statementone volatile store to a constant address
fence()builtin statementcompiler + hardware memory barrier
interrupt fn name() [priority N] { ... }declarationan entry point called by the vector table
critical { ... }statementmask maskable interrupts, restore on exit
static [var] NAME: Type [= literal]declarationfixed 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 var scalars and fixed arrays, and every access to one is either inside a handler or inside critical. 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 read32 is four bytes, little-endian.
  • Widths are exact. There is no implicit widening, narrowing or sign extension; a wrong type is the ordinary E021 type error. read16 needs u16, which M3 adds to M0's integer set (see §7).
  • writeN returns void and is used as a statement. readN returns 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. The discarded_result rule 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_NAME is an ALL_CAPS constant of type u8/u16/u32/u64 whose value fits in 32 bits, including board.* 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 static is not a constant expression. let addr = 0x40013800 followed by read32(addr) is E171.
  • 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:

  1. The target is a none target. A hosted target has no declared peripherals: E170.
  2. The address is a constant expression: otherwise E171.
  3. The address fits in 32 bits and the interval [address, address + width) lies entirely inside exactly one declared peripheral range: otherwise E172.
  4. address % width == 0: otherwise E173.
  5. The range's capability is in the profile's capabilities list: otherwise E170.

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, or fence();
  • 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 BSRR depend 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 following isb where 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 E173 forbids 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[]u8readN/writeN
Addressa run-time pointer plus lengtha compile-time constant, never a value
Creationalloc, read_file, sub-slice, literalimpossible: no address-producing expression
Boundsrun-time checks against lencompile-time range check
Ownershipowned or borrowed, with free/lifetime rulesno owner, no lifetime, no cleanup
Volatilityordinary memory: cacheable, foldable, reorderableobservable event, never cached or folded
Aliasingordinary aliasing rulesmay alias other device addresses; no assumption
Lengtha u64/usize in the valuefixed by the builtin name
Failuretraps at run timerejected 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

CodeTriggerExample fix
E171the address is not a constant expressionuse board.USART1_SR, not a local
E172the address is outside every declared range, or does not fit in 32 bitsdeclare the range, or use the board constant
E173the access is not naturally aligned for its widthuse read32 at a 4-byte boundary, or read8 for a byte lane
E170the range is known but its capability is not granted, or the target is hostedadd 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 fn is a declaration form, not an expression. The handler is an entry point: it is never called by name. A direct call is E174.
  • 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 N is optional; without it the profile's default priority for that vector applies. N is in 0 .. 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 is E175.
  • 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 contain return with no value.

The ABI is an ordinary AAPCS/RISC-V calling convention function that happens to be entered from an exception, with these additions:

ItemCortex-M3/M4RV32 (ESP32-C3)
Saved by hardwarer0-r3, r12, lr, pc, xPSR (+ FP frame if enabled)nothing
Saved by the generated stubEXC_RETURN (lr), 8-byte stack alignmentmepc, mstatus, ra, t0-t6, a0-a7
Saved by the handler prologuecallee-saved r4-r11, lr as usedcallee-saved s0-s11, ra as used
Returnbx lr with EXC_RETURN (or pop {pc})restore mepc/mstatus, mret
StackMSP; a task's PSP once M6 existsthe current task stack; no switch in M3
Floating pointno FP in M3; FPU disabled, lazy stacking offno FPU
Resultnonenone
Allocationnone, transitivelynone, 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_handler prints unhandled irq N when 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 .data is copied and before main. The runtime groups all bits as preemption priority (no subpriority split in M3).
  • On RISC-V the "table" is a dispatch table plus mtvec and 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, NMI and the fault vectors) are board policy. A profile may expose a fault vector, but critical does not mask NMI or HardFault (§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 i on entry, dsb; msr PRIMASK, r0; isb on exit;
    • RV32: read and clear mstatus.MIE on entry, restore it on exit, with fence before the restore.
  • critical masks maskable interrupts only. On Cortex-M, NMI and HardFault are not maskable; the configurable-priority fault handlers are masked like other interrupts. On RV32, the machine trap path follows the same rule. An NMI or HardFault can therefore still observe a half-updated static var; a fault handler must not read application static var state. The model does not claim atomicity against faults, only against interrupts.
  • A critical may contain MMIO, calls, loops, if/match, and nested critical blocks. It must not contain an operation that can block indefinitely or allocate: sleep_ms, channel/task operations, file or console I/O, and alloc are E176. A critical is a bounded region.
  • Early exits that leave the block (return, fail, break/continue that target an outer loop) are E176 in 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.
  • critical in a contract predicate is E160 (contracts are read-only and side-effect free).
  • On a hosted target critical is a compiler barrier only; there are no interrupts to mask, and this lets shared-state logic be unit-tested on the host. On none it masks.
  • An empty critical {} is an empty block and the existing empty_block rule 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 no LDREX/STREX at all; on M3/M4 there is, but masking is fewer instructions and works uniformly on both cores.
  • RISC-V has A extensions on some parts, but ESP32-C3 is RV32IMC (no A), 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:

  1. static (immutable) is readable from anywhere, including contracts. Its initializer is a literal, so it lives in .rodata or .data with no startup code.
  2. static var may 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 a static var array is also rejected, because the view could escape the critical region. Scalars are naturally aligned; a u64 static is 8-byte aligned even on a 32-bit target.
  3. For every static var, the checker collects its access contexts: the task context and each interrupt fn that can reach an access. The rules are:
    • a task-context access requires critical if any handler accesses the cell, because a handler can preempt a task between a load and a store;
    • a handler access requires critical if 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 a needs_critical summary per function and reports E176 at the first access or call that violates the rule.
  4. The address of a static is 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 var flag, push one byte into a static var ring, or bump a counter. A handler access needs critical only when another handler also touches the cell; the task side uses critical whenever any handler touches it (§2.5).
  • The scheduler's ready queue and timer list are ordinary task-side data protected by critical when 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 fn and 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_ms in a handler is E177 for 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 var outside critical except a cell that is private to that handler (no other handler and no task accesses it);
  • has no fail path and no try that 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, memory and capabilities are 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 are E179, so a typo cannot silently grant nothing.
  • memory sizes accept K and M (powers of 1024). heap = 0 is the default; stack is the main stack; isr_stack is the headroom reserved above the current stack for the deepest handler chain. heap + stack + isr_stack <= ram is checked (E179).
  • flash_base/ram_base are 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 registers entry is a byte offset from range.lo. It generates board.<PERIPHERAL>_<REGISTER> constants (uppercase, for example board.GPIOA_BSRR, board.USART1_SR). Every peripheral also gets board.<PERIPHERAL>_BASE, and every vector gets board.<VECTOR>_VECTOR (its number, for raise). The board module is implicit and reserved on none targets; a user module with that name is E179.
  • registers is 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 to magic_number style rules.
  • console = "semihosting" is valid only when semihosting is in capabilities.
  • A vector block is user-assignable unless it sets user = false. The default is true for external vectors and SysTick, and false for NMI and the fault vectors. A user = false vector stays in the table but always uses kern_default_handler.
  • runner selects 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.

FeatureRequirementFailure
readN/writeNaddress in a granted peripheral rangeE170/E172/E173
interrupt fn vvector v declared, user-assignable, its capability grantedE175/E170
raise(v) (optional test aid)v is a declared, user-assignable vector; task or test context onlyE175/E177
critical, fencecore feature, no capability—
clock_ms, clock_ns, sleep_mssystickE170
print, print_int, print_errorconsole peripheral capability, or semihostingE170
alloc, free (heap path), arena, arena_alloc, arena_new, truncateheap > 0E170
arena_get, arena_set, null_handle, is_null, len, checked conversions, bit builtinsno capability; the arena must already exist—
read_file, write_file, read_dir, try_read_file, path operationsnone on noneE170
spawn_process, wait_process, process_status, stop_processnone on noneE170
get_env, current_dir, executable_path, arg, arg_countnone on noneE170
image_open, image_spawn, image_closenone on noneE170
exit_process, target_idalways; exit maps to semihosting/halt—
test io, inputs [...], --auditnone on noneE178

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 mmio capability. The peripheral range is the permission; granting uart grants 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.
  • print maps to the declared console. If the console is semihosting, it uses the semihosting write call and requires semihosting; if it is usart1, it uses that peripheral and requires uart. The console is never implicit, so a program cannot accidentally grab a UART that a driver owns.
  • target_id() gains 3 = thumbv7m, 4 = thumbv7em, 5 = riscv32 (IMC or IMAC). It identifies the build target family, as it does on hosted targets, and needs no capability.
  • free on a static/arena value is a type error as before; the heap gate only affects alloc.

The same features on a hosted target:

FeatureHostednone
readN/writeNE170 (no declared peripherals)range-checked
fencecompiler barriercompiler + hardware barrier
interrupt fnE170 (no vector table)profile vector
criticalcompiler barrier onlymask/restore
static / static varordinary static storageshared-state rule
test io, inputssupportedE178

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 replaces main as the entry point (so main does not run), calls each test, prints kern-test: ok <name> or kern-test: FAIL <name> through the harness channel, and exits with the failure count (0 = success). The kern-test: prefix keeps harness lines distinct from a program's print.
  • MMIO is allowed in a test on a none target. 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 a hardware class that is legal in a test only on none.
  • test io is rejected (E178). It exists to exercise the host OS, and every none target 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.
  • --audit is rejected (E178). Compiling and running mutants needs process isolation and a host filesystem; a later HIL audit is a separate project. --list still works (it is static).
  • The cache is disabled and --jobs is ignored. One image runs once. --no-cache is accepted and has no effect. Test timeouts are the runner's wall-clock timeout; the 100 ms max_test_ms rule is host-only, and a none test that needs a clock uses clock_ms.
  • Each test starts from the image's initial static state. Before each test the runner copies the .data load image and zeroes .bss, keeping its own counters in a small noinit block. 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 print still 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

CodeStageMeaningFix
E170checka builtin, vector or peripheral needs a capability the target did not grant, or the feature does not exist on this targetadd the capability to kern.target, or remove the use
E171checkMMIO address is not a compile-time constantuse a board.* constant or an integer literal
E172checkMMIO address is outside every declared peripheral range, or does not fit in 32 bitsdeclare the range, or fix the constant
E173checkMMIO access is not naturally aligned for its widthuse an aligned address or a narrower width
E174checkinterrupt fn violates the handler ABI (parameters, result, error, contracts, pub, direct call, fail)make it a plain fn, or remove the offending part
E175checkvector is unknown, duplicated, not user-assignable, or its priority is out of rangeuse a board vector name, one handler per vector
E176checkcritical misuse: a non-local exit, a blocking/allocating operation, or a static var access outside a critical contextrestructure the block, or wrap the access
E177checkan 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
E178checka host-only test feature (test io, inputs, --audit) on a none targetuse a plain test, or run it on a hosted target
E179load/checkinvalid 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.

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_WRITE0 for output and SYS_EXIT_EXTENDED (reason ADP_Stopped_ApplicationExit) so the failure count is the process exit code. A target without the extended call uses SYS_EXIT with 0/1 and prints the count in the final summary. A trap exits 1 with trap: ... on stdout.
  • -semihosting-config is 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.sh builds each case, runs QEMU, checks the exit code, the kern-test: lines and the expect file, and prints one PASS/FAIL line per case. It does not use Docker because QEMU and the ARM/RISC-V toolchain are host tools; CI installs them in the embedded job.
  • The hosted harness (tests/run.sh --host-only) is untouched and must stay green. M3 adds a separate embedded job, 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:

BehaviourWhy QEMU is insufficientGate
STM32 RCC/clock tree, flash wait statesQEMU does not model STM32 RCC or flashHIL
Real UART baud rate, framing, flow controlQEMU's UART is a model, not a baud generatorHIL
Interrupt latency and priority preemption on siliconQEMU timing is not the core's timingHIL
ESP32-C3 interrupt matrix, SysTimer, GPIOno upstream C3 machineHIL / vendor QEMU
Deep sleep, wfi wake, powernot modelledHIL
Electrical behaviour, pin mux, external devicesout of scopeboard bring-up
DMA, caches, MPUout of M3later

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)

FileChange
src/lex.rskeywords interrupt, critical, static; priority is contextual after an interrupt signature. read8/read16/read32/write8/write16/write32/fence stay identifiers resolved as builtins.
src/ast.rsTy::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.rsparse interrupt fn name() [priority N], critical {}, static [var] NAME: Type [= literal]; keep read32(...) as an ordinary call.
src/check.rsbuiltin 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.rscritical early-exit checks (or emit them from check.rs); static var types are non-owning and cannot be borrowed as a slice.
src/rules.rsexempt 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.rscanonical formatting for the three new forms and for priority.
src/gen.rs, src/gen/expr.rs, src/gen/stmt.rstarget 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.rsemit 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.rslocate 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.rsone-image none test mode, E178 for test io/inputs/--audit, no cache/jobs, harness channel.
src/contracts.rsMMIO, fence and critical are impure in contract predicates (E160).
src/walk.rswalk critical and static declarations for the analyses and rules.
src/elf.rs, src/a64.rs, src/x64.rsno 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)

AreaFilesChange
Lexercompiler/src/lexer/token.kn, scan.knkeyword ids and scanning for interrupt, critical, static; contextual priority.
Modelcompiler/src/model/kinds.kn, records.kn, program.kn, tables.knfunction flags/priority, static definitions, critical node/list, target-profile tables, board symbols.
Parsercompiler/src/parser/functions.kn, declarations.kn, statements.knthe three forms; priority clause.
Typingcompiler/src/typing/builtins.kn, functions.kn, check.kn, statements.kn, new compiler/src/typing/target.knbuiltin signatures, u16, handler ABI, critical/static rules, address and capability checks.
Effectscompiler/src/effects/analyze.kn, validate.knhardware class, ISR-safe summaries, critical context, none test admission.
Backendcompiler/src/backend/generate.kn, machine.kn, state.kn, data.kn, statements.kn, expressions.kn, functions.kn; new vectors.kn, startup.knvolatile ops, fences, static data, critical, handler stubs, vector table, reset and priorities; 32-bit register/stack rules from M0.
Runtimenew compiler/src/runtime_mcu/*, compiler/src/runtime/emit.kntrap hook, semihosting, exit, SysTick, board startup; parallel to runtime_arm/runtime_x64.
Rulescompiler/src/rules/functions.kn, used.kn, table.knunused_function exemption for handlers; no new rule ids.
Formatcompiler/src/format/*the three forms and priority.
Speccompiler/src/spec/print.knmust match SPEC.md byte for byte.
Target datanew compiler/src/target/* (or a generated builtin.kn)the same profiles as stage0, with a parity test.
Runner/cache/inputscompiler/src/runner/*, testcache/*, inputs/load.kn, testimage/*none one-image run, no cache/jobs/audit, E178.
CLI/drivercompiler/src/cli/*, driver/*, toolchain/*target/board flags, profile discovery, clang/LLD invocation, linker script, QEMU runner.

6.3 Spec, tests, examples and CI

PathChange
SPEC.mdtargets 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.knregenerate from SPEC.md; the self-host proof compares them.
README.md, EMBEDDED.mdfollow-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.shan embedded job with QEMU (not queue-safe until the image ships QEMU), path claims for targets/* and tests/embedded/*; hosted jobs unchanged.
bench/bench.pyoptional 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.

PhaseDeliverableAcceptance
M3.0kern.target parser/validator, built-in profiles, board constants, capability plumbing, E179; new keywords and AST, but MMIO/handlers still rejectedhosted suite unchanged; profile fixtures pass; kern check rejects a bad profile and a use without a grant
M3.1readN/writeN/fence, address evaluation, range/capability/alignment checks (E170-E173), volatile IR and Thumb/RV32 lowering; u16 and width-generic bit builtinsQEMU register read-back test; non-constant/out-of-range/unaligned fixtures; size budget for the smallest image
M3.2interrupt fn, vector table, reset/priorities, handler ABI, critical, E174-E176QEMU UART echo and SysTick handler; priority override test; no allocation in the image
M3.3static/static var, shared-state rule, critical-context analysis, ISR-safety summaries, E177ring-buffer test shared by a handler and a task; ISR-safety fixtures; stack/ISR report
M3.4STM32F103/F407/ESP32-C3/QEMU profiles, none test runner, E178, run_embedded.sh, size report, HIL harnesskern test under QEMU; flash/RAM budgets; optional HIL smoke on one board
M3.5self-hosted implementation, SPEC.md parity, byte-identical bootstraptests/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.

ImageFlashRAMNotes
empty main + vectors/reset1 KiB256 Btable, reset, .data/.bss
blinky + SysTick3 KiB1 KiBno console
UART echo + interrupt3.5 KiB1 KiBhandler + driver
critical ring buffer4 KiB1.5 KiB64-byte queue
test image, 4 register tests5 KiB2 KiBharness + 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

  1. 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.
  2. 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.
  3. ISR stack. A deep handler chain can overflow a 2 KiB main stack. Mitigation: per-function stack reporting, isr_stack in the profile, and a startup canary in debug images.
  4. Type churn. u16 and 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.
  5. Module privacy and vectors. A handler in a private module must still be linkable. The compiler resolves handlers before codegen; kern api and unused_function must agree. Mitigation: handlers are roots in the call graph and are excluded from API output.
  6. 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.
  7. Capability strictness. Bring-up often wants "just one register" outside the profile. Mitigation: edit the profile, which is reviewable; do not add an --allow-undeclared escape, because it would invalidate the central claim.
  8. The board module is magic. It is a reserved name with generated contents. Mitigation: document it, reject a user board module with a clear E179, and keep the generated surface only constants.
  9. Semihosting is a host escape. It is used only by the harness/trap/exit path, never by program code. Mitigation: gate it behind capabilities for print, and keep it out of test io.
  10. 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

DecisionRecommendationReason
read16/write16 typeadd u16 in M3.0exact widths; zero-extending to u32 hides a truncation at the write
Address constantsgenerated board.* names, not per-project literalsone source of truth; magic_number stays useful; a typo is caught by the range
MMIO in test on noneallow; no new test device formthe device is the subject; a new form adds syntax for no safety
Core peripheral windowreserved; not declarablecritical must be the only mask control; no vector-base or MPU writes
fence()explicit builtin, implicit in criticalone instruction when needed; no cost on every access
Early exits from criticalforbid in M3 (E176)straight-line mask/restore; revisit if real code needs it
interrupt fn visibilitynever pub, never callableno API surface; the vector table is the only caller
Signed register valuesunsigned only in M3no bit-preserving cast yet; i32(u32) is a checked conversion that would trap on bit 31
raise(vector) for testsadd in M3.2deterministic ISR tests without a peripheral stimulus; cheap on both cores
static var of struct typereject in M3field-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, no as cast.
  • No DMA, cache maintenance, MPU, sleep modes or power management.
  • No concurrency: no tasks, channels, Atomic, Shared or 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.

Source: M3-MMIO.md in the repository.