Memory model
Value semantics, var rebinding, compiler-inserted reference counting with Perceus reuse, cycles through Graph, scope-bound resources, and backends in Sakura Lang.
In Sakura Lang every value behaves like its own copy. Changing one never changes another. You never manage memory yourself: there are no pointers, lifetimes, borrow annotations or Rc/Arc in user code.
type User = { id: Int, name: String, handle: String }
fn rename(u: User, name: String) -> User {
var v = u
v.name = name // sugar for v = User { ..v, name: name }
v
}
test "updates never alias" {
let a = User { id: 1, name: "Ada", handle: "ada" }
let b = rename(a, "Ada L.")
expect_eq(a.name, "Ada")
expect_eq(b.name, "Ada L.")
}renamechangesv.name, but the caller'sais untouched.v.name = nameis shorthand for building a newUserwith one field changed and storing it back inv.- The compiler may share memory behind the scenes, but your program can never tell.
The price of this model is a few rules: no shared mutable values, no cycles between values, and explicit scopes for files and connections. The rest of this page covers each one.
Value semantics
Assigning, passing, capturing and returning a value never creates an alias, a second name for the same mutable thing. Records, variants, lists, maps and strings cannot be changed in place from the program's point of view.
letbinds a name that cannot be reassigned.varbinds a name that can be reassigned. Reassigning changes the binding and nothing else.
Growing a collection
Collections grow the same way: xs = List.push(xs, 1). List.push returns a new list. If you call it and drop the result, that is error V2040, which catches a forgotten reassignment:
fn evens(n: Int) -> List<Int> {
var xs: List<Int> = []
for i in 0..n {
if i % 2 == 0 { xs = List.push(xs, i) } // List.push(xs, i) alone would be V2040
}
xs
}Closures capture values
A closure copies the var bindings it uses when it is created:
test "closures see the value at creation" {
var greeting = "hello"
let say = fn() { greeting }
greeting = "bye"
expect_eq(say(), "hello")
}- A closure cannot assign to an outer
var(V2041). Accumulate with avarin the same function body, or withList.fold. - A
trybody follows the same rule, because it may stop at any failing call. Assign after thetryinstead:let v = try { … } catch { … }, thentotal = total + v.
Shared state lives in handlers
The only places with changing state are handler var state and Graph, and both are confined. Shared mutable state, such as a counter or a cache, lives in a handler:
effect Counter { fn next() -> Int }
fn counter() -> Handler<Counter> {
handler Counter {
var n = 0
fn next() { n = n + 1; n }
}
}The state is private to the handler, starts fresh each time you install it with with, and is released when the with exits.
Cycles: use Graph
A value can only refer to values that existed before it, so values cannot form cycles. For cyclic data, such as a social graph, use std/graph. A Graph<N> owns a table of nodes, and edges are NodeId keys that the graph checks:
import std/graph.{Graph, NodeId}
type Person = { name: String }
fn befriend(g: Graph<Person>, a: Person, b: Person) -> (Graph<Person>, NodeId, NodeId) {
let (g1, ia) = Graph.insert(g, a)
let (g2, ib) = Graph.insert(g1, b)
(Graph.connect(Graph.connect(g2, ia, ib), ib, ia), ia, ib)
}ia and ib point at each other through the graph, but no value points to itself. Graph.get(g, id) returns Option<N>, so a stale id gives None, not a dangling pointer. There are no weak pointers.
Resources
A resource is something the host owns that must be closed: a file, a socket, a database connection, an HTTP body, a running task. You never open one and forget it. Instead, a function lends it to a callback and closes it when the callback returns:
This excerpt is from the standard Fs declaration; the omitted types come from std. It is not a standalone program.
effect Fs {
fn with_file<T, e>(path: Path, mode: Mode, body: fn(File) -> T ! e) -> T ! {Fail<FsError> | e}
}- The callback's result may not contain the resource (
V6003). Return the data you read instead. Sql.transaction(fn() { … })follows the same pattern.- Resources are released on normal exit,
fail, defect and cancellation, in reverse order of opening. A failed release is reported as a defect, never ignored. - Resources cannot be compared, shown or serialized, and are used at most once as a whole.
Streams are values
A std/stream Source is a value you pull items from. pull returns Done, or Next(item, rest) with the source that continues after the item.
import std/stream.{Source}
test "a pure source reads the same items every time" {
let src: Source<Int, {}> = Source.from_list([1, 2, 3])
expect_eq(src.fold(0, fn(a, x) { a + x }), 6)
expect_eq(src.fold(0, fn(a, x) { a + x }), 6)
}- A pure source (
Source.from_list,Blob.source, andmap,filter,linesorchunksover them) holds only values. Reading it twice reads the same items twice. - A view reads a resource:
Http.body_source(body, chunk)andFs.file_source(file, chunk). Two reads advance the same body or file. A view is scoped like its resource, so returning one from theHttp.streamorFs.with_filecallback isV6003.
No data races
There is no shared mutable memory, so tasks cannot race on data. Tasks communicate through their results (Task.join, Task.all, Task.race), through handler state (whose operations run one at a time), and through channels. Evaluation is strict and left to right, and Map/Set iterate in insertion order on every backend. See Concurrency.
Backends
A backend is what the compiler turns your program into. All backends give the same results; they differ in how memory is freed.
| Backend | Status | Memory management |
|---|---|---|
| JavaScript | the default; in every release | the JavaScript engine's garbage collector |
| WebAssembly | complete; in every release | reference counting inserted by the compiler |
| Native | experimental | reference counting inserted by the compiler |
sakura run # JavaScript, the default
sakura run --target wasm # WebAssembly, run through Node
sakura build --target wasm
sakura test --target wasm- WASM builds write
main.wasmand the Node host files totarget/sakura/wasm.runandtestexecute through Node 26, not a browser or WASI host. Intis a signed 64-bit integer on WASM. On JavaScript, anIntbeyond ±(2^53−1) is defectD003;String.parse_intreturnsNonefor such a value instead.--target nativebuilds an executable that runs directly. It is experimental: see Native builds.
Every backend starts from the same internal form, so they agree:
Select a backend with --target js (the default) or --target wasm. Native code is experimental: only a compiler built with the native Cargo feature accepts --target native, and no release includes it.
Stability. --target js and --target wasm are proposed as stable from v1.0.0-beta.1, and so is the WASM runtime ABI. Generated JavaScript, LIR and WASM bytes are internal and may change in any release. --target native is experimental. See Stability.
Reference counting and reuse
Because values never form cycles, reference counting (each value counts who uses it and is freed at zero) frees everything without a separate cycle collector. The WASM backend uses it today, conservatively. The JavaScript backend uses the engine's garbage collector instead.
The native design adds in-place reuse, a technique called Perceus. It is experimental and planned after 1.0:
- Same-shape reuse. When nothing else holds a value, an update or a
matchthat rebuilds a value of the same shape reuses its memory. - Copy-on-write buffers for
List,MapandString. Avar xswhose last use isList.push(xs, v)appends in place, which gives fast appends without exposing anything in the language. - Counts per task. Current native work is single-threaded; counts shared across threads are deferred.
type Tree = Leaf | Node(Tree, Int, Tree)
fn increment(t: Tree) -> Tree {
match t {
Leaf => Leaf
Node(l, v, r) => Node(increment(l), v + 1, increment(r))
}
}If the caller passes its last reference to t, native code can rebuild each Node in the memory it just took apart. If the tree is still used elsewhere, the update copies and the original stays intact. The result is the same either way.
When the compiler can prove an update copies because the old version is still used (read again later, captured by a live closure or handler, or stored in a live value), sakura check emits warning W8001 copy_on_write, pointing at that use. An update whose value only might be shared, such as a parameter, is not warned about.
Costs and limits
- Reference counting costs something on every use. Reuse is what makes it competitive; how well it works is not yet measured.
- Sharing a large value and then updating it copies.
W8001reports the copies the compiler can prove. - Cyclic data needs
GraphandNodeIds instead of direct references. - In the native design, handler state uses a lock per handler. Whether that holds up under parallelism is an open question.
- There are no regions (request-scoped arenas). The
regionkeyword is reserved.
What the compiler checks
- There is no syntax for mutating shared values or for pointer identity, so aliasing bugs cannot be written.
- A dropped non-
Unitresult is an error (V2040), which catchesList.push(xs, v)without reassignment. - Neither a lambda nor a
trybody can assign an outervar(V2041). - A resource cannot escape its scope (
V6003). - Reference counting is inserted automatically and is never visible in source.
Reference
Backend flags
--out-dir PATHselects another output directory onbuild,runandtest.runaccepts one source path and passes arguments after--to the program;buildandtestaccept several paths. With no path, they usesrc/when present, otherwise the current directory.build --emit lirwritesmain.lirtotarget/sakura/lir. LIR output supports--layout tagged;--emit lir --layout nicheis rejected as not implemented. WASM always uses the tagged layout.- There is no
build --releaseflag.build --manifestwrites the trust manifest for JS and WASM output, withtargetnaming which; it is rejected with--emit lir. Like JS, a WASM build drops the checkssakura verify --target wasmproved; see verification. - See the CLI reference for every flag.
WebAssembly
- HTTP sends and streams,
Sql.sqlite,Llm.stream,Serve.host()andLog.json()work on WASM, including requests withSecretHTTP headers (Http.bearer, andLlm.anthropicoverHttp.host()). The header's value reaches the host'sfetchand nothing else, and cassettes record it redacted, as on JS. test --recordrequires--target js; both backends read the cassette it writes. Ordinary tests andtest --contractsrun on both.- User
@external(js, …)bindings are rejected for WASM withV8004. - To call a library's functions from Node, see Embedding a library in Node.
- CI compares JS and WASM outputs, exits, defects and traces on Ubuntu and macOS, with explicit expectations for the integer-range difference. WASM defect codes, messages and source spans match JS. Spans come from
sakura.debug;--stripremoves them. See changes on main for host fault handling.
Native
The macOS arm64, Linux x64 and Linux arm64 release binaries (from v1.0.0-beta.4), the Intel macOS one (from v1.0.0-beta.5), and a compiler built from source with cargo build --release -p sakura_cli --features native, accept --target native on build, run and test. The native backend agrees with JavaScript on the semantics test corpus and runs every standard service, WebSocket from v1.0.0-beta.6. See Native builds.
Next
Concurrency: running work at the same time with tasks, cancellation, timeouts and retries.
Details for contributors: design §8.2, §10.2, §16.
Last updated
Capabilities and security
How Sakura Lang separates effects from authority, limits root handlers with sakura.toml, narrows authority for dependencies, and blocks injection and secret leaks.
Concurrency
Structured concurrency with the Task effect, cooperative cancellation, timeouts, retries, budgets, and deterministic scheduling in Sakura Lang.