Skip to content

Internals

The strata command is the compiler/ package, written in Strata. A previous strata builds it (tools/bootstrap.sh, iterated to a fixed point), with a small C runtime and LLVM linked in.

File What it is
compiler/ the strata command: front end, checker, verifier, code generator, codebase commands and driver (modules listed below)
compiler/c/ the C linked into the compiler. jit.c runs compiled code in memory with LLVM’s JIT. ir.c builds codegen’s IR text in LLVM through its C API. toolchain.c compiles IR to objects in parallel parts kept in the cache, and links with lld through lld.cpp, the only C++ file, because lld has no C API. Also driver.c, cache.c, and libSystem.tbd, the stub of macOS’s libSystem that executables link against
runtime/runtime.c the C runtime that compiled code links with: reference counting, big integers, printing, tasks and channels, host I/O. With -DSTRATA_CORE_RT, core.rt replaces its allocator and its string, integer and list functions
runtime/prelude.strata compiled with every program: the list builtins (plus keys, values and map_values over a dict’s entries), lines, and the string builtins written over byte_len, byte_at and byte_slice
core/ the builtin types and functions (builtin type, builtin fn with their requires), the types and traits every program names, the code modules (core.iter, core.channel, core.text, core.task), raw memory (core.mem, for core’s own modules only), and reading compiled values back (core.values’ Raw, for core and packages with [values] read = true)
core/rt.strata, core/str.strata, core/int.strata, core/list.strata, core/fmt.strata, core/float.strata, core/gen.strata, core/fault.strata, core/run.strata core.rt, the part of the runtime written in Strata, and its topic modules: strings, integers and big integers, lists, f-string format specs, floats, value generators (mock and fuzzing), the call stack and faults, and running a test
std/ the standard library, in Strata. Only std can call the native host_* operations
std/typing.strata what a derive’s compile-time code sees of a type
std/json.strata, std/toml.strata JSON and TOML, and the derived Json and Toml traits
std/regex.strata, std/unicode.strata, std/unicode_tables.strata, tools/unicode_tables.py regular expressions: the parser and the tree (modelled on regex-syntax’s Hir), code point sets, Unicode properties and case folding. The script generates the tables from regex-syntax’s
std/cli.strata command-line options: a record that derives CommandLine is parsed by its derived from_args
std/sqlite.strata, compiler/c/libsqlite3.tbd SQLite through extern c and the system’s libsqlite3 ([native] libs in std/strata.toml), behind the Sqlite capability and the Database trait. The code that calls C is left out of std’s precompiled library and compiled with the programs that use it. build links those against the stub, and the JIT loads the library
compiler/wasm.strata, runtime/wasm.c, runtime/wasm.h strata build --target wasm32 (wasm_built): the program’s IR and core.rt’s, runtime.c (STRATA_WASM leaves out its threads, files and processes) and wasm.c (a small C library, the host’s imports) compiled for wasm64 by clang, linked by wasm-ld, lowered to wasm32 by wasm-opt. std.ffi’s TypeScript writes the loader NAME.ts
std/python.strata, the end of runtime/runtime.c extern python: desugar turns each declaration into a call to std.python (arguments through to_json, the reply through from_json). std.python sends a JSON line to a Python worker that the runtime starts on the first call (python_worker_call, through extern c). The worker’s driver is a string in runtime.c
std/net.strata, the end of runtime/runtime.c sockets: extern c calls to the runtime’s std_net_* functions. A connection is a slot in a table, named by a 64-bit handle (index and generation), so a handle used after close fails. Every socket is non-blocking: a call that would wait polls first, with the thread’s wake pipe when it can be cancelled (the same wait as stdin’s read_line), so a race or a cancelled scope stops it. Bytes cross one at a time through a buffer per thread (std_net_byte, std_net_push_byte); text crosses as strings. TLS is Secure Transport, loaded with dlopen at the first start_tls, so programs that don’t use it don’t link Security.framework
std/agent.strata the agent loop: run asks a Model for replies until one calls no tools, answering its calls; Claude sends the Messages API’s JSON over std.http, and its stream reads the server-sent events of std.http.open’s body into Chunks as Stream’s next is called. derive Tool for f makes a type Tool$f (a record of the bound parameters) implementing the Tool trait at compile time: the schema from std.typing (input_schema), the call from Self.try_call with std.json.decode_as per parameter. A list of tools is a list of trait values (a table of methods and the value)
std/rust.strata, compiler/cargo.strata, the end of runtime/runtime.c extern rust: desugar turns each declaration into a call to std.rust, as for extern python. cargo writes a crate with a C function per declaration into the package’s .strata/rust and builds it with cargo (rust_built, before run, test and build); std.rust calls it through rust_library_call: dlsym finds the functions in a built executable, which links the static library (rust_linked), else the shared one is loaded from the setting rust.library
std/ts.strata, the end of runtime/runtime.c extern ts: as extern python, with a Node worker (ts_worker_call, the JavaScript driver a string in runtime.c); the workers share Worker
std/io.strata, std/fs.strata, std/process.strata, std/http.strata, std/web.strata, std/code.strata, std/time.strata the console, files, the process, HTTP and routes, HTML as values, the codebase as values (Codebase), clocks
tests/cases/, tests/data/, tools/check/ the golden-output cases and their runner (strata run tools/check); see testing.md
tools/bootstrap.sh, tools/build-lld.sh, tools/release.sh, tools/release-check.sh, tools/libsystem-tbd.sh, tools/cache-portable.sh building strata with itself, building lld’s libraries, making and checking a release, generating libSystem’s stub, and checking that caches are portable

core/ declares what every program has without a use. It is a package below the standard library: std depends on it, and it depends on nothing.

  • core.types: the built-in types, Debug, Display, Option, Result, and the prelude’s refinements.
  • core.builtins: the builtin functions.
  • Code modules that a program gets only when it uses them:
    • core.iter: iterators, when the program names one of their definitions (xs.iter(), impl Iterator, …). A list’s map is a builtin and doesn’t need it.
    • core.channel: channel(), Sender, Receiver and their methods.
    • core.text: s.bytes(), s.code_points().
    • core.task: Panic, for supervised spawn.
  • core.mem: raw memory on machine integers (Ptr, raw_alloc, load_i64, store_u8, atomic_add_i64, …), which the runtime is written in. Only core’s own modules can use it; Ptr and its functions are errors anywhere else.
  • core.values: reads a compiled value back from memory, read-only, on top of core.mem. Raw is a value’s address as compiled code hands it over. r.word(i) reads its 64-bit slot i (a block’s tag and fields, a list’s header), r.at(i) reads slot i as a value, and r.byte(k) reads a byte. Core’s modules can name Raw, and so can a package whose strata.toml sets read = true under [values], which the compiler does to read back the values of compile-time code. Anywhere else, Raw is an error, reported once per definition. verify never runs a function that takes one.
  • core.rt: the runtime written in Strata. It holds the allocator and reference counting (strata_alloc, strata_dup, strata_release, strata_free) and every strata_... entry point. It calls the topic modules core.str (strings), core.int (integers), core.list (lists), core.fmt (format specs), core.float (floats), core.gen (generated values), core.fault (the call stack and faults) and core.run (running tests and fuzz cases), which only it uses. None of these modules may allocate. The checker rejects lists, records and closures built at run time, Int arithmetic, and calls to anything other than the runtime’s functions, core.mem’s, and the integer conversions.

strata --file core test runs core’s tests, except those of the runtime modules (core.rt and the rest), which compile only together into the runtime.

Whatever the compiler itself provides is declared with builtin, which only core may use. A builtin is a type with its parameters (builtin type Dict[K, V]) or a function signature. A function has a requires where it fails on some arguments, so a builtin’s precondition is a contract like any other, and a builtin without requires always returns:

/// `xs[i]`: element `i`, from 0.
builtin fn at[A](xs: List[A], i: Int) -> A
requires 0 <= i && i < len(xs)
/// The string of one character, code point `c` (not a surrogate).
builtin fn chr(c: Int) -> String
requires 0 <= c && c <= 1114111 && !(55296 <= c && c <= 57343)

A name can have several signatures (len of a list, dict or set). A call uses the first whose parameters fit the arguments.

  • strata --file core view builtins shows them all, and strata builtins lists them briefly.
  • strata --file core/ edit MODULE < text stores a module of core as written. An edited builtin replaces the one with the same name and parameter types, and other overloads stay. Builtin names are global, not module-scoped.
  • strata --file core check checks the core that strata is built with.

Not yet expressed as contracts: matches with a pattern that isn’t a valid regular expression, and a channel used after it ended.

strata build compiles a program to an executable through LLVM:

  1. compiler/codegen writes LLVM IR as text.
  2. compiler/c/ir.c builds the IR in LLVM, which is linked into strata, through LLVM’s C API. LLVM’s own IR text reader is used only for constructs ir.c doesn’t handle, because it is several times slower.
  3. LLVM compiles the IR to objects, at -O0 with fast instruction selection.
  4. lld links the objects with the runtime and std’s precompiled library. It keeps only the functions and data the program reaches (-dead_strip), so a hello world is about 55 KB.

Parts and caching. The IR is split into parts: runs of whole functions, each with copies of the constants it uses and, when optimizing, of the small functions it calls, so they can be inlined. Parts compile in parallel, one thread per core.

  • Each part’s object is cached under the hash of its text (objects/), so after an edit only the changed parts are recompiled.
  • The program’s IR is cached under the bytes of every file it comes from (ir/), along with what verify proved, in the form codegen reads (proofs-lines/). Building an unchanged program only links.
  • A package with its own C ([native]) caches its C objects and its linked executable, one per output path, keyed by the link’s arguments and the size and modification time of each file they name. Building it again unchanged only copies the executable.
  • C files not yet cached (the runtime’s, a package’s) are compiled immediately, one C compiler process each, while LLVM compiles the program.
  • Objects are linked in part order, so the same program always produces the same bytes.

--emit-llvm prints the IR instead. A program that compiler/codegen can’t compile is an error that says why.

Optimization levels. Programs are compiled unoptimized (-O0), the fastest to build. --release compiles at -O2, and run and test accept it too. Compile-time code and the probes that confirm counterexamples are always unoptimized, since they run once. verify’s fuzzing is always optimized, since its cases run many times. std’s precompiled library is built once at -O2, by the first run, build, test or check that needs it. verify never builds it: it loads it when it is already made, and otherwise its fuzzed and compiled checks compile the std functions they call.

The runtime. The runtime is linked in as a precompiled object. A release ships runtime-lto.o: runtime.c and core.rt in one module, optimized together at -O3 by tools/release.sh, so a user’s build never compiles it. Without it, runtime.c (C compiler, -O2) and core.rt (-O2) are each compiled once and cached.

The runtime is written in C (runtime/runtime.c), except for core.rt and its topic modules, which are written in Strata: the memory allocator (strata_alloc, strata_dup, strata_release, strata_free), strata_unique, the string, integer, list, format and float functions, value generators, and rendering a fault’s call stack (core.str, core.int, core.list, core.fmt, core.float, core.gen, core.fault). strata build-core compiles it to LLVM IR under the C runtime’s names, and every executable links it. strata itself is built in two stages to use it (tools/bootstrap.sh; see core/rt.strata in the source layout).

build first verifies what changed since it was last verified (--no-verify skips this and keeps every check), and the checks it proves are left out of the program (--all-checks keeps them; see verification). So are the checks verify proved of std where std’s code is compiled into the program, a generic’s instance: std’s library is made with those proofs, and the cache keeps them beside it (main.std_library_proofs). The proofs lists hold each check on one line (text.proof_text), so a contract written over several lines matches its proof.

What compiles. A compiled program behaves like strata run: the same output, and the same run-time contract checks and fault messages (refinements of parameters, results, annotated bindings, declared variables and new values, requires, ensures, assert), exiting with 101. The whole language compiles; there is no interpreter. The exception is a few methods called on a value of a trait type: one taking Self inside another type, such as List[Self], or using type parameters together with Self or mut. Those are rejected with an error that says so. In detail:

  • Int is arbitrary-precision. A value in [-2^62, 2^62) is a machine integer, and arithmetic on it is inline. Any other value is a big integer in the runtime, encoded in the 64-bit values outside that range, so comparing a small and a big integer needs no call. Also Float, Bool, String, (), and refinements of them.
  • A Float operation’s result is tested inline (fabs against infinity). The runtime (strata_finite, declared cold) is called only to write the fault, and the code doesn’t come back from that call into the loop. So a loop of float operations has no call on its cycle, and LLVM keeps what it reads (a list’s header) in registers.
  • Conversions between Int and the 64-bit sized types (x.to_int(), n.to_i64(), n.wrap_i64()) test for a small integer inline and call the runtime only for a big one. xs[i] with i: I64 (core’s at(List[A], I64)) reads the slot directly, with no Int made.
  • Records, variants (Option, Result and user-defined), tuples, distinct types and unions of any types, with field access, { ..e, f: x }, field assignment (x.a.b = e), is, ==, and printing as code (Debug, Display).
  • Generic functions and types, each compiled once per set of type arguments. Inherent methods (impl Item { ... }). Traits, with the implementation chosen from the type where the call is compiled: default methods, supertraits, generic traits and implementations, static methods like T.empty(), and a variant’s own implementation chosen by its tag. The trait’s requires and ensures apply to every implementation.
  • Lists: literals, +, list patterns ([x, ..rest]), for, xs[i], slices (xs[1..]), and the list builtins (len, get, at, slice, push, take, drop, range, map, filter, fold, all, any, find, count, contains, reverse, sort, sort_by, zip, enumerate, sum, join), most written in Strata (runtime/prelude.strata).
  • Dicts and sets: literals (Dict { "a": 1 }, Set { 1, 2 }, typed empty ones), dict, set, insert, remove, get, contains, keys, values, items, map_values, to_list, union, intersection, difference, len, for (a dict yields (key, value) pairs), ==, printing, and the refinements of elements, keys and values.
    • Each is a hash table (runtime.c’s strata_tbl_…): a block laid out as the tuple of its entries, plus an index. Entries are a set’s elements or a dict’s (key, value) pairs, in insertion order, with a removal closing the gap. The index uses open addressing, and tables of up to 8 entries have none.
    • Lookups use functions codegen generates for the key type: @"tbl.hash:T" over @"hash:T", the structural hash, and @"tbl.cmp:T" over the order.
    • for, len, items and printing use the entries list, == compares contents, and two tables are ordered by their sorted entries.
    • compiler/eval stores a table’s entries the same way. No hashing is needed there, since the order depends only on the operations performed, so it prints tables exactly as compiled code does.
  • Strings: +, comparisons, a string’s units (bytes(), code_points(), graphemes()), byte-offset positions (byte_len, byte_slice, index_of), and the string builtins (split, lines, trim, contains, starts_with, ends_with, replace, repeat, reverse, chars, to_upper, to_lower, is_digit, is_alpha, is_space, ord, chr, parse_int, parse_float). Most are written in Strata in the prelude over byte_len, byte_at and byte_slice. The searches (contains, index_of, split, replace) go through the prelude’s str_find_from, which codegen compiles to the runtime’s strata_str_find (memchr to each place of the first byte, then memcmp). The rest (trim, case mappings, the is_ tests, number parsing) are C in the runtime, with case mappings and is_alpha from generated tables.
  • Iterators (for over any Iterator, lazy map and filter, iter()), tasks (scope, spawn, await, one thread per task), channels and select, written invariants (checked at the loop’s head), and extern c calls.
  • Lambdas and closures, named functions as values (filter(is_prime)), and functions that return functions.
  • Functions and recursion, bindings (x := e with patterns, let x: T = e), mut variables and assignment (=, +=, …), if, match with every pattern, while, loop, for, break, continue, return, assert, !, ?, except.
  • f-strings with format specs ({x:.2}, {n:>5}, {n:05}, {s:*^9}), and print, to_string, abs, min, max, float, floor, ceil, round, sqrt.
  • mut parameters and receivers (restock(mut line.qty, 5), mut console.print(s)). The function changes the caller’s variable in place, and the variable’s declared type is checked after the call.
  • Capabilities. main can ask for Console (std.io) and capabilities such as Disk, Process and Codebase (std.fs, std.process, std.code), and gets the terminal, the disk, the process and the codebase in the current folder, as with strata run, along with the program’s arguments. Codebase’s snapshot is built by strata and written into the program’s memory, so an executable from strata build has none and faults saying so.
    • A parameter whose type is a trait (console: Console) is compiled once per implementation passed to it, as the language defines it (console: C for some C: Console). The real console and a test’s Recorder each get their own copy.
    • A trait used as the type of a field, a list element or a let ({ console: Console }, List[Shape]) holds any implementation. The value carries its implementation’s method table, and calls go through it.
  • Options: main can ask for a record that derives CommandLine (std.cli). The compiled program parses it with the same from_args, so --help and bad-argument messages match strata run (exit code 0 after help, 2 after an error). The usage line names the executable as it was started; strata build names it after the package, as strata run does.
  • main returns (), an exit code, or a Result of either.

A fault prints the call stack as strata run does ( stack: main -> inner -> half). Running out of stack is a fault (fault (Limit): stack overflow (recursion too deep)), not a crash. There is no other limit: loops run as long as they run, and recursion goes as deep as the stack allows. The stack: line collapses a recursion into one entry (main -> down (95846 times)).

Regular expressions. matches(s, re) is std.regex’s, compiled. For a literal pattern a DFA can match, codegen builds the DFA while compiling (std.regex.matcher, codegen.regex_matches) and stores its tables as constant lists, which std.regex.run_parts runs: no allocation per call. Any other pattern, one that asserts more than ^ and $ or is built at run time, is parsed, compiled and matched by the Pike VM on each call (std.regex.match_code), written in Strata and precompiled with std, including in built programs. An invalid pattern faults with std.regex’s message (bad regex: unclosed group (at character 11)).

Memory is reference-counted, and a value is freed as soon as nothing holds it.

  • No object is counted by two threads, so every count is a plain load and store. What crosses to another thread is the receiving thread’s own: what a spawn captures (a race arm and a supervised spawn too), what is sent on a channel, and a task’s result when its handle was sent to another thread. Codegen’s cross:T helpers walk the value at the crossing (a closure’s captures through the function in its block’s fourth word, a trait value’s through its table’s last entry). A block held once by the giver moves as it is. Any other block is copied (core.rt’s strata_cross_block: one allocation outside any arena and a copy of its bytes), and what it holds is copied in turn. A constant or a block on the stack (count 0) is given as it is, without what it holds: so a variable a lambda or a spawn mentions is never on the stack (codegen’s escapes). So a value passed on its last use moves for the cost of one test per block, and a value the sender keeps costs a copy of it.
  • Channel ends are blocks of their thread pointing at the channel. An end that crosses is a new end of the same channel (strata_channel_cross), and the channel counts its ends under its lock.
  • A task’s result comes back through await after the task’s thread is joined, so only the awaiting thread sees it and it gains a holder there. When the handle was sent to another thread, more than one thread may await it: the result is replaced by its own copy when the handle crosses (strata_task_share), and each await then copies it under a lock (strata_task_shared).
  • strata_memory_keep_shared (core.rt), which the compiler calls while its workers run, freezes what crosses instead of copying it, except blocks held once, which still move. A frozen object’s count word is core.rt’s frozen_mark (negative, so the compiled code’s inline test leaves it to the runtime): no thread counts it again and it is never freed. The workers then read the compiler’s tables without copying them. Check mode freezes nothing.
  • A frozen object is never changed in place, grown or written past its end: other threads may read it.
  • Code from an older compiler runs as follows: code that marked crossings shared (strata_share) freezes what it marks, and code that marked nothing (strata_spawn) runs each task to its end before the spawn returns. Both are a bootstrap’s first stage only.
  • Each thread takes small objects from its own free lists, refilled from the shared lists 64 at a time and returned when the thread ends, and opens its own arenas. An object freed by another thread than the one that made it goes to the freeing thread’s list.
  • A list extended in place past its end claims the slot plainly, as only its thread sees the buffer, unless the buffer is frozen: then the push copies.
  • A list is a header (its length, its buffer and its offset in it) over a buffer (its capacity, how many slots are used, then the slots). mut xs.push(x) and xs = push(xs, x) change the header in place when nothing else holds the list: its header and buffer are held once, the buffer is all its own, and, while an arena is open, the arena made both (strata_list_pushable). A full buffer then doubles. Otherwise the push makes a new header, as the built-in does. The check costs two count reads; the in-place push makes nothing.
  • A non-empty list literal whose elements are all constants (Int literals, strings, field-less constructors) is one constant block: a header and a buffer with counts of 0, emitted once per program (codegen constant_list). It costs no allocation. A change to it copies it first, as for any list held twice. The buffer is writable data, since list_extend writes a buffer’s used count, unchanged, when it adds nothing.
  • xs = xs[..n] and xs = take(xs, n) drop the tail in place when nothing else holds the list (take_in_place). The buffer then ends where the list does, so a later push or + extends it in place.
  • for x in xs over a non-mut variable borrows the list, since the variable holds it through the loop. Over any other list the loop holds it. An iterator made for the loop (for b in s.bytes()) moves into the loop’s variable, so its mut self method finds it held once.
  • x += s (and x = x + s) on a string held once by x writes s after x’s bytes when its block has room (str_append). Otherwise it makes a new string with room for as many bytes again, so building a string of n bytes copies O(log n) times. A small object’s room is its size class (block_room).
  • Inside an arena, a full buffer that is the arena’s last object, with room left in its 1 MB chunk, grows where it is: the arena’s next-object address moves past it (arena_grow). Nothing is copied and nothing is left behind. This also holds for a buffer another list shares, when no list has used the slots past its end, since its elements don’t move. Any other full buffer is copied into one twice the size, and in an arena the old one stays until the arena is freed.
  • A small value is a tuple, record or sum whose fields (and tag, for a sum) fit in 4 words. A function returning one gives { ptr, words } in registers: null and the words when it built the value in result position (on its stack), else the block it already held. The caller keeps the words in a block on its stack when the value can’t outlive the statement or the variable (x := f() not escaping, (a, b) := f(), match f(), f().x, f()?, f() or d, an argument not kept), and boxes them anywhere else, with one allocation. The stack block’s fields are dropped once, when what holds it ends: the variable, or the temporary for the statement. p = f(p) writes the words into p’s block when nothing else holds it. A loop calling such a function allocates nothing.
  • An update in place (x.f = v, mut xs.push(x), mut d.insert(k, v), xs[i] = v, mut xs.pop()) tests whether its value is held once, and copies it otherwise. compiler/unique proves the test true where it can, before codegen compiles the functions, and codegen then leaves the test out (held_test).
    • A variable is held once when its value is new: a constructor with fields, a list literal with a value made at run time (or [] where a list is wanted), a set or dict literal with elements, or a call of a function whose result is new. Assigning a field also leaves its variable held once, since the record is changed in place or copied.
    • It stays held once while it is only read: a field read, a comparison, an element read (len, get, contains, xs[i]), or a parameter the callee doesn’t keep (kept_by). Any other use ends it, such as a copy into another variable, a list, a record or a closure, or a for over it. So does a borrow followed by a later operand that mentions the variable, since the call holds the value meanwhile.
    • mut xs.push(x) and mut xs.pop() on a list keep it held once, and so do insert and remove on a dict or set. A dict’s insert makes it held once even when it was shared, since its copy is a table of its own.
    • A mut parameter is held once inside its function when every call passes one held once, and a callee gives it back held once when it holds at each of its returns. A field passed mut is put back after the call, which leaves its record held once. These per-function facts, and whether a function’s result is new, are found together as a greatest fixed point: each starts true and turns false where a body breaks it, until nothing changes. A loop’s state is found the same way, walking its body until the state at its head stops shrinking.
    • A mut parameter is assumed held once only in a program’s build, where every call is in the program. Even there, methods taking mut self, the methods of traits, functions used as values and the prelude’s functions get nothing on entry. Verify’s fuzzing, strata run f and compile-time code skip the analysis.
    • Codegen looks a site up by its function and its statement’s text. A text that occurs more than once in a function is proven only when every occurrence is.
    • A proven test costs a load of strata_slow_counts and a branch. Where counts go through the runtime (in check mode, and while tasks run), the test still runs, and in check mode a value found shared stops the program (memory: an update in place proven to find its value held once found it shared, in FUNCTION: CODE), so the tests of strata build catch a wrong proof. A push proven owned still checks the open arena (list_arena_pushable).
    • On strata check of the compiler package, 234 of the 347 unique sites that always found their value held once are proven, which is 23.6M of 27.0M tests. 309 of the 447 such owned sites are proven, which is 18.2M of 26.0M tests. No proven site found its value shared. A loop of 3 million calls updating a record through a mut parameter, plus 3 million pushes and a dict built in a loop, runs 15% fewer instructions (2.82G to 2.38G). strata check of the compiler package itself barely changes (80.3G to 79.6G instructions).
  • With STRATA_MEMORY set, a compiled program reports how many objects it allocated and freed when it exits (memory: 128 allocated, 128 freed, 0 live). With STRATA_MEMORY=check, it also keeps freed memory aside, stops on any use of a freed object (memory: drop of a freed object), and lists the objects still alive at exit. The tests of strata build run every program this way.
  • strata build --memory-sites (and strata run --memory-sites) builds a program that counts its memory operations by site. A site is one place in the generated IR that does one of these: allocates a block (alloc), puts a block on the stack (stack), adds a holder (dup), drops one (release: a call to a type’s drop: helper, or a release written out), tests whether a value is held once before an update in place (unique, owned), extends a list (push) or a string (append), opens an arena (arena), or calls a runtime function that may allocate (runtime, whose second counter is the objects made during the call).
    • codegen marks each statement in the IR it writes, then numbers the sites in one pass over the finished IR (counted_sites). Each site gets two counters in an array the runtime allocates (strata_site_counts), and each operation adds to them with an atomic add, so the counts are exact while tasks run.
    • The second counter says how it went: for alloc, the blocks made in an arena; for unique and owned, the tests that found the value held once (the others copied it). A test that compiler/unique proved still runs in this mode, counted as unique.p or owned.p, so the proofs can be compared with what the program does; for push and append, the extensions done in place (the others made a new buffer, because the value was shared or full).
    • Each site records its function, its statement’s location (DEF@HASH/PATH, for the program’s own code) and the statement’s code. std is compiled with the program in this mode, so its sites are counted too. The functions of core.rt and runtime.c are not: the objects they allocate are reported as one number, the objects made less the heap blocks the sites made.
    • When the program ends it prints, on stderr, the totals by kind and the 20 sites counted most. With STRATA_MEMORY_SITES=FILE it also writes every site to FILE, most counted first, one line each: the two counts, kind, function, location and code, separated by tabs.
    • The mode costs nothing when it is off: without the flag, the IR is unchanged. With it, strata check of the compiler package runs 8% more instructions and about twice the cycles, from the atomic adds on counters that the worker threads share.
  • With --memory-sites and STRATA_MEMORY_LIVE, core.rt counts the heap’s live objects by site (strata_live_start). Before each allocation and each call of the runtime, the compiled code sets the thread’s site (strata_site_set, a word of core.rt’s heap). strata_alloc records it: in a U32 per 16 bytes of the small objects’ region (reserved address space, paged in as used), or in a hash table for a large object, under a lock. strata_free reads it back. Each site’s live objects and bytes change by atomic adds. When the live bytes pass the last peak by 2% (and 1 MB), the counts are copied as the peak’s, about 270 copies for a 500 MB peak. When the variable isn’t set, an allocation and a free each cost a load and a branch.
  • With --memory-sites, the program also reports where each value would be allocated if each scope had a region of its own (compiler/roots; the design is in IDEAS.md, “Memory: scoped allocation from roots”). Nothing else changes: the program allocates and counts as without the flag.
    • A scope is a function’s body, a block, a loop’s body or a statement. roots.verdicts builds a flow graph for each function. A node is a variable, a value an expression makes, or a fixed place: a statement’s temporaries, the function’s result, a parameter, or a reason to stay counted. An edge from s to d says d may hold what s holds. A node’s home is the outermost scope among the homes of the nodes it reaches, found as a fixed point.
    • A value stays counted when it is replaced or shrunk in a loop below its variable’s scope, updated there without a proof that it is held once, stored into or added to a mut parameter, sent to another task, returned by a closure that captured it, or kept by a function that may send it.
    • An expression’s verdict is keyed by its function, the hash of its statement’s text, the hash of its own text, and how many times before the statement had that text (roots.text_key). Codegen looks each expression up the same way as it compiles it (root_code) and marks the IR around it (; root.push CODE, ; root.pop). A variable’s verdict is keyed by its name and the statement that declared it. Codegen marks its drop (; root.drop CODE), and an assignment’s or a mut loan’s releases (; root.stmt CODE).
    • counted_sites adds each allocation, each call of the runtime that may allocate (with strata_memory_allocated read before and after it) and each release to its code’s totals: the first 3 × 15 counters (roots_table). A function’s result takes its caller’s code at run time. Each call stores its code in the thread’s word (strata_roots_state), and each of the program’s functions and helpers reads it on entry. A release in the program’s functions also adds the releases that helpers (drop:, unbox:) made during it, counted in the thread’s second word.
    • The report follows the sites (docs/tools-reference.md). Each site’s line in STRATA_MEMORY_SITES ends with its root: a code’s name, or result for a function’s result.
    • Cost, in this mode only: the analysis is one walk of each function and a fixed point over its edges; every expression that may allocate is printed once more; each call adds two loads and two stores, each runtime call two calls, and each function a call on entry.

Verify. strata verify runs only compiled code. --jit explains why a function’s fuzzer couldn’t be compiled; that function is then skipped.

  • Fuzzing compiles one module with a driver per function. The driver generates the function’s arguments (with the same generators mock uses), records them for a counterexample, and calls the function.
  • An implementation’s trait method, and a law, are fuzzed through a wrapper function. For a law, the wrapper ensures it holds.
  • Loops and calls count steps, so a runaway case ends with a Limit fault (too many steps).
  • The solver’s counterexamples are confirmed by running them compiled: a probe binds the values to the parameters’ types, then calls the function. Literal arguments that break a refinement (attr("onclick", …)) are confirmed the same way and reported as errors before anything runs.
  • Probes, like compile-time code, are compiled without optimization, since they run once.

Test. strata test compiles tests the same way. Each test block is a function, a fault ends the test instead of the process, and what a test prints is kept for the report (strata test --emit-llvm prints the tests’ IR). A test that can’t be compiled fails with the reason, and the others still run. Only the project’s own tests run, those in its files (the package’s, or the script’s). Imported code (std, and dependencies once fetched) is compiled, verified and tested separately (std with strata --file std test), so its tests aren’t run again. strata test --with-deps runs them too.

Run. strata run compiles the same IR in memory with LLVM’s libraries and runs it in the compiler’s own JIT, with std’s precompiled library and any [native] C of the package loaded. A program therefore runs at native speed without a build step (fib(32): 26 ms, compilation included). Code that can’t be compiled is an error that says why, since there is no interpreter.

  • strata run f [ARGS] calls one function, compiled. Its arguments, written as code ('"abc", 3'), go into a wrapper function that calls it and is checked with the program. The result is printed as code; the compiled call returns its debug text.
  • --trace makes compiled code print each call and return.

Compile-time code runs on the JIT too: in a derive, and comptime e anywhere else. Its value is computed during compilation and embedded in the program as a constant, so re := comptime parse("[a-z]+") never calls parse at run time. e may use definitions but not the surrounding variables. compiler/codegen compiles comptime e, and the compiler’s own JIT runs it in-process, within 5,000,000 steps. Its value is read back from memory according to its type (codegen’s read_back, core.values) and embedded with that type. Code that codegen can’t compile, and the small pieces of a derive’s code, run on compiler/eval.

Swapping in proven code (compiler/c/jit.c). A strata run with a verifier alongside compiles the program so that functions can be swapped.

  • The verifier runs as a separate process (strata verify-alongside): verify --quiet, then, if it proved something new while the run continues, a recompile of the program without those checks, written to its folder under the cache’s alongside/.
  • In the running program, each of the program’s own functions (strata:NAME, except main) is renamed NAME.checked. NAME becomes a stub that atomically loads the slot NAME.slot and tail-calls what it holds. The module’s private globals are made visible.
  • When the verifier finishes, a thread in the run reads the new module. A function whose printed code matches the first compilation is declared, reusing the main module’s copy, and so is every global and helper the main module defines. A changed function is compiled as NAME.proven.N. Once all are compiled, each slot is pointed at its new body with one atomic store.
  • A call already running the checked body finishes in it. A task on another thread runs one body or the other, never a mix.
  • The end of the run waits for a swap in progress (none starts after it), then reports how verifying went.
  • With fib(37) making 78M calls through the stub, and the verifier done before main starts, there was no difference above the noise of a loaded machine: at -O0, 910 ms against 912 ms; with --release, 490 ms against 555 ms (medians of 6, load 15–25).
  • A run without a verifier, and every built executable, have no stubs.

Live edits (strata run --live, compiler/c/jit.c). The program is compiled swappable, as with a verifier alongside, and the run starts strata live-edits, a process of its own.

  • It reads the program’s module files every 100 ms (verified_key: their bytes). A change, the same bytes twice 30 ms apart, is an edit. Its definitions’ headers (live_snapshot: hashes only, nothing decoded) are compared with those running (live_changes): only functions and impls whose interface hash is unchanged, other than main, may change.
  • Each edit is checked, verified and compiled by strata live-edit, a new process each time, so nothing of an earlier edit’s is left in it. It writes the module to the run’s folder (live-N.ll).
  • The run and each edit are compiled with --live (codegen’s Gen.live): no function’s code depends on another’s body, since swapped and running code mix. Parameters are all taken as kept (kept_by is not used: no argument on the stack), static uniqueness (compiler/unique, whose summaries are over callers and callees) is off, and entry checks proven at every call stay.
  • The watcher tells the run on a pipe (its descriptor 3): swap N T or refused N, with a note in a file. A thread of the run swaps the module in. A function changed since the program started, or swapped before, is compiled as NAME.live.N and its slot pointed at it. A function whose type changed is refused (the slot’s callers were compiled for the old one). In the edit’s module, a definition the main module has with the same code is declared, so it is shared. A changed one becomes the module’s own internal copy, and so does a constant whose value changed (live_own). So does one that refers to a copy not called through a slot, until nothing changes: a function making a closure of a changed lambda is swapped, though its own code is the same. A function the main module calls directly (not a slot, not a lambda) that changed refuses the edit. A variable is always the main module’s, so its state is kept. The run answers in done-N.txt, so the watcher knows which code runs.

build and the JIT share one code generator (IR text, which compiler/c/ir.c builds in LLVM for the JIT too) and one runtime (runtime/runtime.c, linked into strata for the JIT and into the program by strata build). A release ships the runtime precompiled together with core.rt as runtime-lto.o.

The strata command is the compiler/ package. It is an ordinary package whose modules are named by their paths (lex, parse, …). It is a program, not a library, and not part of std, so programs don’t import it. tools/bootstrap.sh builds it with an earlier strata (a release, or STRATA_SEED), then with itself, until the build reaches a fixed point (target/strata).

Its main dispatches the command line, which compiler/driver parses. It can also run single front-end steps on files (strata --file compiler run -- lex FILE, parse, stored, check, eval, codegen, jit, object, link, …; see compiler/main.strata). The tests use these step names.

Module Contents
ast Strata’s syntax tree as Strata types (Decl, DeclKind, TypeExpr, Expr, Stmt, Pattern, …)
binary reading and writing .strata files: read(bytes) (a module file or a bundle), read_header, decode_module (which checks each definition’s hash), decode_definition, encode_definition (a definition’s bytes, exactly as strata writes them), hash, interface_hash, code_hash, and without_notes (in ast). Its SHA-256 is private: it names definitions, and std gets no public hash function until one has been reviewed as cryptography
store the codebase as the tools keep it. graph(decls) gives each definition’s dependencies within the package, as qualified names, matching a module file’s header: a method call (x.m(), or T.m(x), operators as their methods) depends on its trait and on every impl with a method m, a variant on its type, and a definition on its bounds and its refinements’ predicates. Core’s files list none. refs(d) lists what one definition mentions. With binary.encode_module(decls, module, deps) (and encode_parts), it writes a module file byte for byte as strata does. compiler store-check FILE... checks a package’s files
codebase the codebase commands (compiler init, log, edit, add, status, done, abort, rename, move, view, interface, header, holes, pack, diff, merge-file, resolve, setup-git, sync, upgrade): changes (what changed, with hashes and dependents), merge (edits stored into the package), write_modules, log_line (strata.log’s JSON), find_root, init, parse_log, log_text. compiler/main runs them. edit reads from standard input, from $EDITOR (at a terminal, or with --editor), or from a file (add), and --file targets a script or a folder outside any log. A package is checked as compiler check checks it, and an edit that breaks code elsewhere opens a pending change
pending a change in progress: holeify (each broken use becomes a hole ?pending_N, and match arms are fixed after a variant change), keep_holes, hole_names, and reading and writing .strata/pending.json
diff structural diffs, as strata diff shows them. diff pairs two programs’ definitions by name and through recorded renames, and describes each change in words (a variant added, a stronger guarantee, a method added). It shows the code with changes marked in place and the rest folded, the doc as a word diff, and what verification found before and after. log_range replays the log’s patches backwards from the package, using each entry’s texts. git_range lists the commits since a base, each split into the log entries it added, then the working tree, reading old revisions through a separate git index. range_text
views view’s levels (select, view: a map, interfaces, source) and separate_members (view --members separate)
merge merge-file, definition by definition, following renames. merge does a line merge for a definition both sides changed, with conflict markers when it can’t. follow_rename is what sync does with a rename either side logged: every reference renamed, in any module
refactor rename and move on the stored form, where every reference is qualified. member, owner, rename_all (definitions, variants, trait methods, and fields when no other record has the name), and move_def (imports added where code uses the short name, private definitions kept in reach, and a function named like a builtin kept in the root module)
text the printer: code as text, laid out to stay within 80 columns. module_text(decls), decl_text, fn_decl_text, type_decl_text, expr_text(e, depth), type_text, pattern_text, block_text, escape. It prints a tree as given. strata view first converts a stored tree to its written form, shortening names as the imports allow, which needs name resolution
lex the lexer. lex(text) returns the tokens (Token { tok, line, col, nl_before, space_before }, where tok is an IntTok, StrTok, FStrTok, Ident, Sym, …, then Eof) and the // comments, or an error (1:9: unterminated string). token_text and comment_text print them as strata lex FILE does
parse the parser. parse_module(text, module) and parse_program(text) return the definitions with comments in place, or an error (3:5: expected `)` (found `,`)). Also parse_expr(text). The tree is as written; storing it (strata edit) qualifies its references, which needs name resolution
resolve name resolution. stored(decls, std) turns a parsed program (a script, or a package’s modules together) into its stored form, with every reference to a definition by its qualified name and locals and methods as written, and std’s definitions in scope. written(decls, std) gives the written form view shows: each reference as short as the imports allow, a union written out by name, and a type listed by one union shown inside it. union_members decides a union’s bare members. errors(decls, std) returns the resolver’s errors: a use of something missing or private, a private name, std’s host builtins outside std, a mock outside tests, an extern called from another module
desugar turns syntax sugar into calls. desugar(decls) rewrites a..b as range, xs[i] as at, slices as slice, comprehensions as map, filter and fold, and Dict { .. } and Set { .. } as dict and set. Where a local, a function of the module or an imported name has one of those names, the call is by $core:at (ast.core_ref), which no program can write, so it still means the built-in; check, codegen, verify and eval read $core: names as the built-ins. It fills in record defaults, turns refinements written as type arguments into aliases ($where_0), and splits unions that have members of both kinds (Shape$own). It reports errors such as a range missing an end outside a slice. check and eval work on its result
walk rebuilding a tree one level at a time (expr_children, type_children, decl_parts) and collecting what it contains (kids, decl_exprs, decl_types, any_expr), for the passes that rewrite programs
check the type checker. definition_errors (a name defined twice, or clashing with the prelude; two impl Type blocks; a trait implemented twice), variant_errors, mixed_unions (a union whose members of both kinds are split as the checker splits them), expression_errors (unknown variables, wrong argument counts) and type_errors (inference for Int, Float, Bool, String, (), lists and the program’s functions), each worded as strata check words it. spreads_resolved expands each record-spreading call (f(...x) into f(x.a, x.b), by parameter name, inferring the receiver’s and values’ types) right after derive, in check, expanded (what is compiled), verify’s program and holes, so other passes see ordinary calls
eval runs a program from its stored trees. run(decls, args) returns a Run (stdout, stderr, code) matching what the compiled program prints and its exit code, faults and their messages included. It resolves methods from the receiver’s run-time type, gives main the console and the process, and knows what a function’s type parameters stand for while it runs (T.zero(), Self.check(x), T.from_json(j)). It learns them from the argument values, from the receiver’s impl, and from the types check.instantiated writes around generic calls ({ $result: T := call; $result }, the type the caller wants). strata pack --prelude FILE writes the prelude’s definitions that programs run with. world(decls) and value_in(w, module, e) evaluate one expression, which derive uses for compile-time code. Not supported: files, mocks, extern
derive derived traits and comptime. expand(decls) replaces each derive Trait for Type with its impl. The type is described as a std.typing.Type value and checked against the trait’s kind and requirements. Each derived fn is specialized: comptime e is evaluated by eval and embedded, comptime for and match comprehensions are written out, match comptime keeps the arm that fits, make and try_make build a value field by field, and calls to functions with comptime parameters become copies. It also folds every other comptime e into its value. Errors include reaching compile_error(..) and a kind that doesn’t fit. setting(..) returns None, since strata.toml isn’t read there
parallel spreads the compiler’s work over every core. map(xs, f) computes xs.map(f), sharing the elements among STRATA_JOBS threads (default: the number of cores; STRATA_JOBS=1 uses only the main thread). Each thread takes the next element when it finishes one, and results are put back in order, so the output doesn’t depend on scheduling. check infers each definition’s body this way. codegen compiles its queue of instances in rounds: each instance alone, reading only the state from the start of the round, with its additions kept in new_... tables and merged in queue order, so a global or helper made twice is kept once. Generated names start with their owner’s symbol (lambda.<owner>N), and string constants are named by a hash of their bytes. main decodes the module files a command reads this way, and verify encodes each function this way, with --jobs N threads and as many solver processes (default: STRATA_JOBS, else the cores, at most 4: past 4 the wall time hardly falls and CPU time rises). While the threads run, objects that existed before they started and that they share are kept permanently (strata_memory_keep_shared, above); what they allocate is counted as usual