Skip to content
lechatthecatPublic

About

Willow is an experimental, native, garbage-collected language for API servers. Its compiler and semantic CLI share the same frontend and query infrastructure, giving coding agents direct access to compiler-owned safety evidence, transitive effects, source-level witnesses, uncertainties, and the impact of code changes.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

Willow

Status: experimental Release CI License: MIT

Willow is an experimental, statically typed, garbage-collected language that compiles to native code through Cranelift. It has enums, pattern matching, classes, lightweight tasks, channels and lexical locks. The compiler enforces a set of concurrency rules, and a semantic CLI exposes its analysis to people and coding agents. Willow is not ready for production use.

What the compiler checks

Willow has two levels of checking:

  1. Checks that run on all code, with no annotations: what a task captures, whether a lock body can wait (also inside the functions it calls), and lock order.
  2. Contracts you add where you want them: @effects(...), requires / ensures and @verified.

This program has no annotations and is still rejected:

fn audit(ch: Channel<i64>) {
    let v = ch.recv();
}

async fn main() {
    let balance = Mutex::new(100);
    let ch = Channel<i64>::new();
    lock balance as mut value {
        audit(ch); // E2604
        value = value + 5;
    }
}
error[E2604]: cannot call a waiting helper while holding a Willow lock
 --> main.wi:9:9
  |
2 |     let v = ch.recv();
  |                ---- `Channel.recv` causes this transitive effect
...
9 |         audit(ch); // E2604
  |         ^^^^^ `audit` may suspend the task before returning

The checks are conservative and can reject safe code. Each diagnostic says where and why, so the author, or a coding agent, can change the code and check again.

willow check and willow build reject programs that break these rules:

Check Accepted code Limits
E2402 / E2408 Values captured by a task are shareable or exclusively lent to it. A transferred value can't be used through its old aliases. Tasks can't reach non-Sync immutable statics. The analysis is conservative and can reject safe code. Native shared memory isn't analyzed.
E2604 A lock body never waits, including inside the functions it calls. Calls with unknown effects are rejected. Console output is allowed. Rust functions marked #[willow::assume(no_block)] are trusted. Long computations are allowed.
E2605 Nested locks follow one acyclic order and never reacquire a held lock. Locks the analysis can't tell apart can't be nested; use a group lock instead.
@effects(...) A function has none of the declared effects, including through its calls. Unknown effects are rejected. Native declarations are trusted. no_alloc covers Willow allocation, not native allocation.

These rules don't exclude every deadlock or data race: tasks can still wait forever on channels or await outside a lock. See current limits.

E2607 reports some permanent waits in simple straight-line code. It is a bug finder: a program without E2607 can still hang. See the supported and unsupported cases.

At run time, when an unfinished async main and all of its tasks are stuck on channels or await, the program prints a wait witness and exits with status 1. See deadlock detection.

Compiler-owned semantic evidence

Rust and Go: the language server has its own analysis next to the compiler.

%%{init: {'flowchart': {'subGraphTitleMargin': {'top': 4, 'bottom': 28}}}}%%
flowchart TD
    src[Source] --> cfe
    src --> lfe
    subgraph cfe["Compiler<br/>rustc / types2"]
        ctc["Type checking<br/>and borrow checks"]
    end
    subgraph lfe["Language server<br/>rust-analyzer / gopls"]
        ltc["Own parsing,<br/>name resolution<br/>and type inference"]
    end
    cfe --> cg[Code generation] --> bin[Native binary]
    lfe --> ide[Editor or coding agent]
Loading

Willow: one frontend serves both the build and the semantic CLI.

flowchart TD
    src[Willow source] --> fe
    subgraph fe[Shared compiler frontend]
        tc[Type checking]
        cc[Concurrency checks]
        ea[Effect analysis]
        cv[Contract verification]
        db[(Compiler DB)]
    end
    fe --> cg[Code generation] --> bin[Native binary]
    fe --> cli[Semantic CLI] --> agent[Coding agent]
Loading

The semantic CLI runs on the same compiler frontend and query database as willow check and willow build. Language servers usually keep their own analysis next to the compiler: rust-analyzer has a frontend separate from rustc, and gopls uses go/types while the Go compiler uses types2. In Willow a query answer and a compile result come from the same code, so a tool or coding agent doesn't have to guess the rules from source text.

Besides symbols, types and references, the CLI reports what the compiler decided about safety:

  • willow check --format ndjson: diagnostics with spans, the location that caused them, and fix suggestions.
  • effects: what a function may do (wait, allocate, panic, ...) and the source location that causes it, as MAY, NONE or UNKNOWN. UNKNOWN is treated as possible. Unresolved calls and trusted native declarations are listed.
  • impact: the callers and callees an edit can reach, across modules.
  • Contract comparison: whether an edit keeps a function's contracts.
  • willow edit prepare / preview / validate / apply / recover: structured edits run as a transaction. The candidate is checked against the current source revision and validated before it is written; a failed apply rolls back the files it wrote.
  • willow agent instructions <codex|claude> prints agent instructions from the current binary; willow agent sync writes them into AGENTS.md or CLAUDE.md. See agent instructions.

With the experimental persistent cache (WILLOW_QUERY_CACHE=1), later queries reuse checked results saved by earlier runs.

Project status

Willow is a research project on compiler-enforced concurrency rules and machine-readable compiler evidence. Network services are a target use case, but the standard library and tooling are still small. Rust crates are used through handwritten adapters.

This README describes main; some features are newer than the latest release.

Try Willow

Download a prebuilt release for Linux x86_64, macOS arm64/x86_64 or Windows x86_64, and keep its bin/ and lib/ directories together. Linking needs a system C toolchain. Rust is needed only for Rust interop. Releases include checksums.

willow --version
willow init hello
cd hello
willow run

To build from source (Rust 1.96+):

git clone https://github.com/lechatthecat/willow.git
cd willow
cargo build --release
./target/release/willow --version

See installation and toolchain requirements.

A taste of Willow

async fn deposit(balance: Mutex<i64>, amount: i64) {
    lock balance as mut value {
        value = value + amount;
    }
}

async fn main() {
    let balance = Mutex::new(100);
    await deposit(balance, 5);
    lock balance as value { println(value); } // 105
}

If the lock is taken, the task parks until it is free. The lock is released on every exit from the body. E2604 rejects waiting inside the body, including in called functions; console output is the one exception. See the standard library and runnable examples.

Language essentials

A function, method or block lambda returns its final expression when it has no trailing semicolon. Each branch of a final if / else or match can supply the value. Use return value; for early returns. A semicolon discards a value; a non-void function that can reach its end without one reports E0205. Loop and defer bodies never return from the enclosing function.

class User { pub score: i64; }

fn score(user: User) -> i64 {
    match user.score { 0 => 10, n => n }
}

fn main() {
    let user = new User(2);
    println(score(user));
    println(2.0); // 2.0
}

Objects are created with new, as in new User(args...) or new model::Box<i64>(...); User(args...) without new is error E0843. Enum variants, static factories, functions and callable values are called without new, even when a function or local callable is named like a class.

print and println are ordinary functions from std::io, available without an import. They can be imported, aliased, shadowed or called as std::io::println(value). Each takes one printable value. To pass one as a callback, give it a concrete type with a lambda such as |value: i64| println(value). Printing scalars never panics, so it adds no panic path to the caller.

f64 values print with a decimal point when integral: 2.0, 0.0, -0.0. This applies to output, .to_string(), format and array display. Values outside 1e-6 <= abs(x) < 1e21 use scientific notation (1e30), and finite values round-trip exactly. Integers print as 2. JSON numbers keep their source spelling, so parsing and writing 2 yields 2. See the language example and float display example.

Integer overflow checks

Integer arithmetic is checked in debug and release builds. Turn the checks off with --overflow-checks=false:

willow run example/integer_overflow.wi --release
willow run example/integer_overflow.wi --release --overflow-checks=false

build, run and debug accept --overflow-checks=true|false or --overflow-checks true|false; the last value wins. In the library API, set options.target.overflow_checks: Option<bool>, where None means checked.

The setting covers +, -, *, **, unary -, +=, -= and *= on every integer width, and shift amounts outside the type's bit width, in every compiled module. A failed check raises a recoverable integer overflow panic with the source location and runs defer. wrapping_* and checked_* methods, division, remainder and array bounds keep their own behavior. See the example.

Runtime channel/await deadlock detection

When an unfinished async main and all of its tasks are suspended on channel operations, await or select, and nothing else can wake them (no runnable task, timer, I/O waiter or blocking operation), the runtime prints runtime deadlock with a wait witness and exits with status 1. This covers empty receives, full bounded sends, channel cycles and await chains.

runtime deadlock: task 1 (main) blocked on await; no runnable task or wake source remains
witness (registered waits; select entries are alternatives):
  task 1 (main) blocked on await
    await -> task 2
  task 2 (receiver) blocked on channel/select
    RecvWait -> channel 0x1234

The witness starts at main and follows await targets, listing task IDs, names, spawn sites and channel waits. IDs, names and addresses vary between runs. Channel identifiers are opaque; a registration doesn't name a sender, and select entries are alternatives. Output is capped at 64 tasks and 256 registrations, with truncation marked. The witness is collected only after the stop is detected, so normal execution pays nothing for it.

A program that is still making progress is never reported: a queued sender, finished task, timer, I/O event or completed blocking call keeps it running. Returning from main succeeds without waiting for detached tasks. See the channel protocol example.

Not detected:

  • Some tasks are stuck while another keeps running, or keeps a timer, I/O registration or blocking call outstanding.
  • An external peer never answers, a system call never returns, native code breaks its declared effects, or the program livelocks.
  • Synchronous main, nested synchronous scheduler drives and native blocking paths.
  • Detached tasks still blocked after main returns.

See the scheduler, witness traversal and deadlock tests.

Runtime instances

A Willow program runs on one process-wide runtime. Creating and managing several runtimes from a host application isn't supported yet; see embedding.

Details

Rust interop

Put Rust code in src/native.rs and write import native; in Willow. Public functions and structs become the interface, and inherent methods become Willow methods: pub fn add(a: i64, b: i64) -> i64 { a + b } is called as native::add(20, 22). List Cargo crates under [rust-dependencies]. Bind an owned resource with use resource = native::Resource::new(); to close it when the scope exits, including on errors and cancellation. See the native module example.

Willow generates the ABI wrappers but doesn't analyze Rust function bodies. Synchronous Rust calls made from tasks run on a bounded blocking pool, so the worker keeps running other tasks while one waits. Inside no_wait, no_suspend or a lock body, a Rust call needs a reviewed #[willow::assume(no_block)] attribute. See the parallel example and the execution policy.

  • Boundary types: scalars, strings, supported arrays, records, opaque handles, and Option/Result built from them. Classes, closures and raw pointers can't cross. See the record mapping, interface extraction and type mapping.
  • Async: Willow can await a Rust Future that is Send + 'static and owns its inputs. Rust can't call back into Willow. See the async example and interop directions.
  • Assumptions: #[willow::assume(no_block)] and no_io are the developer's claims about Rust code, including its conversions and destructors. Each needs a current review fingerprint. See bounded calls and reviewed assumptions.

Concurrency

The concurrency core defines the Send/Sync and loan, E2604 and lock-order rules, with executable models and differential tests.

Captures and transfers (E2402/E2408). Send and Sync are inferred from a type's structure. Mutable arrays and maps aren't Sync. A fresh local value with Send contents can be lent to one task until that task is awaited unconditionally in the same block. Values that loop or escape follow stricter rules. Tasks can't reach non-Sync statics, even through helpers. See loans, ownership transfer, capture tests and static sharing.

Shared mutable objects. Calling an async fn starts a task; there is no spawn keyword. A mutable object can't be shared with another task through arguments, closures, channels or fields while unprotected access to it remains. The diagnostic names the boundary or alias involved.

To share mutable state, use Mutex<T>, RwLock<T> or atomics, or share frozen data. Sending a non-Sync object through a channel transfers it: the sender and its aliases can't use it afterwards. A fresh local object can be lent to one task and used again after that task is awaited unconditionally in the block that lent it. See the shared-object example.

To fix rejected code, create the object inside the task, wrap it in a mutex and share the mutex, send it and stop using it, or send a frozen copy. A factory function needs a @sending return contract to show its result is fresh. Some race-free code needs these changes because branches, loops, unknown calls and escaping aliases are analyzed conservatively.

Closed channels. Sending on a closed channel raises a recoverable panic; values already buffered can still be received. A select send arm on a closed channel panics before its body runs. See the closed-send example.

Lock bodies (E2604). await, select, channel waits, blocking cells and synchronous file APIs are rejected inside a lock body, including through helpers, dynamic dispatch and imports. Console output and reviewed nonblocking Rust calls are allowed. See effect propagation, lock tests, indirect-call tests and the lock example.

Effect contracts. no_block excludes blocking, no_suspend excludes suspension and no_wait excludes both. no_panic excludes language faults, no_alloc excludes Willow allocation and no_io excludes external access. Each covers called functions too, and an override can't weaken an inherited contract. no_alloc doesn't cover allocation for panic reports or runtime bookkeeping, no_io isn't an OS sandbox, and no_panic doesn't cover running out of memory. See contract examples, I/O examples, checker and tests.

Contracts and proofs

@verified implies purity and proves a function's contracts with Z3. It supports integers, bool, char, String equality and byte length, frozen arrays and immutable data. Other String methods aren't supported yet. Unsupported code and failed proofs are compile errors. Install Z3 4.15.4 and put z3 on PATH, or set WILLOW_Z3. See the proof example, strings, immutable data, loops and no-panic proofs.

A failed proof points at the clause that failed. Replacing non_negative's body in this example with return x; gives:

error[E2630]: @verified `non_negative`: COUNTEREXAMPLE: ensures truth: sat; candidate inputs x = -1; result = -1

The label points at result >= 0. Inputs use source names and Willow values such as [-3], new Point(-4) and Choice::Yes(-6); records built by explicit constructors are shown as Point { x: -4 }. The values come from the solver, so with loops or abstracted calls they may not reproduce the failure when run. UNKNOWN also fails the proof.

In verification JSON (willow.verification.v1), each failed obligation has a presentation object (willow.verification.presentation.v1) with evidence: "CANDIDATE", the failing location and obligation, source-named inputs, an optional result, and an incomplete reason when values can't be shown. Preconditions that can never hold report evidence: "VACUOUS_PRECONDITION". Ignore presentation versions you don't recognize.

@effects(pure) forbids any interaction beyond arguments and results, including reads of mutable heap data and calls to unknown functions. It combines with other effects, as in @effects(pure, no_panic). Purity alone allows panics and allocation. Impure bodies are rejected with E2620, also under @verified alone. @pure is an alias, and repeating a contract has no extra effect. An override that lists its effects must keep inherited purity (E2611); an override without a list inherits it.

requires / ensures are checked at run time in debug and release builds and raise recoverable panics. See pure functions and runtime contract cases.

Locks

Nested locks (E2605) follow one project-wide order and can't reacquire a held lock. Locks the compiler can't tell apart, such as two parameters of the same lock type, can't be nested. Locks are released on every exit, panic and cancellation; writes are not rolled back. See ordered locks, parent/child locks and tests.

Group locks, such as lock from as mut debit, to as mut credit { ... }, acquire their members in runtime identity order. If one is taken, the group releases the others before parking. Duplicate handles are rejected. Group acquisition isn't fair, so a group can starve. See the implementation.

Hand-over-hand traversal uses lock walk cursor as node { ... }, where cursor is a local Mutex<T> variable. Set cursor to the next node in the body. At the end of each iteration, the walk takes the next lock before releasing the current one. break ends the walk; return, panic and cancellation release the held lock. Body defers run at the end of each iteration.

The first lock is waited for normally. Each handover tries once: if the next lock is taken, or the cursor points back at the held node, the walk panics. Two walks in opposite directions therefore can't deadlock. In a longer cycle the walk can revisit an earlier node, so the program decides when to stop. At most two locks are held during a handover and one while the body runs. Nesting a walk and another lock is rejected by E2605. See the linked-list example.

Semantic tooling

The CLI provides effects, impact, refs, type, symbol, rename and overview, with structured output. See the AI toolchain protocol.

  • Rename edits every resolved occurrence in the project and checks the result. Strings and code outside the project are untouched. Preview with willow rename SELECTOR NEW_NAME --dry-run --diff. See rename tests.
  • Effect states: MAY comes with a witness. UNKNOWN means the analysis couldn't decide and treats the effect as possible. NONE means the analysis found no way for the effect to happen (native declarations are trusted). See the effect-state example.
  • Contract comparison checks whether an edit keeps a function's contracts; it doesn't prove the old and new code behave the same. Approving a change needs --protected-base COMMIT, --approval-evidence FILE and --approval-verifier EXECUTABLE. Use a verifier outside the editable checkout; being outside it doesn't make a verifier trusted, so choose one you trust. It must check the evidence and request binding, finish within 10 seconds, and print exactly {"schema":"willow.contract-approval.v1","approved":true,"binding":<request binding>}. See comparison, repair and tests.

Type parameter queries and rename

A type parameter's selector is module::owner::parameter, for example util::fold::T for fn fold<T> or util::TopK::T for class TopK<T>. symbol also accepts file:line:column on the parameter or any use of it. refs lists its uses inside the owner, and rename changes them together with the declaration; --dry-run --diff previews the edit. Same-named parameters of other owners don't change. Rename refuses names that would clash inside the owner. See the type parameter example.

Measurements

Measured on 2026-11-28 (commit e0e602a7): Ryzen 7 7800X3D, Linux, release builds, Go 1.27.0, OpenJDK 26.0.2, 8 workers, median of 5 runs. Some cases time the whole process, so their Java numbers include JVM startup. Willow builds use --overflow-checks=false, since Go and Java don't check overflow either. With checks on, fibonacci takes about 3.7x as long, closure_call and virtual_dispatch about 1.7x; the other cases are within a few percent.

Case Work Willow (ms) Go (ms) Java (ms) vs Go vs Java
idle_spawn 100,000 parked tasks 59.0 121.4 84.3 Willow 2.06x Willow 1.43x
wake_fanout 100,000 tasks, one send each 71.6 13.0 179.5 Go 5.49x Willow 2.51x
yield_switch 100,000 tasks × 100 yields 343.6 1,417.7 548.9 Willow 4.13x Willow 1.60x
ping_pong 1,000,000 channel round trips 721.1 166.4 778.0 Go 4.33x Willow 1.08x
gc_scheduler 10,000 tasks × 100 alloc/yield rounds 63.0 133.7 140.0 Willow 2.12x Willow 2.22x
channel_select_fan_in 1,000,000 select receives 881.4 231.7 535.9 Go 3.80x Java 1.64x
spawn_join_tree 111,110 spawn + join 33.6 16.0 99.2 Go 2.10x Willow 2.95x
server_sim_c1000 1,000 connections × 1,000 requests 205.4 79.9 323.8 Go 2.57x Willow 1.58x
general_pow 20,480,000 pow calls 582.3 603.6 199.5 Willow 1.04x Java 2.92x
leibniz_reduced 100,000,001 terms 108.6 99.4 263.8 Go 1.09x Willow 2.43x
fibonacci naive fib(40) 173.1 386.9 230.6 Willow 2.23x Willow 1.33x
array_sum append + sum 5,000,000 i64 60.6 52.9 88.7 Go 1.15x Willow 1.46x
linked_list build + traverse 1,000,000 nodes 32.3 25.9 47.1 Go 1.24x Willow 1.46x
array_read_sum_only index-read 5,000,000 values 4.1 2.2 5.0 Go 1.91x Willow 1.21x
array_write_only index-write 5,000,000 values 4.9 3.2 7.3 Go 1.55x Willow 1.48x
object_churn 10,000,000 short-lived objects 69.8 56.4 71.2 Go 1.24x Willow 1.02x
map_lookup_insert 1,000,000 inserts + 2,000,000 gets 89.4 84.3 201.3 Go 1.06x Willow 2.25x
virtual_dispatch 20,000,000 interface calls 65.6 40.4 58.4 Go 1.62x Java 1.12x
closure_call 20,480,000 closure calls 52.6 25.9 16.7 Go 2.03x Java 3.15x
string_build 2,000,000 built strings 61.2 80.3 85.2 Willow 1.31x Willow 1.39x

100,000 parked tasks use 757 bytes of memory each in Willow (Go 2,743, Java 1,348). See the benchmark harness to run the cases yourself.

Current limits

  • Willow is experimental and not ready for production.
  • The checks cover Willow code. Rust adapters, native threads and native memory aren't analyzed; Rust effect declarations are trusted.
  • The checks don't prove termination, fair scheduling, freedom from every data race or freedom from deadlock outside locks.
  • Conservative analysis can reject correct programs.
  • The guarantees depend on the compiler, runtime and GC being correct.

MIT licensed. See LICENSE.

About

Willow is an experimental, native, garbage-collected language for API servers. Its compiler and semantic CLI share the same frontend and query infrastructure, giving coding agents direct access to compiler-owned safety evidence, transitive effects, source-level witnesses, uncertainties, and the impact of code changes.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages