Egg Language Design
Bingnan Zheng · 2026-10-22
English · 中文
Overview
Egg is an AI-native systems language whose core has no capabilities at all: exceptions, IO and allocation are capability modules that each program declares on demand. The name says it: everything hatches from a minimal egg.
Three principles:
- The core has nothing. No GC, no exceptions, no hidden allocation, no IO, no dependency on an operating system.
- Capabilities are declared and checked recursively. A module declares what it needs, and the compiler walks the call graph to confirm nothing exceeds it.
- Designed for AI. The core is small enough to fit in a model’s context, and every capability ships with a machine-readable spec, examples and tests.
One structural payoff: the runtime is the restricted subset. Go constrains its runtime with special rules such as nosplit and nowritebarrier. Egg needs none: the exception machinery is a capability library written in core code that declares no capabilities, and the compiler is an ordinary program that declares alloc and io. The lowest layer is restricted by construction, and the compiler checks it.
A second payoff: the core is portable by construction, because everything that touches an operating system lives in a capability module.
Core language
The core follows Zig but stays smaller: it keeps only features that need no runtime support. Function signatures must spell out types; bodies may infer them. This avoids whole-program type inference, which makes compilation slow and hard to make incremental.
| Area | Contents | First version |
|---|---|---|
| Integers | i8…i64, u8…u64, usize |
v0 (i64 only); all widths v2 |
| Other primitives | bool, f32, f64, void |
v0 |
| Composite types | struct, enum, tagged unions |
v1 |
| Pointers and memory | slices, arrays; single-item pointers | v1; raw pointers v2 (holding them is safe; pointer operations such as p.* need allow unsafe) |
| Control flow | if, while, for, switch, all expressions |
v0 (if, while first) |
| Errors | errors as values (like !T), try |
v1 |
| Compile time | comptime parameters, generics (functions returning type); reflection (@typeInfo) |
v1; reflection after v1 |
Type syntax is prefix and reads left to right, as in Go and Zig. Every modifier sits on the left of the type it modifies:
| Type | Reads as |
|---|---|
[4]u8 |
array of 4 bytes, length part of the type |
[3][4]u8 |
3 rows of 4 bytes; indexed grid[2][3] in the same order |
[]u8 |
slice: pointer plus runtime length |
*[4]u8 |
pointer to an array of 4 bytes |
?T |
a T or null; *T is a raw pointer and can already be null, so ?*T and ??T have two levels |
!T |
a T or an error |
Rust’s [u8; 4] was considered and rejected: it is the only form that puts the element type in the middle, and nested arrays read inside out.
Kept out of the core on purpose:
- Operator overloading and implicit conversions: mildly annoying for people, clearer for AI and reviewers
- Closures: capturing an environment usually means allocating, so it belongs to a capability
- Exceptions, heap allocation, IO: all capability modules
- Garbage collection: not in the language at all. Heap memory is managed only by ownership (one owner, checked on every path): freeing is explicit, and neither a collector nor the ownership check runs at run time. Until v3, strings and
a.createlive in a program-lifetime arena instead
Errors as values are in the core because they are just a return value plus a tag. Exceptions need stack unwinding, so they are not.
v0 syntax (tentative):
fn fib(n: i64) i64 {
if (n < 2) { return n }
return fib(n - 1) + fib(n - 2)
}
fn main() i64 {
return fib(20)
}
Capability system
A module (a file) declares its capabilities at the top with uses; the compiler infers what each function actually uses and checks it recursively along the call graph. A capability is used through a value (Io, Allocator, Fs, Args) that only main receives from the runtime and that is passed down explicitly, so code without the value cannot reach the capability, and code in a module without the declaration cannot use the value. A module that declares none is pure core code.
Core only, no capabilities:
fn hash(bytes: []const u8) u64 {
var h: u64 = 0xcbf29ce484222325
for (bytes) |b| { h = (h ^ b) * 0x100000001b3 }
return h
}
Declaring what it needs:
uses alloc, fs
fn read_config(files: Fs, a: Allocator, path: str) !Config {
const text = try files.read(a, path) // a Buf(u8) the caller owns
defer a.free(text)
return parse(text[0..])
}
First capabilities:
| Capability | Provides | Planned |
|---|---|---|
alloc |
heap allocation, allocator passed explicitly | v2 (owned buffers Buf(T) that are freed, with ownership checking); v3 (text a program builds is a Buf(u8); a.leak and a.cstr keep text for the whole program) |
io |
standard streams, one implementation per OS | v2 (standard output first); standard error and input added |
args |
command-line arguments | done (len and get) |
fs |
files, one implementation per OS | done: whole-file read and write, open files as owned Reader and Writer values, seek on a Reader, directories (make_dir, open_dir listing as an owned DirReader), remove_file, remove_dir, rename, stat and real_path; a file open for reading and writing at once not yet |
net |
TCP, UDP and name resolution, one implementation per OS | done: blocking sockets; Unix sockets and TLS not yet |
thread |
system threads; owned values move between them; shared data is immutable (Shared(T)), atomic (Atomic) or in a ConcurrentMap, Erlang-style: programs hold no locks (the map takes its own, briefly) |
done: spawn, join, detach, channels, select, Shared(T), Atomic, ConcurrentMap(K, V) |
raise |
raising and catching exceptions, implemented in core code | after v3 |
Checking rules:
- A function may not use a capability its module did not declare (E130).
- The compiler infers each function’s capability set along the call graph, including indirect calls, calls into other modules and generic instances: a module without
uses iocannot print even inside a generic function instantiated withIo. - Capability sets are not written in signatures; tooling shows them (the language server’s hover does).
AI-native features
Egg assumes an AI learns the language in context rather than from training data: a new, user-extensible language has almost no training data, so its spec itself must be readable by a model.
- Machine-readable spec in the repo’s
spec/directory, with the full core definition small enough to load into context at once. - Every capability module ships three things: a spec, examples and tests. A capability without them cannot be published.
- Structured diagnostics: the compiler can emit errors as JSON with location, rule number and suggested fixes, so an AI can repair code on its own.
- One canonical format: a built-in formatter with no options, so generated code is uniform.
- Regular, unambiguous syntax: one way to write each construct, no operator overloading, no implicit conversions.
- Capability checks as a safety net: generated code may be wrong, but the compiler guarantees it uses no undeclared capability.
Code somewhat longer than Rust is an acceptable cost: when most code is generated, explicitness helps both the AI and the reviewer see what it does.
Compiler architecture
The first compiler, eggc, is written in the Ruby subset Spinel can compile: it runs directly on CRuby during development and is compiled to a native binary with Spinel for release. It emits C and hands it to the system C compiler.
Pipeline:
- Lexing (
lexer.rb) - Recursive-descent parsing into an AST (
parser.rb) - Loading imported modules and merging them into one program (
loader.rb, from v2) - Type checking (
typecheck.rb) - Capability checking, from v2 (
caps.rb) - Ownership checking of buffers, from v2 (
own.rb) - C code generation (
codegen_c.rb) - Invoking the C compiler to produce an executable
Layout:
egg/
├── bin/eggc
├── lib/egg/
│ ├── lexer.rb
│ ├── ast.rb
│ ├── parser.rb
│ ├── loader.rb
│ ├── typecheck.rb
│ ├── caps.rb
│ ├── own.rb
│ └── codegen_c.rb
├── spec/ # machine-readable language spec
├── examples/
└── test/
Coding rules (to stay inside the Spinel subset):
- No
send,define_method,method_missingoreval. - AST nodes are
Structs, handled withcase … inpattern matching rather than double-dispatch visitors. - Every
case … inends with anelsethat raises a clear error naming the node type, since Ruby does not check exhaustiveness. - No gems; the parser is hand-written.
- Test early how well Spinel infers types for an array holding several node types; if it struggles, switch to a single
Nodeclass with akindfield.
These rules also prepare for rewriting the compiler in Egg: case … in maps almost one to one onto Egg’s switch over tagged unions.
Bootstrapping and portability
The bootstrap chain starts from a C compiler and contains no prebuilt binary that must be trusted. Users need only a C compiler, not Ruby.
Chain:
- A C compiler builds CRuby.
- CRuby runs the
eggcRuby sources directly and compiles Egg programs to C. - Optional: Spinel compiles
eggcto a native binary for speed. - From v4:
eggcis rewritten in Egg and compiled by the previous generation. - Check: the second- and third-generation compilers produce byte-identical output.
Distribution follows Nim and Zig: ship the C that eggc generates, and users build it with any C compiler (MSVC, clang, MinGW).
Windows:
- CRuby and Spinel are developer tools; Windows users never need them.
zig cc -target x86_64-windows-gnucross-compiles a Windows build from Linux.- Windows developers can work in WSL.
- Spinel already has a native Windows build (MinGW-w64 against the UCRT, see its win32.mk), so a Spinel-compiled eggc can ship as a Windows binary.
The C that Egg generates must be portable from day one:
- Standard C only (C99 or C11); the core calls no POSIX API.
- All platform-specific code lives in capability modules; for example,
cap.iohas one implementation each for Linux, macOS and Windows, chosen at comptime by target.
Roadmap
Each phase ends at a gate that can be checked automatically. v3 completes memory management without a GC; raise is the first real test of the runtime-is-the-subset design; v4 is self-hosting. v0, v1, v2 and v3 are done; full reflection (@typeInfo) moved past v1. In v2, step 1, the capability check (modules, uses, the Io and Allocator values, E130), is done. Step 2 is done too: integer types of every width with @as, raw pointers usable in files that allow unsafe (local to the file, not carried along the call graph, so an unsafe module can offer a safe API), function values, and extern fn declaring the capabilities the C function uses. Function values turned out not to need allow unsafe: taking a function as a value counts as calling it for the capability check, so a function value carries capabilities the way an Io value does. Step 3 added ownership: Buf(T), a heap buffer with one owner, made by a.alloc and freed by a.free. The check is linear: following every path, a buffer is used only while owned and must be freed, returned or passed on before its owner goes away, so there is no use after free, no double free and no leak. It needs no lifetimes, because slices are already second-class: a borrowed slice of a buffer cannot outlive the call. Buffers first lived only in locals, parameters and results; then structs, arrays and buffers holding buffers became owned too. The fields of a struct variable are followed one by one, so v.data can be freed and replaced while v stays usable, and an inout self method can resize its buffer. Elements of containers are not followed: they are borrowed in place and swapped out with @replace/@take, Buf(T).empty is a buffer that owns nothing, and a.free frees everything a value holds. defer and errdefer came with it, since freeing on every error path is otherwise impractical. Strings and a.create stay in the program-lifetime arena. A GC was planned as v3 and dropped on 2026-10-27: realistic programs (a growing hash map, a tree rewritten in place) work under the ownership rules, so v3 instead closes the two gaps they showed: read-only methods have to take inout self, and strings are never freed. Both are closed: parameters borrow by default, and sink marks the ones that take ownership; text a program builds is a Buf(u8) it frees, and only an explicit a.leak or a.cstr keeps text for the whole program. Slices later became usable as local constants: const s = x[lo..hi] is read-only and borrows x until its last use, as in Rust’s non-lexical lifetimes, so the check still needs no annotations, because a slice stays inside the function that made it. inout s = &x[lo..hi] is the writable form: it has x to itself until its last use, so a place has either many readers or one writer, as in Rust.
| Phase | Scope | Acceptance gate |
|---|---|---|
| v0 · Core subset ✅ | i64, functions, if, while, return; emits C for the system C compiler |
fib.egg compiles and prints 6765 |
| v1 · Types and comptime ✅ | struct with methods, enum, tagged unions, str, arrays, second-class slices, inout; error values; comptime generics; @sizeOf, @typeName |
Generic Pair and error-value examples pass their tests |
| v2 · Capability checks ✅ | modules; alloc and io capabilities; recursive check along the call graph; integer types, raw pointers, function values, extern fn; ownership of buffers, defer |
Programs using undeclared capabilities are rejected |
| v3 · Memory without GC ✅ | read-only borrow parameters; owned strings that are freed like buffers | A long-running loop that builds strings stays in constant memory, and a generic map’s read methods take a borrow instead of inout self |
| v4 · Self-hosting | eggc rewritten in Egg, compiled by the previous generation |
Generation 2 and 3 output is byte-identical |
Open questions
- Semicolons at the end of statements? The examples omit them; weigh against parser simplicity.
- Syntax for capabilities in signatures:
fn f() !void with io, or only module-level declarations with generated docs? Decided in v2: module-leveluses alloc, io, with capability values passed explicitly; signatures carry no capability list, and tooling shows each function’s set. - Granularity: is
ioone capability, or split intofs,netandstdio? Decided when files arrived: split.fshas its own valueFs, so ausesline says what a file can reach;netwill follow the same pattern. - Are the clock and random bytes capabilities? Decided on 2026-11-28: no.
timeandrandwere, withClockandRandomvalues, so that code declaring neither ran the same on the same input; but nothing relied on that, and every function that stamped a time or made a key, and every caller above it, had to declare them and pass the value down (ws.client(rng, a)for a 4-byte mask). Reading either changes nothing outside the program and reaches nothing in it, unlikefsornet, so they are plain functions, as in Go, Rust and Zig:time.now()andtime.monotonic()instd/time,rand.fill(&b[lo..hi])instd/rand, over builtins only the standard library may call. - How is freed memory kept safe? Decided in v2: an owned
Buf(T)checked linearly (moved, never copied; freed or passed on exactly once on every path), withdefer/errdefer; freeing is never implicit. Strings stay in an arena that is never freed. - A GC? Decided on 2026-10-27: none. Memory is managed only by ownership.
- How are built strings freed? Decided in v3: no new type. Text a program builds is a
Buf(u8), andstris left for literals,a.leakcopies and slices of them, which last for the whole program. - What does a read-only borrow parameter look like, and is it the default for
self? Decided in v3: as in Hylo, a plain parameter (selftoo) borrows an owned value,sink x: Ttakes it over, and the call is writtenf(x)either way. - Bitwise operators: which precedence, and does
<<panic on lost bits? Decided on 2026-10-29: as in Zig,& | ^bind tighter than comparisons and<< >>sit between them and+ -, but& | ^cannot be mixed without parentheses (E002);<<drops the bits shifted out, and an amount below 0 or not below the width panics; operands are any integer type (signed in two’s complement,>>sign-extending), the amount any integer type;0xand0bliterals came with them. - A 64 by 64 bit product for bignums? Decided on 2026-11-13, for the TLS package’s P-256, P-384 and RSA, whose limbs were 32 bits for want of one: a builtin
@mulWide(a, b)on twou64, giving[2]u64{ low, high }, as Zig’sstd.math.mulWidedoes without a 128-bit type. eggc computes it withunsigned __int128under gcc and clang,_umul128(x64) or__umulh(arm64) under MSVC, and four 32-bit products elsewhere and withEGG_PORTABLE, so the test suite’s debug build checks that path. Nou128type: it would need every operator, literals and printing, and MSVC has no 128-bit integer to lower it to. No add-with-carry builtin either:s = a +% b; carry = s < asays it, and C compilers turn it into an add with carry. - Wrapping arithmetic for hashes and ciphers? Decided on 2026-11-12, for the TLS package: as in Zig,
+%-%*%on every integer type give the result modulo 2^N (two’s complement for signed types) and never panic, at the precedence of+ -and*;+ - *stay checked. eggc computes them in the unsigned C type of the width, and 8 and 16 bits inunsigned int, since C promotes them toint, and with the 32-bitintof every target eggc supports,u16 *% u16would overflow there. Not in top-level constants, whose arithmetic is exact on i64. A 128-bit product came later, as@mulWide(2026-11-13, above). - How are large read-only parameters passed in C? Decided on 2026-11-12, after the TLS package’s AES copied a 960-byte key schedule per round: a plain parameter (a read-only borrow,
selfincluded) larger than 16 bytes goes asconst T *; up to 16 it stays a value. 16 is Egg’s line; how a value goes is the target’s C ABI: SysV x86-64 and AArch64 pass up to 16 bytes in registers, Windows x64 passes more than 8 by reference to a copy. No new syntax: Egg’s three modes already match Rust’s&self,&mut selfandself(plain,inout,sink), so only the lowering changes. The one call where a pointer could show is aninout selfmethod given a plain value of a part of itself (m.mix(m.last)), which must see it as it was: that argument is copied first, as is one that a later argument changes as it is computed. A later&ychanges nothing until the call, and then onlyy: on 2026-11-13, after TLS records copied their AEAD key before everyseal(key, nonce, aad, &buf[0..]), such an argument no longer forces a copy. A big argument that is a place (x,x.f,x[i]) now goes by its own address unless computing a later argument writes something (f(x.big, g(&x))), or an&argument of the call is part of the same variable or goes through a pointer; then it is copied. One that is computed (make(3), a value converted to?T) is a temporary either way, passed by that temporary’s address. - How does a program keep secrets out of memory? Decided on 2026-11-12, from the TLS package’s X25519 example:
rand.fill(&k[0..])writes random bytes straight into an array, so a key need not pass through aBuffreed with the key in it; and the builtin@secureZero(&x)(or&x[lo..hi]) zeros a place with stores C compilers keep (a memset followed by an empty asm that may read the memory; volatile stores under MSVC) where they delete a plain assignment to memory that is not read again. A builtin, not a std function, because plain Egg cannot express such stores; the place must own nothing. - A struct of arrays, as Zig’s
MultiArrayList? Decided on 2026-11-22: a built-inMultiArrayList(T)(Zig’s name, first calledSoa), likeBuf(T), since Egg has no reflection (@typeInfo,inline for,@field) to write one in std; it can move there once reflection exists.Tis a struct of plain values, kept one column per field in one allocation, withappend,len,get,set,pop,swap_remove, ands.items(.x)for a column as a slice, which a reader sees is one column. Writing two columns at once is the point of the layout, so the ownership check treatss.items(.x)as the places.x, as it treats a struct’s fields:inout xs = &s.items(.x)and&s.items(.vx)do not clash. Aslice()returning every column, as Zig has, was dropped: slices cannot be struct fields, so it would need a view type of its own and still the same per-column places. Owned fields came on 2026-11-24, as aBuf’s elements may own memory: an owned element exists only as its columns, sogetandsetare refused for it (E139); its fields are borrowed from the columns, and whole elements go in withappendandreplaceand come out withreplace,popandswap_remove(which now returns what it removes), so freeing stays explicit.slice()stays out: each column’s pointer is already in the value, soitems()costs nothing, and a function that needs every column takes the list itself. - Exceptions via
setjmp/longjmpor a check after every call? - How does comptime run in the Spinel-written compiler: interpret the AST, or generate C and run it?
- Distinct types: type aliases (
const Bytes = Buf(u8)) are one type under two names. A new type over an existing one, to keep an invariant, already works for values that own something:const Text = owned struct { bytes: Buf(u8) }can only be built and changed in its own file. It does not fit a scalar such asUserId, which would have to be ended on every path, so a copyable type that other files cannot build is still missing. Revisit with owned strings. - Can users define their own capabilities, or does the first version ship only built-in ones?