Kern
On this page

Kern compact language specification

Kern is a statically typed, ahead-of-time compiled language. Targets are macOS arm64, Linux arm64 and Linux x86-64. All use little-endian, 64-bit words (8-byte slots). kern wasm builds a wasm32-wasi subset: no tasks, no OS builtins. There are no classes, receiver methods, inheritance, garbage collector, exceptions, implicit numeric conversions, runtime interfaces or unqualified imports.

Source and names

Source is UTF-8. // begins a line comment. Whitespace separates tokens; semicolons are not used. A newline after return returns no value. A call's ( or index's [ cannot start a new line. Assignments evaluate the right side before the destination; compound assignments then load the destination and apply the operator. Identifiers contain ASCII letters, digits and underscores. Values/functions use snake_case; types, variants and type parameters use descriptive CamelCase; constants use ALL_CAPS. Type names need an uppercase initial and a lowercase letter.

A program is one .kn file or a folder with src/main.kn. Each folder under src/ is a module whose .kn files share one namespace; files in src/ form the root module. Paths/files are snake_case; build/ is output; no .kn files belong outside src/. Entry point: fn main() in src/main.kn, with no parameters, result, error or type parameters.

use parse.expr precedes all declarations and imports the module under its final segment, expr, in that file only. Use expr.parse(...), expr.Token, expr.MAX_LEN. There are no aliases, wildcards or root-module imports. Import cycles and colliding final segments are errors. Declarations are private to their module unless prefixed pub. Public struct fields and enum variants are public. Public signatures cannot expose private types or interface bounds.

use std.bytes imports a standard library module from $KERN_STD, else std/ beside the compiler's folder. Each std/<name>/ is module std.<name> (paths std/<name>/<file>.kn), laid out like src/; only imported modules load. std is reserved (src/std/ is E117); unknown std.x is E104 listing std modules. Std files are exempt from host rules/tests; kern test std and kern api std[.MODULE] check std.

Optional kern.packages in a project or package root lists dependencies, one per line (# comments): name = path (root-relative or absolute) or name (looked up in colon-separated $KERN_PACKAGES). Names are unique snake_case, excluding std (E117), main, src and local module folders (E118); missing folders/manifests are E119. A package's source root is src/ if present, else its root; declared vendored folders are allowed outside src/. Transitive manifests deduplicate diamonds by canonical path; cycles are E109. use pkg.mod or root-file use pkg (E104 if missing) loads only imported modules, exempt from host rules and tests.

Types and declarations

Types are i64, u64, i32, u32, u8, u16, usize, isize, bool, []Element, named structs/enums, Arena and Handle[Target]. Integer types are nominal. usize/isize are unsigned/signed target-word integers (64-bit hosted); i32/u32 are 32-bit and i64/u64 64-bit. Hosted scalar locals/fields occupy one 8-byte slot, including i32/u32, u8, u16 and bool. u8/bool slice elements use one byte; others use their slot layout. Struct fields have no packing or padding; enums use a tag slot plus the largest payload; slices use two slots, Arena three and Handle two. Slot values are canonical: unsigned zero-extended, signed sign-extended. Unannotated literals default to i64 (hosted); typed literals must fit their type. A slice is a pointer and usize length, not NUL-terminated. String literals have type []u8 and immutable static storage. Characters ('a', '\n') have type u8. Decimal and 0x integer literals allow _ separators. String/character escapes include \n, \r, \t, \0 and escaped quotes/backslashes.

const LIMIT: usize = 64
struct Span { lo: usize, hi: usize }
enum Token { Number(i64), Word([]u8), End }
fn add(first: i64, second: i64) -> i64 { return first + second }

Constants require an explicit type and a literal value. Struct literals specify every field exactly once: Span { lo: 0, hi: 1 }. Enum constructors are Token.End or Token.Number(1); empty constructors have no (). Struct/enum values contain their fields inline; direct recursive layouts are errors. Recursive graphs use handles. All slices share the syntax []Element, including nested slices and slices of structs/enums. There is no nullable ordinary reference.

Functions have named, typed parameters, an optional -> Result, optional ! Error, contracts, then a body. Omitted result means no value. Calls are positional. Hosted calls pass the first six argument words in registers and the rest on the stack; thumbv7m-none allows at most six argument words. Parameters borrow resources by default. &mut permits mutation through a unique borrow; the caller writes &mut place. own consumes resources; the caller writes move value. &mut own allows updating an owning place without transferring its owner to the callee. Non-void functions must end in a return/failure or returning if/else according to the structural return check.

Expressions and control flow

let value = expression is immutable; var value: Type = expression is mutable. Type annotations are optional when the initializer determines the type. Lexical bindings cannot shadow another live binding. Assignment requires a mutable place. +=, -=, *=, /= and %= are available. Mutability is not permission to write through an immutable borrowed view.

Precedence, lowest to highest: or; and; == != < <= > >=; + -; * / %; unary ! - &mut try move; calls/fields/indexes. and/or short-circuit. Arithmetic/comparisons require matching integer types; bool supports equality/inequality. ==/!= on slices of integers or bool compare lengths, then elements. Structs/enums and other slices have no implicit equality. Use i64(value), u64(value), u8(value), u16(value), i32(value), u32(value), usize(value) and isize(value) for checked value conversions. A conversion preserves the mathematical value or traps as cast; it never truncates or reinterprets bits. Conversions are never implicit. Overflow, bad conversions, division by zero, invalid indexes and bad slice ranges trap with the source file and line. slice[lo..hi] is a half-open borrowed view; slice[lo..] ends at len(slice), slice[..hi] starts at 0 and slice[..] is the whole view.

if condition { statements } else if other { statements } else { statements }
while condition { statements }
for element in slice { statements }
for index in lo..hi { statements }
match token { Number(value) { statements } Word(bytes) { statements } End {} }
match number { 0, 1 { statements } else { statements } }

Conditions are bool. Ranges are half-open; count ranges default to usize. Explicit integer bounds keep their nominal type. Indexes and both subslice limits are usize. break/continue require a loop. Match is a statement; arms contain blocks, with no arrows or fallthrough. Matches must be exhaustive or have else; patterns can group variants/literals with commas. Variant names in patterns are unqualified. Payload bindings use _ to ignore a field. assert condition traps on false. A bare non-void call result must be used, or explicitly discarded with _ = call(...).

Errors and contracts

fn parse(bytes: []u8) -> i64 ! ParseError { ... } returns either a successful value or an ordinary typed error. fail error_value takes the failure path. Every fallible call needs try call(...) or match call(...) { ok(value) { ... } err(error) { ... } }. try propagates a compatible error; there is no unwinding. let result = call(...) (immutable, no type annotation) stores the outcome; read it only with try result or match result { ok(v) {} err(e) {} }, which consume it. A stored result owns what its value or error owns, and must be consumed before it leaves scope. Owners must be released on every path.

fn positive(value: i64) -> i64
requires value > 0
ensures result > 0 {
    return value
}

Zero or more requires/ensures bool clauses follow a function signature. Preconditions run in declaration order at entry; postconditions likewise on every successful return, including implicit void returns, but not on fail or failed try. The returned expression is evaluated once before checking postconditions. result names that value in non-void postconditions only; a function with such postconditions cannot name a parameter result. Conditions see parameters, not body-local variables. Mutable parameters have their current values; there is no old() snapshot. A moved/freed parameter cannot be read by a postcondition.

Release and test builds check contracts. False conditions trap as precondition or postcondition at the clause's source location. Predicates must be read-only: no I/O, allocation, mutation, try, explicit move or ownership-taking calls, including transitively through helpers. Read-only scalar conversions, len, is_null, null_handle and arena_get are allowed. Interface signatures contain no contracts; mapped implementation functions can have them.

Ownership and arenas

alloc[Element](count) returns a zero-filled owned slice; alloc(count) means alloc[u8](count). Counts, lengths and arena capacities are usize. read_file(path) returns owned writable bytes. Owners move when assigned or returned; explicit move is required for owning function arguments. Every continuing exit must free or transfer every owner. free(owner) consumes it. Use after move/free, double free, dangling borrows and overlapping exclusive arguments are compile errors. truncate(move owner, length) only shortens a slice; later free releases the entire original mapping. Owned child elements must be freed/transferred before their container. Heap resource-header mutation requires the direct owner and invalidates prior borrowed views; scalar element writes do not. Indexed resource slots conservatively combine provenance until their container is freed.

Arena is a unique owner of fixed-capacity storage: var region = arena(capacity). arena_alloc[Element](&mut region, count) returns a writable region-borrowing slice. arena_new[Target](&mut region, value) returns Handle[Target]; arena_get(region, handle) copies the stored value, while arena_set(&mut region, handle, value) replaces it. Allocations are aligned to the target word and capacity/access checks trap at the source location. Handles cannot outlive their arena. null_handle[Target]() and is_null(handle) express missing links. Stored references must come from the same arena or static storage, never separate heap owners/other arenas. Arena headers are opaque and cannot be copied into storage. free(region) releases the whole region. Borrowed data loaded through handles is read-only; use arena_set to replace it. Recursive owning parameters require handles.

Generics and interfaces

struct Pair[Value] { first: Value, second: Value }
fn identity[Value](value: Value) -> Value { return value }
interface Equality[Value] { fn equal(first: Value, second: Value) -> bool }
fn integers_equal(first: i64, second: i64) -> bool { return first == second }
impl Equality[i64] { equal = integers_equal }
fn same[Value: Equality](first: Value, second: Value) -> bool {
    return Value.equal(first, second)
}

Functions, structs and enums can have type parameters; every application supplies all arguments: identity[i64](1), Pair[i64] { first: 1, second: 1 }. Interfaces have one unbounded type parameter and one to five function signatures. An implementation maps every signature exactly once to an ordinary production function with identical parameter types/modes, return and error types. One implementation per interface/type pair. Bounds permit Value.function(...) with static dispatch. Interfaces are not values and have no default implementations. Monomorphization reuses recursive instances. Limits: depth 64, 1,024 function instances, 4,096 types.

Tasks and channels

scope { ... } is a statement and may nest. spawn f(args), valid only inside a scope, names a program function; a built-in or non-call is E161. It returns an affine Task[T]. join(move task) -> T consumes it. A task with a result must be bound and joined; only one without may be a bare spawn. A handle dropped, joined twice or escaping its scope is E163. A fallible join needs try or match (E073). Arguments are scalars, moved owners, Sender and Receiver. Views, slices, handles, &mut and owners without move are E162. A spawned task cannot name a static var or call image_*, directly or through calls (E167).

BuiltinRule
channel[T](cap: usize)let (var tx, rx) = channel[T](cap) gives (Sender[T], Receiver[T]); only in a scope (E164); cap 0 is a rendezvous
send(tx, v), try_send(tx, v)bool; an owner value needs move (E133)
recv(rx, &mut ok), try_recv(rx, &mut ok)T; closed and drained, or cancelled: ok is false and the value zero
close(&mut tx)tx is a var; no live task may hold it (E165); later sends return false; receivers drain the buffer first
yield(), sleep_ms(ms: u64) -> boolswitch tasks
fd_wait(fd: i64, events: u64, timeout_ms: u64) -> i64waits until a socket or pipe can read (1) or write (2), or hangs up: 1 ready, 0 timeout (u64 max: none), -1 cancelled, closed, error, or second waiter of that direction

T holds no task, endpoint, handle, array or slice of owners (E164) and has no zero size (E043). Failed sends and undelivered items free their owners. An endpoint of the wrong kind is E021.

select {
    recv(rx, &mut ok) as value { use(value) }
    send(tx, move item) as sent { }
    after(50) { }
}

select runs one ready recv or send case. after(ms: u64) or default (at most one) runs when none is ready after ms or at once; else E166, also for an empty select or one channel twice. The scan start rotates for each task: no case has priority. as names the received value or the bool of send. Operands are evaluated once, in source order, move values last. An owned value is move of a place without an index (E133); only the winning case moves it. A closed or cancelled case is ready and acts as the plain call: leave a loop on ok false.

Default threads match host CPUs (1-64; KERN_THREADS overrides; tests use 1). One thread is FIFO; channels keep each sender's order. Tasks switch only in a blocking call, yield() and every 10,000 loop back edges, counted together. A failing task, or return, break, continue or try out of a scope, cancels the scope and its inner scopes. Cancelled send, recv and sleep_ms return false, fd_wait -1, at once and on later calls. Running code continues. A normal exit does not cancel. Every scope exit joins the unjoined tasks in spawn order and drops their errors. A task trap ends the process; a deadlock sleeps forever.

A task stack is 65,536 bytes above a guard region. An overflow prints trap: task stack overflow and exits with code 1. thumbv7m-none rejects scopes (E091).

Builtins, tests and tools

Other builtins: len(slice) -> usize, print(bytes), print_int(integer), arg(index: usize) -> []u8, arg_count() -> usize. Arguments are immutable borrowed bytes; missing arguments are empty. print_error(bytes) writes stderr.

Pure bit_and, bit_or, bit_xor, bit_not (unary), shift_left, shift_right take/return matching unsigned integers (u8, u16, u32, usize, u64). Shifts discard overflow, shift right logically, and trap on counts >= bit width (8, 16, 32 or 64).

write_file(path, bytes) -> bool creates/truncates a file (0644, subject to umask), handles partial writes and closes its descriptor. Failure can leave partial output; atomic output requires a staging file and rename_file(old, new) -> bool. make_dir(path), remove_dir(path), remove_file(path) and make_executable(path) return bool; mkdir uses0755/umask, executable mode is0755, remove_dir requires empty. file_kind(path) follows symlinks; link_kind(path) does not. Both return u64: 0 missing/error, 1 regular file, 2 directory, 3 other. Paths are byte slices; embedded NUL is rejected without changing the filesystem. read_dir(path, &mut success) -> []u8 returns owned unsorted NUL-separated names, excluding dot/dotdot. Failure returns empty with success=false; successful empty directories set success=true. Free the result on either path. These filesystem operations require test io and are forbidden in declared-input cached tests.

spawn_process(executable, arguments: [][]u8, capture_prefix) -> i64 returns a child PID or -1 setup failure. No shell/PATH search; arguments exclude argv[0]. Environment is inherited. Empty prefix inherits stdout/stderr; otherwise truncate prefix.out/.err. Exec failure exits127. wait_process(pid), process_status(pid), stop_process(pid) return exit code or128+signal, -1 error; status returns -2 while running. Completion reaps once; stop verifies child ownership, kills/reaps only that child. Always reap. clock_ms() and clock_ns() return monotonic u64 time; sleep_ms resumes interruptions. clock_unix_ns() -> i64 is realtime nanoseconds since the Unix epoch, -1 on error. random_bytes(&mut buffer: []u8) -> bool fills the whole buffer from the OS CSPRNG. signal_watch(signal) -> bool installs a counting handler for 1 (HUP), 2 (INT) or 15 (TERM); signal_pending(signal) -> bool reports and clears a delivery. No user code runs in a handler. fd_read(fd, &mut buffer) -> i64 and fd_write(fd, bytes) -> i64 make one transfer and return the count (0 end of file), -2 would block, -1 error. fd_close(fd) and fd_set_nonblocking(fd) return bool. Socket builtins take raw OS constants and sockaddr bytes and return i64 (>= 0 ok, -2 would block/in progress/interrupted, -1 error): socket_open(domain, kind), socket_bind(fd, addr), socket_listen(fd, backlog), socket_accept(fd), socket_connect(fd, addr), socket_set_option(fd, level, name, value), socket_get_option(fd, level, name), socket_shutdown(fd, how), socket_local_address(fd, &mut addr), socket_send_to(fd, bytes, addr), socket_receive_from(fd, &mut buffer, &mut addr). poller_new(), poller_control(poller, op, fd, records) and poller_wait(poller, &mut records, ms) wrap epoll (Linux) and kqueue (macOS) with raw OS event records. socket_listen first raises the soft descriptor limit to the hard limit (macOS: at most 10240). process_id() -> i64; exit_process(i64) terminates. get_env(name), current_dir(), executable_path() return owned bytes (empty missing/error). env_present(name) -> bool distinguishes unset from empty. resolve_path(path) returns owned canonical bytes, empty on failure. try_read_file(path, &mut success) returns owned bytes; the flag distinguishes empty files from failure. Free all these results. On macOS, image_open(package) -> i64 validates a relocatable test image: managed handle or -1. image_spawn(handle, selector, capture_prefix) forks an isolated child from it; reap as above. image_close(handle) -> bool retires it; stale handles fail. Linux returns unsupported. Handles expose no addresses. These operations require uncached I/O tests. Pure target_id() -> u64 identifies macOS arm64=0, Linux arm64=1, Linux x64=2.

test "name" { ... } lives beside production code and must reach an assertion and a project function. Plain tests cannot reach I/O. test io "name" { ... } always runs unless it declares inputs ["path", ...]: those inputs are frozen and hashed, and undeclared reads trap. Paths are relative to the command's working directory. An input may name a project directory. read_file on that exact path returns a snapshot of its loaded sources, in loader order. Each record contains path, module name, and source bytes, each prefixed by its length as an eight-byte little-endian integer. Any source change invalidates the snapshot. Directory traversal and reads of individual files remain undeclared operations. test fn helper(...) { ... } is unavailable to production and omitted from releases. Each selected test runs in an isolated process; passing tests are cached by semantic transitive dependency hashes. Positions/comments/formatting are not dependencies. Mutation audit reports exact generated-mutant results.

kern check|build|run|test|asm|asm-test|fmt FILE_OR_PROJECT|std; kern api PROJECT [MODULE], kern api std[.MODULE]; kern rules [FILE_OR_PROJECT]; kern spec; kern wasm FILE_OR_PROJECT [--test] [-o OUT.wasm]. fmt --check verifies without writing. test accepts --list, --force, --no-cache, --jobs N, --audit. --target macos-arm64|linux-arm64|linux-x64 selects the target; --cc uses the external toolchain path. asm/asm-test emit assembly without quality rules. Diagnostics are newline-delimited JSON on stderr with file, line, col, code, msg, fix.

Quality rules are on by default: canonical format, no duplicate code, named production numbers except 0/1, one bool parameter; 500 lines/file, 100 columns, 60 lines/function, 5 parameters, 4 nesting levels, 15 branches, 12 struct fields, 20 enum variants; 15 functions/file, 5 types/file, 12 files/module, 10 public items/module, 8 imports, 3 module levels; 30 lines/test, 5 direct tests/function, 100 ms/test. Unused items, unreachable code, discarded results, weak/misplaced tests and comment policy also have rules. kern.rules overrides name = integer|on|off; # starts a config comment. kern rules prints the complete active rule set. Rules do not weaken type/ownership safety. --rules PATH selects an explicit config; otherwise use the project's config, or search upward from a single source file. layers and advisory same_path_test are off by default. Mutant-survivor/redundancy rules apply during --audit only.

Native Cortex-M3 MMIO (M3a)

--target thumbv7m-none builds a single-file scalar program directly as Thumb-2/ELF32 for QEMU MPS2 AN385, without an external assembler or linker. Its scalar subset includes i32, u32, usize, u8, u16 and bool. u16 is a nominal unsigned 16-bit integer with checked arithmetic and conversions; it uses a target-word storage slot.

read8(addr) -> u8, read16(addr) -> u16, read32(addr) -> u32 perform one volatile load. write8(addr, value: u8), write16(addr, value: u16) and write32(addr, value: u32) perform one volatile store and return void. These names are reserved builtins. Values must match the access width exactly. Addresses must be integer literals or integer const names. No address or pointer type is exposed. The entire access must fit inside the MPS2 peripheral window 0x40000000..=0x400FFFFF, with natural alignment (1, 2 or 4 bytes).

MMIO requires thumbv7m-none (hosted: E170). Nonconstant addresses report E171, out-of-window accesses E172, misaligned addresses E173; argument count, type and out-of-range literals keep E031, E021 and E022.

Each dynamically executed MMIO call emits exactly one access at its stated width, in source evaluation order, including _ = read32(ADDR). The native path has no optimizer: reads and writes must never be cached, folded, eliminated, duplicated, merged or reordered. M3a adds no interrupts, fences, board profiles, pointer arithmetic or physical-board guarantee.

Source: SPEC.md in the repository.