Kern (prototype v0)
Kern is a small, typed, explicit language for LLM agents. Its native compiler is written in Kern and
bootstrapped from a pinned self-hosted CIP release binary (.cip/bootstrap.lock). It targets macOS arm64,
Linux arm64 and Linux x86-64. All targets have direct executable writers; --cc explicitly selects the system toolchain.
kern wasm also builds a standalone wasm32-wasi module (a limited subset, see "WebAssembly").
Build and use
sh .cip/build-kern.sh # fetch/verify pinned bootstrap, build stage1 -> build/kern
build/kern check examples/wc.kn # type check, JSON result
build/kern test examples/wc.kn # run the `test` blocks
build/kern test examples/wc.kn --list # affected tests and the changed functions
build/kern test examples/wc.kn --force # run all tests, refreshing the cache
build/kern test examples/wc.kn --audit # compile mutants and audit test coverage
build/kern fmt examples/calc --check # verify canonical formatting
build/kern run examples/wc.kn README.md
build/kern asm examples/wc.kn # print the assembly
build/kern build examples/sieve.kn --time
build/kern build examples/sieve.kn -O2 # optimization level: -O0, -O1 (default), -O2, -Os
build/kern wasm examples/wc.kn -o wc.wasm # wasm32-wasi module; add --test to build the `test` blocks
build/kern rules examples/wc.kn # the active quality rules, as a kern.rules file
build/kern test examples/calc # a project folder: all `test` blocks of all modules
build/kern run examples/calc "1+2*3" # a project folder: program arguments follow the folder
build/kern api examples/calc # the `pub` signatures of all modules
sh examples/errors.sh build/kern # show diagnostics and traps
check, build, run, test, asm, asm-test and rules take a file (single-file mode) or a project folder
(project mode, see "Project layout"). With no path, the current folder is the project when it has src/main.kn.
api works on a project only.
sh tests/test_selfhost_cli.sh build/kern-bootstrap regenerates the compiler through three native stages
(bootstrap -> stage1 -> stage2 == stage3), requires byte-identical stage2/3 executables with external tools blocked,
checks its own source policy/tests, and runs the complete language and feature suites through the self-built compiler.
The verified artifact is build/kern-selfhost. Use --host-only as the second script argument when Docker cross execution is unavailable.
Optimization levels
-O0, -O1 (default), -O2 and -Os select the level for build, run, test, asm and profile.
| Level | What the native backends (macOS arm64, Linux arm64, Linux x86-64) do |
|---|---|
-O0, -O1 | Same code on these targets. Constant folding and removal of dead branches (fold.kn), removal of unused runtime helpers (dce.kn), proof of safe bounds, overflow and divide checks from local facts (check_env.kn), register allocation of scalar locals (regalloc.kn), peephole rewrites (peephole.kn, peep_*.kn) |
-O2 | The above, plus inlining of small functions (inline.kn), a NEON (arm64) or SSE2 (x64) loop vectorizer (vectorize.kn, vec_*.kn), frame removal for leaf functions, and a few more removed overflow checks |
-Os | Like -O2, but with a much smaller inlining budget, no vectorizer and a smaller code size goal |
The thumbv7m-none and rv32 writers read the same flag; -O0 there also switches off some folding and array rewrites.
WebAssembly
kern wasm <file.kn | project folder> [--test] [-o out.wasm] writes a standalone wasm32-wasi module
(compiler/src/driver/wasm.kn, compiler/src/wasmgen/). The default output is <file>.wasm next to the source,
or <folder>/build/<folder name>.wasm for a project. --test builds the test blocks into a module whose _start
runs them in order. There is no -O flag for kern wasm. The only WASI import is fd_write.
Run a module with Node 20 or later: node scripts/wasm-run.js out.wasm. sh scripts/wasm-native.sh builds and runs
the subset, and sh scripts/wasm-parity.sh build/kern compares the output and exit code with the native compiler.
What kern wasm rejects (diagnostic E093, message wasm32 ...):
- Tasks and channels:
scope,spawn,join,channel,select(wasm32 target does not support tasks or channels). - Builtins outside the supported set (
wasm32 unsupported builtin call). The supported set isprint,print_int,print_float,len,alloc,free,truncate, the bit and shift builtins, casts, the arena builtins andtarget_id. Hosted OS builtins such asread_file,arg, sockets, signals andstdmodules that use them are not available. - Expressions and statements the generator does not lower (
wasm32 unsupported expression,wasm32 unsupported statement), an aggregate value that has no address (wasm32 cannot materialize aggregate expression), and an index of an unsupported type (wasm32 cannot index this type). - Not a
wasmgenrejection, but a limit:usizeandisizeare 32-bit, so the type checker rejects anisizeliteral that does not fit in 32 bits.
Memory is one linear memory that grows on demand; a failed grow traps. A trap exits with code 1, as native Kern does.
Benchmarks
python3 bench/bench.py # compile, C baseline, runtime, test jobs, peak RSS
python3 bench/bench.py --quick # skip the large generated file and the full job sweep
python3 bench/bench.py --json build/bench.json
python3 bench/size.py # executable and section sizes
python3 bench/size.py --json build/size.json
The harness builds a 1000- and a 5000-function file with bench/gen.py, compares compile wall time with
cc -O2 bench/sieve.c, runs both sieve programs, and sweeps kern test compiler --jobs N for CPU utilisation.
Kern has no thread API: the compiler is single-threaded and test jobs run as separate processes.
The size runner builds isolated copies of the examples and reports file bytes and selected section totals;
see EMBEDDED.md for the hosted baseline and the meaning of the section totals.
Project layout
A project is a folder with a fixed layout. Nothing else is allowed.
calc/
kern.rules optional, the rule settings of the project
src/
main.kn has `fn main()`; the root module
lexer/ a folder is a module
token.kn all `.kn` files of one folder share one namespace
scan.kn
parser/
...
parse/expr/ a nested module (path `parse.expr`)
build/ the output of `build`, `run` and `test`
- The
.knfiles directly insrc/are the root module. Other modules cannot import it. - Every other folder in
src/is a module with the pathaora.b. A module folder has at least one.knfile. - A file or folder name must be
snake_case. A.knfile outsidesrc/is an error.build/is skipped. mainmust be insrc/main.kn.- The diagnostic field
fileis the path of the file of the error, relative to the project folder. - A runtime trap names the file:
trap: overflow at src/lexer/scan.kn:12. In single-file mode the path is the one given tokern. kern.rulesis read from the project folder only (or--rules <path>).
Layout errors: E100 (name is not snake_case), E101 (.kn file outside src/), E102 (empty module folder),
E103 (no src/main.kn).
Modules
An item (fn, struct, enum, const) is private to its module. Write pub before it to export it.
The fields of a pub struct and the variants of a pub enum are public. A pub fn (and a pub type) cannot use a
private type in its signature (E112).
use lexer // at the top of the file, before all items
use parse.expr // the path starts at src/; the name in the code is the last segment: `expr`
pub fn count(s: []u8) -> u64 ! lexer.LexError {
let toks = try lexer.scan(s) // a function
if len(toks) > lexer.MAX_LEN { return 0 } // a constant
return len(toks)
}
// a type: `lexer.Token`, a variant: `lexer.Token.Num(1)`, a struct literal: `lexer.Span { lo: 0, hi: 1 }`
A
useis valid for its file only. A name from another module is always qualified by the last segment of the module path. There is no unqualified import, no alias and no wildcard.Two imports with the same last segment in one file are an error (
E108).A variable, parameter or function cannot have the name of an imported module (
E111).Patterns write a variant without the module:
match t { Num(n) { } }. The type of the value gives the enum.Import cycles are an error. The message lists the cycle:
import cycle: a -> b -> a(E109).testblocks stay in the file of the code and can use the private items of their module.kern test <project>selects affected tests across all modules and printsok <module>: <name>for each passed test (mainis the root module).Symbols are named with the module path (
k_parser__parse), so two modules can each havefn parse.kern api <project> [module]prints only thepubsignatures, grouped by module (types, constants, functions), in Kern syntax with no bodies:The standard library is Kern code in
std/, one folder per module:use std.bytesthenbytes.equal(a, b). The compiler finds it in$KERN_STD, else instd/beside the folder of its executable (build/kernuses the repositorystd/). To install a release, putkern-<target>inPREFIX/bin/kern(mode 755) and unpackkern-std.tar.gzof the same release inPREFIX. Only imported std modules load. Their rules and tests do not run with your program:kern test stdruns the std tests,kern api std.bytesprints a std module. An unknownstd.xisE104.STD.mdlists the public API of every module; refresh it withsh scripts/std-api.shafter changing the library.std.jsonparses with a pull parser (json.reader,json.nextreturningBeginObject,Key,String,Number(i64), ... , andjson.decode_stringfor the bytes behind a text token) and writes withjson.tokensplusjson.begin_object/key/text/integer/boolean/nothing/end_objectover astd.fmtbuilder. Numbers are integers for now; floats are rejected (JsonError.BadNumber) untilf64.std.collectionsholdsList[Value](list_new,list_push,list_get,list_set,list_pop,list_count,list_clear,list_release),U64Map[Value]andBytesMap[Value](open addressing: put, get, has, remove, count,*_key_atfor iteration, clear, release). Lists and maps own their storage and hold plain value types; byte keys are copied, so the caller keeps its own bytes.
// module lexer
pub enum Token { Num(i64), Plus, Minus, Star, Slash, LParen, RParen, Eof }
pub enum LexError { BadChar(u8), TooLong }
pub fn scan(s: []u8) -> []Token ! LexError
| Code | Meaning |
|---|---|
E104 | Unknown module in use. The fix lists the modules. |
E105 | The item is private. The fix names the file and line to add pub. |
E106 | The module has no such item. The fix lists its pub items. |
E107 | Wrong item kind (a constant called as a function, use lexer.Token, ...). |
E108 | Two imports with the same last segment. |
E109 | Import cycle (also a module that imports itself). |
E110 | use after an item. |
E111 | A name is the name of an imported module. |
E112 | A pub item uses a private type. |
E113 | The root module cannot be imported (use main). |
E114 | A module name is used as a value (let x = lexer). |
E117 | A project module named std (src/std/): std is reserved for the standard library. |
E115 | pub before something that is not fn, struct, enum or const. |
E116 | module.name is not a call, a constant or a type value. |
When a name is unknown (E023, E020, E012) and a pub item of that name is in another module, the fix says
which use and which qualified name to write.
use and pub are keywords. examples/calc/ is a small project with three modules in three layers (lexer, parser,
eval), test blocks in each module, and layers = eval > parser > lexer in its kern.rules.
Generics and interfaces
Generic functions, structs and enums take explicit, descriptive CamelCase type parameters. Calls and type applications supply every type argument; there is no implicit inference or runtime type representation.
struct Pair[Value] { first: Value, second: Value }
enum Maybe[Value] { Empty, Present(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)
}
fn main() {
let pair = Pair[i64] { first: identity[i64](1), second: 1 }
assert same[i64](pair.first, pair.second)
}
An interface has exactly one type parameter and one to five function signatures. An impl maps each signature
exactly once to an ordinary production function with the same parameter types, ownership/mutability modes,
return type and error type. There is at most one implementation per interface/concrete-type pair across the
whole program. A bound permits Value.function(...); compilation resolves it to the mapped ordinary function.
There are no objects, receiver methods, vtables, inheritance or runtime interface values.
Instantiations use AST monomorphization, retaining normal type, ownership, module visibility and purity checks.
Generic recursive functions reuse an existing concrete instance; growing specialization is bounded (64 nested
expansions, 1,024 function specializations, 4,096 total types). Recursive graph types still need arena handles.
Modules export interfaces and generic definitions with pub; kern api prints the original generic signatures.
Source structure limits count definitions, not generated instances. Tests and mutation auditing exercise the
concrete implementations, and implementation changes invalidate affected test fingerprints.
Runtime primitives
Bit operations use u64: bit_and, bit_or, bit_xor, bit_not, shift_left and shift_right.
bit_not has one argument; the others have two. Shifts discard shifted-out bits; right shift is logical.
Counts of 64 or more trap at the source location. The operations are pure and allowed in contracts.
| Filesystem builtin | Result and behavior |
|---|---|
write_file(path, bytes) | bool; create/truncate0644 with umask, full-write loop and descriptor cleanup |
make_dir(path) | bool; create0755 with umask, false if already present |
remove_dir(path) | bool; remove an empty directory |
remove_file(path) | bool; unlink a file or symlink |
rename_file(old, new) | bool; operating-system atomic rename within one filesystem |
make_executable(path) | bool; chmod0755 |
file_kind(path) | u64; follow symlinks: 0 missing/error, 1 regular file, 2 directory, 3 other |
link_kind(path) | u64; same codes without following symlinks |
read_dir(path, &mut success) | owned []u8 of unsorted NUL-separated names, excluding dot/dotdot |
try_read_file(path, &mut success) | owned []u8; success distinguishes an empty file from failure; free either result |
resolve_path(path) | owned canonical absolute path, resolving symlinks; empty on failure |
Paths are length-aware byte slices; embedded NUL is rejected rather than silently shortening a path.
write_file can leave partial/truncated output on failure; use a staging file and rename_file for atomic output.
read_dir distinguishes a successful empty directory from failure through its bool flag; free its result on
either path. All filesystem primitives require test io. A declared-input cached test cannot use the new
filesystem primitives because their reads/writes are not represented by frozen input contents (E126).
sh tests/test_runtime.sh checks bits, files, symlinks, directory growth and repeated operations under a low FD limit.
| Process/system builtin | Result and behavior |
|---|---|
spawn_process(executable, arguments, capture_prefix) | i64 child PID; -1 setup failure; arguments are [][]u8 excluding argv[0] |
wait_process(pid) / process_status(pid) | i64 exit code or 128+signal; -1 error/reaped/non-child, -2 running for status |
stop_process(pid) | verify a current child, SIGKILL if running, reap and return status |
clock_ms() / sleep_ms(milliseconds) | monotonic u64 milliseconds / bool success; interrupted sleeps resume |
clock_ns() / env_present(name) | monotonic u64 nanoseconds / bool distinguishing unset from empty |
process_id() / exit_process(code) | i64 PID / terminate with the low eight bits of an i64 code |
get_env(name) / current_dir() / executable_path() | owned []u8, empty on missing/error; always free the result |
arg_count() / target_id() | u64 argc including argv[0] / pure target: macOS arm64=0, Linux arm64=1, Linux x64=2 |
print_error(bytes) | write bytes to standard error |
clock_unix_ns() | i64 wall-clock nanoseconds since the Unix epoch (realtime clock); -1 on error |
random_bytes(&mut buffer) | bool; fill the whole []u8 from the OS CSPRNG (Linux getrandom, macOS getentropy) |
signal_watch(signal) / signal_pending(signal) | bool; install a flag-setting handler for SIGHUP 1, SIGINT 2 or SIGTERM 15 / read and clear it |
fd_read(fd, &mut buffer) / fd_write(fd, bytes) | i64 byte count (0 is end of file); -2 would block (EAGAIN); -1 other error |
fd_close(fd) / fd_set_nonblocking(fd) | bool; close a raw descriptor / set O_NONBLOCK |
socket_open(domain, kind) | i64 descriptor; raw OS AF_*/SOCK_* values (std.net maps them per target) |
socket_bind / socket_connect(fd, sockaddr) | i64 0 ok; connect returns -2 while in progress |
socket_listen(fd, backlog) / socket_accept(fd) / socket_shutdown(fd, how) | i64; accept returns the new descriptor or -2 |
socket_set_option(fd, level, name, value) / socket_get_option(fd, level, name) | i64; raw setsockopt of an int / the int value |
socket_local_address(fd, &mut sockaddr) | i64 address length written by getsockname |
socket_send_to(fd, bytes, sockaddr) / socket_receive_from(fd, &mut buffer, &mut sockaddr) | i64 count; an empty sockaddr means none |
poller_new() / poller_control(poller, op, fd, records) / poller_wait(poller, &mut records, timeout_ms) | i64; epoll on Linux, kqueue on macOS, raw OS records |
Spawning uses the exact executable path, no shell or PATH search, copies arguments before fork and inherits
the environment. An empty capture prefix inherits stdout/stderr; otherwise they go to prefix.out and
prefix.err (create/truncate0644). Setup failure can leave these files; exec failure exits127 in the child.
Wait/status consume a finished child once. Stop cannot signal non-children or process groups. It stops only
that child, not descendants. Every successfully spawned child must be waited or stopped. Returned executable
paths need not be canonical on macOS. An environment name containing NUL or = yields an empty owned result.
Except pure target_id, these operations require I/O tests; only arg_count may appear in a declared-input
cached test, where test-dispatch arguments are hidden. sh tests/test_system.sh exercises both direct and
external-toolchain execution, captured output, inherited environment, concurrency, cleanup and failures.
The service primitives above are the base for event loops and sockets. random_bytes retries interrupted
and short reads; fd_read/fd_write make one transfer, retry EINTR, and report would-block as -2 on every
target. Signal handlers run no user code: they count deliveries, and signal_pending reports whether a signal
arrived since the last call. Handlers restart interrupted system calls. Other signal numbers return false.
Socket and poller builtins return the OS result or a negative status: -2 for would block, in progress
or interrupted, -1 for any other error. Addresses are raw sockaddr bytes and poller records are raw
epoll_event (Linux) or kevent (macOS) records; std.net builds and decodes them per target. Linux
sends use MSG_NOSIGNAL; on macOS set SO_NOSIGPIPE. All of them require uncached test io.
Run sh tests/test_system.sh build/kern (add --cross for the Linux targets).
The native compiler's macOS test loader also uses managed image_open(package) -> i64,
image_spawn(handle, selector, capture_prefix) -> i64 and image_close(handle) -> bool capabilities.
They validate section/table bounds, import names and instruction relocations, map executable code separately
from writable data, and expose no memory addresses. Each spawned test is a forked child with independent data;
wait or stop every child and close each image handle. Retired handles cannot be reused. Linux reports these
image operations as unsupported and uses one temporary direct ELF instead. Image capabilities require uncached
I/O tests. sh tests/test_safe_os.sh build/kern --cross also checks canonical paths and safe read failures.
Specification and contracts
kern spec prints the compact, embedded language specification from SPEC.md (under 2,000 words).
It needs no source path and can be supplied directly as language context in a prompt.
Functions can declare multiple requires and ensures bool clauses after the signature:
fn positive(value: i64) -> i64
requires value > 0
ensures result > 0 {
return value
}
Preconditions run at entry; postconditions run at every successful return, including implicit void returns.
fail and failed try bypass successful-return postconditions. The returned expression runs once, before
postconditions, and result denotes its typed value in non-void postconditions. Conditions see parameters,
not body locals; mutable parameters have their current values, with no implicit old-value snapshots.
Ownership checks reject postconditions that read a parameter after it has been moved or freed.
Predicates must be transitively read-only: I/O, allocation, mutation, try, explicit moves and owning calls
are E160. Read-only predicate functions, conversions, len, is_null, null_handle and arena_get are allowed.
Contracts remain enabled in release and test builds. A false clause reports trap: precondition at file:line
or trap: postcondition at file:line. Generic contracts specialize normally; kern api includes contracts,
and changes invalidate affected test fingerprints. Contracts do not count as a test's explicit assertion.
During mutation audit, contracts remain unchanged as oracles; return-value mutations execute before their checks.
Run sh tests/test_contracts.sh for the specification/contract regressions.
Quality rules
The compiler has built-in, opinionated code-quality rules. They are on by default, and a violation is an error:
check, build, run and test stop with exit 1 before code generation (asm does not run them).
The rules run only when the program already passes the type check. The compiler reports all violations, one JSON
object per line on stderr, sorted by line. They have the fields of a compile error plus rule:
{"file":"a.kn","line":3,"col":1,"code":"R003","rule":"max_fn_lines","msg":"function `parse` has 74 lines; the limit is 60","fix":"split it into smaller functions"}
| Rule | Code | Default | Meaning |
|---|---|---|---|
max_file_lines | R001 | 500 | Maximum lines in one file. |
max_line_length | R002 | 100 | Maximum characters in one line. |
max_fn_lines | R003 | 60 | Maximum lines in one function or test, from fn to the closing }. |
max_params | R004 | 5 | Maximum parameters of one function. |
max_nesting | R005 | 4 | Maximum depth of nested if, while, for and match blocks. else if keeps the depth; else { if ... } adds one. |
max_branches | R006 | 15 | Maximum if, while, for, match arms, and and or in one function. |
max_struct_fields | R007 | 12 | Maximum fields in one struct. |
naming | R008 | on | snake_case for functions, parameters, variables and fields. CamelCase for structs, enums and variants. ALL_CAPS for constants. |
unused_variable | R009 | on | A let, var, parameter, loop variable or match name that is never read. A name that starts with _ is exempt; in a pattern write _. |
unused_function | R010 | on | A function that no function or test calls, in any module of the project (main is exempt). |
var_never_changed | R011 | on | A var that is never assigned and never passed as &mut. Use let. |
unreachable_code | R012 | on | A statement after return, break, continue or fail, or after an if/else where both blocks exit. |
discarded_result | R013 | on | A call statement that drops a non-void result. Write _ = f(...) to drop it on purpose, or use the result. |
empty_block | R014 | on | An if, else, while or for block with no statement. An empty match arm is allowed. |
constant_condition | R015 | on | if true, if false or while false. while true is allowed. |
comments | R016 | on | on: comments are allowed. off: every comment is an error. |
max_comment_length | R017 | 80 | Maximum characters of one comment, from // to the end of the line. |
max_comment_lines | R018 | 3 | Maximum comment lines in a row. |
max_file_comment_lines | R019 | 40 | Maximum lines with a comment in one file. |
comment_position | R020 | on | A comment must be on its own line, not after code. |
commented_code | R021 | on | A comment must not hold Kern code (for example // let x = 5 or // if x > 3 {). Plain English passes. |
trailing_whitespace | R022 | on | No space or tab at the end of a line. |
duplicate_test_name | R023 | on | Two tests must not have the same name. |
self_assign | R024 | on | An assignment such as x = x has no effect. |
empty_function_body | R025 | on | A function or test with no statement. |
max_enum_variants | R026 | 20 | Maximum variants in one enum. |
unused_constant | R027 | on | A const that no code uses. |
max_fns_per_file | R028 | 15 | Maximum functions in one file. Tests are not counted. |
max_types_per_file | R029 | 5 | Maximum structs and enums in one file. |
max_files_per_module | R030 | 12 | Maximum .kn files in one module folder. |
max_pub_per_module | R031 | 10 | Maximum pub items in one module. |
max_imports | R032 | 8 | Maximum use lines in one file. |
max_module_depth | R033 | 3 | Maximum depth of a module path (a.b.c has depth 3). |
unused_import | R034 | on | A use line whose module the file never names. |
unused_pub | R035 | on | A pub item that no other module uses. The fix is to remove pub. Project mode only. A type that a used pub function or type exposes counts as used. A pub function that nothing calls is reported by unused_function only. |
layers | R036 | off | layers = cli > app > core: a module imports only modules to its right. The names are top-level modules. A top-level module that is not in the list is an error. The root module may import any module. |
test_without_assert | R037 | on | A test must reach an assertion, directly or through a helper. |
constant_assert | R038 | on | An assertion in test-reachable code cannot compare only constants. assert false remains an explicit failure marker. |
test_reaches_nothing | R039 | on | A test must call a project function, directly or through a helper. Builtins do not count. |
test_location | R040 | on | A test must reach production code in its own file. |
test_only_file | R041 | on | A file with tests must also contain production code, types or constants. Test helpers do not count as production code. |
max_test_lines | R042 | 30 | Maximum lines in a test. |
max_tests_per_fn | R043 | 5 | Maximum tests reaching one production function, including indirect callers. Each test counts once. |
untested_pub_fn | R044 | on | A public function must be reached by a test when the program has tests. main is exempt. |
max_test_ms | R045 | 100 | Runtime limit per test process; off disables the timeout. |
test_helper_scope | R046 | on | A private function used only by tests must be declared test fn. Functions reached by main or a public function remain production code. |
same_path_test | R047 | off | Advisory runtime warning when tests visit identical branch/function bitmaps; enabling it reruns all tests to collect paths. |
redundant_test | R048 | on | During mutation audit, every test must uniquely kill a generated mutation. |
untested_behavior | R049 | on | During mutation audit, every generated mutation must be killed by a reaching test. |
duplicate_code | R050 | on | Duplicate checked function or test bodies after local names are normalized. |
magic_number | R051 | on | Production numbers other than zero and one need named constants; tests and named constant definitions are exempt. |
max_bool_params | R052 | 1 | Maximum bool parameters in one function. |
format | R053 | on | Source must match kern fmt; kern fmt --check verifies without writing. |
To drop a result on purpose, write _ = f(x). It is a statement, legal only for a call with a non-void result.
Incremental tests
Tests stay beside their code. Helpers use ordinary function calls; there are no setup or teardown hooks.
The compact syntax examples can be normalized with kern fmt before building under the default format rule.
fn twice(value: i64) -> i64 { return value * 2 }
fn main() { print_int(twice(3)) }
test fn check_twice(value: i64, expected: i64) { assert twice(value) == expected }
test "positive" { check_twice(3, 6) }
test io "output" { print_int(twice(3)) assert twice(3) == 6 }
A plain test is pure: print, print_int, read_file and arg are forbidden throughout its call graph
(E120). Allocation is allowed. Clocks, randomness and signals are I/O builtins. An I/O test must use
test io; without declared inputs it always runs. To cache an I/O test, declare every file it reads:
test io "fixture" inputs ["fixtures/input.txt"] {
let input = read_file("fixtures/input.txt")
assert count(input).lines > 0
free(input)
}
Input paths are relative to the command's working directory. Kern snapshots the files before hashing or generating
code. Declared-input tests read copies of these frozen bytes, so a concurrent file change cannot alter an execution
after selection. Undeclared reads trap; a missing input is E124. The snapshot contents join the test fingerprint.
Test processes have no program arguments; the runner's internal selector is not visible through arg.
test fn helpers are checked with the project but their functions are omitted from release code generation.
Production functions cannot call them (E121).
The cache stores successful pure tests and successful I/O tests with declared inputs. Each fingerprint includes the checked body, reachable functions,
constant values, string contents and type layouts. Recursive call groups are hashed together. Comments, positions
and formatting do not change the fingerprint; changing an unrelated function does not select a test.
The compiler executable and timeout setting also identify the cache, so rebuilding the compiler invalidates it.
Cache files live under build/.kern-test in the project, or the current working directory for single-file mode.
Removing that folder forces the next run to execute all tests.
--list reports run or cached for every test, with changed-function reasons, without generating code or
updating the cache. --force reruns everything and updates the cache. --no-cache neither reads nor writes it.
--jobs N limits concurrency; the default uses all available cores. Only selected tests print ok lines.
The summary goes to stderr. A failing, trapped or timed-out test does not stop the other tests, and failures
are never cached.
Selection happens before code generation. If every test is cached, no machine code or executable is produced.
On macOS arm64, selected tests share one in-memory image and each runs in a forked child. Each child restores
JIT execution protection before entering generated code. Linux writes one temporary ELF directly, while --cc
assembles and links one binary for the entire project. Separate processes invoke its test selector; the file is removed.
The macOS --cc path warms the executable before starting test timeouts to exclude its first-launch OS cost.
Run runner regressions with sh tests/test_runner.sh; audit/snapshot checks use sh tests/test_audit.sh,
format/rule checks use sh tests/test_structure.sh, ownership/arena/runtime checks use sh tests/test_ownership.sh,
and generic/static-dispatch checks use sh tests/test_generics.sh.
The compiler harness remains sh tests/run.sh.
The compiler-conformance examples explicitly relax selected test rules in their kern.rules files because some
tests exercise syntax, constants and runtime primitives directly. The legacy harness composes tests/kern.rules
with case-specific settings; new feature suites exercise product defaults or explicitly isolate their target rules.
A call with ! still needs try or match: _ = try f(x).
Mutation audit
kern test --audit runs the unchanged suite first, then compiles mutations of production functions and executes
only their reaching tests. It bypasses the pass cache. Mutations change arithmetic/comparison/boolean operators,
numeric or character literals, unary operators and returned scalar values. Compound arithmetic is included.
The entry point main, tests and test helpers are outside the unit mutation scope. Compile-identical mutants
are skipped. Baseline failures stop the audit; mutant traps and timeouts count as kills without stopping other tests.
untested_behavior reports surviving mutations, including functions no test reaches. redundant_test reports
tests with no unique kill. These are exact results for the generated mutation set, not a proof about every possible
program change: equivalent mutants can survive and need review. Both audit rules are configurable. The audit
summary reports mutants, survivors, redundant tests and actual selected test executions.
Ownership and arenas
Heap allocations have one owner. Assigning an owned slice or resource-containing struct moves it; use after move
is E130. free(owner) consumes it, and every continuing/return/failure path must free or transfer all owners
(E136). String literals and arg are immutable borrowed bytes. Sub-slices borrow their original allocation;
they cannot outlive it (E131) or be freed (E133). There is no implicit heap cleanup.
Parameters borrow by default. value: own []u8 transfers ownership and a call uses move value.
value: &mut own Stack borrows an owning place and can free/replace its owned fields. Ordinary &mut parameters
cannot acquire independent heap owners. Calls reject overlapping exclusive arguments (E138).
fn consume(value: own []u8) {
free(value)
}
fn main() {
let bytes = alloc(1)
consume(move bytes)
}
truncate(move owner, length) shortens an owned slice without losing allocation-size information; freeing it
releases the full mapping even when its visible length is zero. It cannot grow or hide owned child elements.
An owning slice of owning elements needs for item in values { free(item) } before free(values).
Heap resource headers must be changed through the original owner. Such writes invalidate earlier borrowed
views (E141); create a fresh view afterwards. Scalar element writes preserve views. This prevents stale alias
metadata from hiding a newly stored borrow. Owned recursive parameter types use arenas and handles (E139).
Arena is an opaque, unique owner of a fixed-capacity byte region. arena(capacity) creates it; free(region)
releases all arena storage. Allocations are eight-byte aligned and checked for capacity/overflow. arena_alloc[T]
returns a writable slice borrowing the region. arena_new[T] stores a value and returns Handle[T];
arena_get loads a copy, arena_set replaces it, and null_handle[T]()/is_null provide null links.
Handles stay valid across allocations and cannot outlive their arena. Data stored in an arena may reference the
same arena or static bytes, including through helper functions. A different owner is E141. Arena storage cannot
adopt separate heap owners, and Arena headers cannot be copied or stored as arena objects. Borrowed slices loaded
through handles are read-only views; use arena_set to replace stored values.
struct Node {
value: i64,
next: Handle[Node]
}
const REGION_BYTES: u64 = 64
fn main() {
var region = arena(REGION_BYTES)
let node = arena_new[Node](&mut region, Node {
value: 1,
next: null_handle[Node]()
})
assert arena_get(region, node).value == 1
free(region)
}
Arena bounds traps name the source file and line. The ownership regression suite also links the emitted allocator into a C probe and queries OS mappings to verify full unmapping after a zero-length truncation.
kern.rules
A plain text file, one name = value per line. # starts a comment. The value is a positive integer, on or off.
The rule layers takes a list of names with > between them, or off.
off is valid for every rule, also the numeric ones. on is the default value of the rule. An unknown name or a bad value
is an error (code R000) that names the file and the line and lists the valid rule names.
# kern.rules
max_fn_lines = 80
max_comment_lines = off
comments = on
Lookup: the option --rules <path> wins. In project mode kern reads <project>/kern.rules. In single-file mode kern searches for
kern.rules in the folder of the source file, then in each parent folder. With no file, the defaults apply.
The rules of one file (size, naming, comments) also run in single-file mode. unused_pub runs only in project mode.
kern rules [file.kn | project] prints the active value of every rule with a short comment, and the path of the config file in use.
The output is a valid kern.rules file.
Targets
--target | Runtime | Link |
|---|---|---|
macos-arm64 | libc (write, open, mmap) | direct Mach-O writer, or cc with --cc |
linux-arm64 | raw system calls, no libc, entry _start | direct ELF64 writer, or cc -nostdlib -static with --cc |
linux-x64 | raw system calls, no libc, entry _start | direct ELF64 writer, or cc -nostdlib -static with --cc |
wasm32-wasi | WASI fd_write; no --target flag, use kern wasm | direct .wasm writer, a limited subset (see "WebAssembly") |
The default target is the host. kern asm file.kn --target linux-x64 works on all hosts.
Direct build works across all targets without an external assembler/linker. Cross builds with --cc need
clang and an appropriate linker. run and test only start the program on the host target.
Direct writer for macOS arm64
On a macOS arm64 host, build and run write the signed Mach-O executable themselves. There is no cc step.
test loads code into memory instead, unless --cc is requested.
compiler/src/arm64/ encodes the assembly text of backend, compiler/src/macho/ writes the file and the ad-hoc
code signature, and compiler/src/sha256/ makes the page hashes. Write time is under 1 ms for a small file. An instruction
or directive that the writer does not know is an error with the line number. --cc (or the variable KERN_CC=1) uses cc
as before. A cross build uses its target's direct writer too. Note: macOS needs 200 to 300 ms to start a new binary for the first time.
Direct writers for Linux
compiler/src/arm64/ also accepts the emitted Linux arm64 syntax; compiler/src/x64/ encodes the emitted Intel-syntax subset.
compiler/src/elf/ resolves checked relocations and writes static ELF64 executables, with separate RX text, R constants,
RW data and a non-executable stack. It includes section/symbol tables for inspection. Arm64 segments use 64 KiB
alignment so the same file works on Linux kernels with 4, 16 or 64 KiB pages. Unknown assembly is a hard error,
not an implicit external-toolchain fallback. Output uses a unique staging file and atomic rename.
Linux test runs write one temporary ELF directly; they do not invoke cc unless --cc is requested.
sh tests/test_writers.sh blocks cc, clang, as and ld to verify direct builds, tests, audits and reproducible
cross-target output.
Source layout
| Path | Content |
|---|---|
compiler/src/ | self-hosted native Kern implementation of every compiler phase, direct writers and CLI command |
std/ | standard library modules written in Kern (use std.<module>) |
.cip/bootstrap.lock, .cip/bootstrap.sh | pinned self-hosted CIP release binary and SHA-256 verification script |
The Kern compiler has its own encoders, executable writers, ownership and quality passes, formatter,
dependency cache, isolated runner and mutation auditor. It does not require a Rust toolchain or external
assembler/linker for direct builds. See compiler/README.md for bootstrap and policy details.
examples/core.kn has the tests that all targets must pass.
What v0 has
| Area | Content |
|---|---|
| Types | i64, u64, u8, bool, struct, enum (tagged union), and a slice []T of any type T ([]u8, []Token, [][]i64) |
| Names | CamelCase is a type (a struct, an enum or a variant), ALL_CAPS is a constant, anything else is a variable or a function. The parser relies on this: Name { is a struct literal, and if x == MAX { is a block |
| Statements | let, var, if/else, while, for x in slice (any element type), for i in a..b, return, assert, break, continue, match, fail, _ = call(...) (drop a result); compound += -= *= /= %= |
| Parameter modes | x: T (borrow/read), x: &mut T, x: own T (call with move), x: &mut own T |
| Safety | No implicit conversion, no shadowing, read-only let, bounds traps, overflow traps, checked casts |
| Slices | alloc[T](n) (zero elements; alloc(n) is []u8), a[i], a[i] = v, a[i].x += v, &mut a[i], a[lo..hi] (shares the data), len(a); bounds traps |
| Constants | const MAX_LEN: u64 = 4096 at top level. The value is an integer, bool, char (type u8) or string (type []u8) literal, with an optional -. A use compiles to an immediate |
| Enums | enum Token { Num(i64), Ident([]u8), Plus, Eof }. Build with Token.Num(5) or Token.Plus. Layout: word 0 is the variant index, then the largest payload. An enum is a value like a struct: copy, pass, return, field, slice element. alloc gives the first variant. == on enums is an error: use match |
match | A statement. On an enum: Num(n) { }, Pair(a, b) { }, Plus, Eof { }, _ ignores a value. Every variant exactly one time, or else. On an integer, u8 or bool: literal or constant patterns, else is required (not for bool with both values). Bindings are read-only copies. return, break and continue work in an arm. It compiles to compare-and-branch |
| Errors | fn f(s: []u8) -> i64 ! ParseError, or fn g() ! ParseError with no value. fail e returns the error. try f(s) returns the same error from the caller (same error type). Other use of a call with !: match f(s) { ok(n) { } err(e) { } } (ok { } for no value). Both arms are required. The error type can be any type. main has no !. let r = f(s) stores the result; only try r or match r read it |
| Builtins | print, print_int, len, alloc, free, truncate, read_file, arg, casts, arena, arena_alloc, arena_new, arena_get, arena_set, null_handle, is_null |
| Modules | Folders are modules, pub, qualified use, import cycles are errors, kern api. See "Modules" |
| Diagnostics | One JSON object: file, line, col, code, msg, fix. A compile error stops at the first. Quality rule violations (R...) have a rule field and are all reported |
| Code generation | Direct native lowering for macOS arm64, Linux arm64, Linux x86-64 and Cortex-M3 (thumbv7m-none); kern wasm for a subset on wasm32-wasi |
What v0 does not have yet
matchon a slice or a struct.Floats and wrapping operators.
&mut a[i]for a[]u8or[]boolelement (a byte has no address).An SSA/IR middle end. The backend has folding, dead-code removal, register allocation of scalar locals, peepholes and, at
-O2, inlining and a vectorizer (see "Optimization levels"), but it works on the tree and on assembly text. So it has no loop-invariant hoisting, no copy or constant propagation across blocks, and no range analysis: a bounds or overflow check is removed only when a local fact proves it (O1C-AUDIT.md, "Ordered work", steps 4-6).A stored
!result (let r = f(x)) is read only bytry rormatch r; it cannot be copied, passed or returned.No range patterns, no guards and no nested patterns in
match. No==on enums or structs.No automatic slice growth: allocate replacement storage explicitly. Use
truncate(move tokens, n)to return an owned prefix, ortokens[0..n]to borrow a view.
Result ABI (calls with !)
The flag is in x2 (AArch64) or r11 (x86-64): 0 is success, 1 is an error. The value or the error uses the normal
result path: x0/x1 (rax/rdx), or the struct result pointer for a struct or an enum. The caller gives a memory area
of the larger of the two sizes. A normal call does not touch the flag, so it costs nothing.
try on a scalar or slice error is one test of the flag and a jump to the function exit.
File paths are length-aware slices. Runtime helpers make their own terminated copies and reject embedded NUL.