Sakura Lang

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.")
}
  • rename changes v.name, but the caller's a is untouched.
  • v.name = name is shorthand for building a new User with one field changed and storing it back in v.
  • 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.

  • let binds a name that cannot be reassigned.
  • var binds 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 a var in the same function body, or with List.fold.
  • A try body follows the same rule, because it may stop at any failing call. Assign after the try instead: let v = try { … } catch { … }, then total = 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, and map, filter, lines or chunks over them) holds only values. Reading it twice reads the same items twice.
  • A view reads a resource: Http.body_source(body, chunk) and Fs.file_source(file, chunk). Two reads advance the same body or file. A view is scoped like its resource, so returning one from the Http.stream or Fs.with_file callback is V6003.

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.

BackendStatusMemory management
JavaScriptthe default; in every releasethe JavaScript engine's garbage collector
WebAssemblycomplete; in every releasereference counting inserted by the compiler
Nativeexperimentalreference 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.wasm and the Node host files to target/sakura/wasm. run and test execute through Node 26, not a browser or WASI host.
  • Int is a signed 64-bit integer on WASM. On JavaScript, an Int beyond ±(2^53−1) is defect D003; String.parse_int returns None for such a value instead.
  • --target native builds an executable that runs directly. It is experimental: see Native builds.

Every backend starts from the same internal form, so they agree:

The compiler pipeline on main (design §13). One Core feeds every backend; WASM and native share the LIR.source: .sak files, parsed with error recovery. CST: lossless; the formatter works here. HIR: names resolved. Typed HIR: types, effect rows, holes, obligations. Core: explicit Perform, Handle, Fail, Check. Then JavaScript or LIR. JavaScript: the default target; runs on Node. This path ends here. LIR: from a Core snapshot; reference counts made explicit. Then WebAssembly or native. WebAssembly: complete; runs on Node. This path ends here. native: Cranelift; experimental, behind a feature.source.sak files, parsedwith errorrecoveryCSTlossless; theformatter workshereHIRnames resolvedTyped HIRtypes, effectrows, holes,obligationsCoreexplicit Perform,Handle, Fail,CheckJavaScriptthe defaulttarget; runs onNodeLIRfrom a Coresnapshot;reference countsmade explicitWebAssemblycomplete; runs onNodenativeCranelift;experimental,behind a feature

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.

The compiler pipeline on main (design §13). One Core feeds every backend; WASM and native share the LIR.

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 match that rebuilds a value of the same shape reuses its memory.
  • Copy-on-write buffers for List, Map and String. A var xs whose last use is List.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. W8001 reports the copies the compiler can prove.
  • Cyclic data needs Graph and NodeIds 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 region keyword 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-Unit result is an error (V2040), which catches List.push(xs, v) without reassignment.
  • Neither a lambda nor a try body can assign an outer var (V2041).
  • A resource cannot escape its scope (V6003).
  • Reference counting is inserted automatically and is never visible in source.

Reference

Backend flags

  • --out-dir PATH selects another output directory on build, run and test. run accepts one source path and passes arguments after -- to the program; build and test accept several paths. With no path, they use src/ when present, otherwise the current directory.
  • build --emit lir writes main.lir to target/sakura/lir. LIR output supports --layout tagged; --emit lir --layout niche is rejected as not implemented. WASM always uses the tagged layout.
  • There is no build --release flag. build --manifest writes the trust manifest for JS and WASM output, with target naming which; it is rejected with --emit lir. Like JS, a WASM build drops the checks sakura verify --target wasm proved; see verification.
  • See the CLI reference for every flag.

WebAssembly

  • HTTP sends and streams, Sql.sqlite, Llm.stream, Serve.host() and Log.json() work on WASM, including requests with Secret HTTP headers (Http.bearer, and Llm.anthropic over Http.host()). The header's value reaches the host's fetch and nothing else, and cassettes record it redacted, as on JS.
  • test --record requires --target js; both backends read the cassette it writes. Ordinary tests and test --contracts run on both.
  • User @external(js, …) bindings are rejected for WASM with V8004.
  • 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; --strip removes 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.

Edit on GitHub

Last updated

On this page