The Strata language
This is the specification of the rebuild. The language you can install today is the prototype, described in the docs; About says how the two relate.
This document specifies the Strata language as the rebuild implements it. Each section states the rules exactly; nothing is left to convention. Where a rule is a law, it is written as a law.
What binds. Every rule binds a first implementation, except what is marked: to try in the lab is a proposal, not required until a trial keeps it; built late is required, after the rest. open marks a question not yet decided, which binds nothing. The lab's history, its measurements and the trials behind each rule are in REBUILD.md, not here.
Notation. Code examples follow section 2's syntax, and functions they call with unnamed arguments (the helpers laws use, such as lex(s) or in_scope(d, b, u)) are taken to declare _ parameters. Grammars are EBNF: = defines, | separates choices, [ x ] is optional, { x } repeats zero or more times, "x" is literal text, 'a'..'z' is a range of characters, and - removes a set (any - "\""). A rule is followed by an example. Helpers an example calls but doesn't define (fetch, save, show, respond) are taken to be declared elsewhere with whatever capabilities they need; the example leaves those out to keep to its point.
0. Overview
Strata is a language for programs that are proven correct where they can be and checked where they can't, written by people and coding agents together.
- Code is a tree, not text. Each module is stored as a typed tree with stable ids. Text is a view, printed under each reader's settings, and
strata editis the one way code changes. A rename changes one name; hashes, proofs and compiled code are untouched. - Contracts are proven. Refinements,
requires,ensuresand laws are obligations, proven by a ladder (a static pass, then Z3, then a small kernel for written proofs). What is proven runs with no check; what isn't is checked when it runs. - Effects are capabilities. Files, the network, the console and the clock are values a function is given. A function given none is pure, and tests give mocks.
- Values never change. Memory is counted, never by two threads; tasks are structured and run on one thread each; channels have a duty to close.
- Libraries from elsewhere (C, Rust, Python, TypeScript) are read into typed bindings.
It is not a scripting language with optional types, and it has no garbage collector, no exceptions, no null and no global state.
use std.io.{Console, IoError}
use std.fs.Files
use std.process.Process
/// Counts the lines of each file named on the command line.
fn main(cap console: Console, cap files: Files, cap process: Process) -> Result[(), IoError] {
for path in process.arguments() {
text := files.read(path)!
console.print(f"{path}: {text.lines().len()} lines")
}
}
fn mean(_xs: NonEmpty[f64]) -> f64 {
_xs.fold(0.0, (sum, x) -> sum + x) / f64(_xs.len())
}
main takes the capabilities it uses; its loop gives (), which R2 makes Ok(()); ! passes a read error on, and main's Err ends the program with exit code 1. mean is pure, and its NonEmpty refinement is what makes the division safe: a caller must prove its list isn't empty.
1. Lexical structure
The lexer turns a module's text into a list of tokens. The parser (section 2) reads the tokens. Tokens are never stored: the stored form of a module is its tree (section 3), and text exists only to be read and edited.
1.1 Source text
- A source text is a sequence of bytes that must be valid UTF-8. Invalid UTF-8 is an error at the first byte that is not part of a valid sequence.
- A byte order mark (U+FEFF) at the very start is skipped. Anywhere else it is an error, inside strings too: a string holding U+FEFF is written
"\u{FEFF}", and the printer writes it so. - Each CR LF pair is read as one LF. A CR not followed by LF is an error.
- Outside string literals and comments, the only characters allowed are printable ASCII (U+0020 to U+007E), tab (U+0009) and LF (U+000A). Any other character there is an error.
- Inside comments, any character but LF is allowed. Inside string literals, section 1.6 says which characters are allowed.
- A position is a byte offset into the text. Messages show it as
line:column, both counted from 1, the column in code points.
1.2 Tokens
token = identifier | keyword | wildcard | hole
| integer | decimal | string | raw_string | f_string
| module_doc | doc_comment | comment
| punctuation | newline ;
space = " " | "\t" ;
- The lexer reads from left to right. At each point it skips spaces and tabs, then reads the longest token that starts there.
- Each token records its kind, its value, its position, and
space_before: true when a space, a tab, an LF or a comment comes directly before it, or when it is the first token. - After the last token comes
end. - The lexer is total. It returns the whole list of tokens, or the first error with its position. It never skips a character it cannot read.
1.3 Identifiers and keywords
identifier = ( letter | "_" ) { letter | digit | "_" } - keyword - "_" ;
letter = 'a'..'z' | 'A'..'Z' ;
digit = '0'..'9' ;
wildcard = "_" ;
Example: total, Point, _x, s12, u3.
- Identifiers are ASCII only. Case has no lexical meaning; section 5 states the naming conventions.
_alone is the wildcard token, not an identifier. A leading_is part of a name:_xis an identifier, and section 2 gives it a meaning on parameters (a parameter named_xis passed without its name).- A letter, digit or
_directly after an identifier is part of it. Sox1is one identifier.
The keywords are reserved: none of them can be an identifier anywhere, including as a field name after ..
| group | keywords |
|---|---|
| definitions | fn type distinct trait impl test law lemma extern pub use as mock derive with blocking pure ghost |
| bindings | let mut cap comptime move |
| control | if else match while for in loop return break continue assert dbg except or |
| values | true false is self Self it old |
| tasks | spawn scope await select race supervised |
| memory | arena frozen |
| contracts | requires ensures holds invariant decreases where assumed by |
| proof steps | assume calc simplify once unfold witness arithmetic nonlinear bits compute auto |
The groups are only for reading; every keyword is reserved alike, arena and frozen included (section 10 makes them blocks; std has no function of either name). self, Self and it are keywords read as expressions: they can't be names. debug is no keyword: it is the method of core's Debug trait, x.debug(), while the statement is dbg e.
The proof steps are section 8.4's.
The names of built-in types and core's collections (Int, Natural, Real, Bool, String, List, Dict, Set, Option, Result, s1 … s128, u1 … u128, f16, f32, f64, bf16) are identifiers, not keywords. Core declares them, and no binder or definition may take one: core gives way for its other names (section 5.3), never for these. So Set { a, b } and Dict { k: v } are always the collections' literals, never a record of a type of that name.
1.4 Holes
hole = "?" identifier ;
Example: ?body, ?conflict_1.
- A
?followed directly by a letter or_starts a hole, and the hole takes the longest identifier that follows. Any other?is punctuation.
1.5 Number literals
integer = decimal_digits | "0x" hex_digits | "0b" binary_digits ;
decimal_digits = "0" | '1'..'9' { [ "_" ] digit } ;
hex_digits = hex_digit { [ "_" ] hex_digit } ;
hex_digit = digit | 'a'..'f' | 'A'..'F' ;
binary_digits = binary_digit { [ "_" ] binary_digit } ;
binary_digit = "0" | "1" ;
decimal = decimal_digits "." digit { [ "_" ] digit } [ exponent ]
| decimal_digits exponent ;
exponent = ( "e" | "E" ) [ "+" | "-" ] digit { digit } ;
Examples: 0, 1_000, 0xff, 0b1010, 1.5, 0.000_1, 6.02e23, 1e-3.
- An integer literal's value is a natural number of any size. A decimal literal's value is the exact rational number its digits write. Neither has a type of its own: section 6 gives each literal its type from where it is used. Section 6 also says when a decimal literal is a
Real(exact) or a float (the nearest float, ties to even). _stands only between two digits. A leading zero followed by another digit (007) is an error.- A letter, digit or
_directly after a literal is an error (12abc,0xfg,1_,5u8). There are no suffixes: a literal's type comes from its context or from(e: T). - A literal has no sign.
-1is the operator-applied to1(section 2 gives its stored form). - After the punctuation
., a number is read as an integer only, with no fraction and no exponent. Sopair.0.1ispair,.,0,.,1. 1.and.5are not decimal literals: both sides of the.need digits.1..nis1,..,n.
1.6 String literals
string = "\"" { string_char | escape } "\"" ;
string_char = any code point - "\"" - "\\" - control ;
control = U+0000..U+001F | U+007F ;
escape = "\\n" | "\\t" | "\\r" | "\\0" | "\\\\" | "\\\"" | "\\{" | "\\}"
| "\\u{" hex_digit { hex_digit } "}" ;
raw_string = "r\"" { any code point - "\"" - control } "\"" ;
Examples: "total: 3\n", "tab\there", "\u{e9}", r"\d+\.\d+".
- A string literal's value is a sequence of Unicode scalar values, as UTF-8 bytes.
- The escapes stand for: LF, tab, CR, U+0000,
\,",{,}, and the code point with that hexadecimal number.\u{…}takes 1 to 6 hex digits, and its value must be a scalar value (at most U+10FFFF and not a surrogate, U+D800 to U+DFFF). - Any other character after
\is an error. - A string can't hold a raw control character, LF included. Write it as an escape.
- A raw string has no escapes. Its value is exactly the characters between its quotes, so it can't hold a
"or a control character. - Where a token starts,
r"starts a raw string andf"an f-string. So a variablerorffollowed by a string needs a space between them. Inside a longer identifier (for"x") the identifier is read first. \{and\}mean{and}in plain strings too, so text can move between a string and an f-string unchanged.- Which form the printer writes (plain or raw) is a notation setting (section 2).
1.7 f-strings
f_string = "f\"" { string_char - "{" - "}" | escape | interpolation } "\"" ;
interpolation = "{" tokens "}" ;
Example: f"{name} has {len(xs)} items", f"\{literal braces\}".
- The text parts follow the rules of plain strings, escapes included. A
{or}in the text is written\{or\}. A raw}in the text is an error. - An interpolation holds the tokens of one expression, read by the rules of this section. Its end is the
}that matches its{: the lexer counts{and}tokens, and braces inside string tokens don't count. - An interpolation can hold strings and f-strings. It can't hold an LF, a comment or an empty expression (
{}is an error). {{is an error: an interpolation can't start with a block. So text written for older rules, where{{x}}meant literal braces, never silently changes meaning. A block is written{ {…} }or{({…})}, and since an interpolation holds no LF, only a block on one line can be interpolated.- There are no format specs. A
:in an interpolation is part of the expression:f"{(n: u8)}"is the expression(n: u8). - The token's value is a list of parts, each a text or a list of tokens. Section 2 gives its stored form, the concatenation of each part's
Displaytext.
1.8 Comments and doc comments
module_doc = "//!" { any code point - LF } ;
doc_comment = "///" { any code point - LF } ; (* the fourth character is not "/" *)
comment = "//" { any code point - LF } ; (* neither of the above *)
Example:
//! Totals of orders, per customer.
/// The sum of a customer's orders, in cents.
fn total(orders: List[Order]) -> s64 {
// Kahan summation would go here if amounts were floats.
…
}
- Every comment runs to the end of its line. There are no block comments.
- A comment's text is what follows
//!,///or//, with one leading space removed if there is one, and trailing spaces and tabs removed.////starts a plain comment. //!lines are the module's doc. They may come only before the module's first token that isn't a comment. A//!anywhere else is an error.///lines are the doc of the definition, field, member or method that follows them. Section 2 says where one may stand. A///anywhere else is an error.- All three are tokens, kept in order in the lexer's list. The parser keeps plain comments aside, at their place, and section 3 says where each is stored in the tree. A comment also counts as space for
space_before.
1.9 Punctuation
punctuation = "<=>" | "==>" | "..." | "..=" | ".." | "|>" | "**" | "<<" | ">>"
| ":=" | "->" | "=>" | "==" | "!=" | "<=" | ">=" | "&&" | "||"
| "+=" | "-=" | "*=" | "/=" | "%="
| "(" | ")" | "[" | "]" | "{" | "}" | "," | ":" | "." | "="
| "<" | ">" | "+" | "-" | "*" | "/" | "%" | "!" | "?" | "|" | "&" | "^" ;
- The longest match wins:
a!=bisa,!=,b, andx..=yisx,..=,y. ..=is a range only...is a range (a..b, a slice with an open endxs[..b]), the rest of an open record type ({ x: f64, .. }) and a rest pattern ([x, ..rest],P { a, .. }). Which one is decided by where it stands, never by types.**is the power operator:a ** bisPow.pow(a, b), andx**2isx,**,2(section 2 gives its precedence).|>is the pipe:a |> fis the callf(a)(section 2)....is the spread: it puts a record's fields where fields are expected, in a call (f(a, ...p)) or in a record literal (T { ...r, f: v }, a record update).$,;,@,#,~,`,'and\outside a string are errors. No program can write a generated name. The tree tells generated nodes apart by their node ids and core forms (section 3).
1.10 Newlines
Each LF is a newline token. Plain comments (//) take no part in layout: the rules below and the grammar of section 2 read the tokens with plain comments set aside, and there two or more newline tokens in a row count as one. Indentation never matters. Braces delimit blocks.
A newline ends a statement unless the lexer drops it. It drops a newline when any of these holds:
- The innermost bracket open at that point is
(or[. - The token before the newline is
{,,, or a continuing operator. - The token after the newline is
},),],., a continuing operator other than-, or a continuing keyword.
The continuing operators are <=> ==> |> ** << >> := -> => == != <= >= && || += -= *= /= %= : = < > + - * / % | & ^. .. and ..= don't continue a line, since a range may end open (xs[2..]).
The continuing keywords are else or except with where requires ensures holds decreases invariant by as. A line ending in derive Tr for also continues: the definition it derives for follows on the next line.
- A line that begins with
-starts a new statement, because-xcan begin one. To continue a sum onto the next line, end the line with the operator:total +then-x. - A line that begins with
!or?starts a new statement.
Examples:
total := price
* quantity // continues: the line starts with `*`
ok := a &&
b // continues: the line ends with `&&`
xs.map(f)
.sum() // continues: the line starts with `.`
print(t, view)
|> parse
|> desugar // continues: the lines start with `|>`
f(a,
b) // dropped: inside `(`
print(x)
(y) // two statements: the newline is kept
Calls and indexing need their bracket to touch the token before it. The parser (section 2) reads ( or [ as a call, type arguments or an index only when its space_before is false. So f (x) and f followed by (x) on the next line are not calls.
1.11 Laws
Two tokens are equal when their kinds, values and space_before are equal. Positions are not compared.
The lexer and the token printer render are tied by a law, proven on their code:
law lex_render(ts: Tokens where lexable(it)) holds lex(render(ts)) == Ok(ts)
lexable(ts)holds for every token list thatlexcan return. So for any textsthat lexes,lex(s)! |> render |> lex == lex(s).renderwrites each token in one canonical form:- an integer in decimal, without
_; - a decimal literal as the shortest text the
decimalrule accepts for its value, with a lowercaseeand no+; on a tie, the text without an exponent; - a string with
\",\\, control characters and U+FEFF escaped (\n,\t,\r,\0, else\u{…}in lowercase hex), and every other character as itself; - a raw string as it was written;
- a comment as
//,///or//!, then a space and its text when the text isn't empty; - a newline as one LF.
- an integer in decimal, without
- Between two tokens,
renderwrites one space when the second'sspace_beforeis true, or when the two would otherwise read as one token. - This law is about tokens only. Section 2 states the round-trip law of the parser and printer on trees.
Further laws, sketched. Each is proven on the lexer's code.
// tokens come in the order of the text, and never overlap
law tokens_in_order(s: String where lex(it) is Ok, i: u32)
requires i + 1 < len(lex(s)!)
holds end_of(lex(s)![i]) <= start_of(lex(s)![i + 1])
// an identifier is never a keyword
law identifiers_are_not_keywords(t: Token where it is Identifier)
holds !is_keyword(t.text)
// a string's value survives rendering
law strings_round_trip(v: String)
holds string_value(render_string(v)) == v
// a number literal's value survives rendering
law numbers_round_trip(n: LiteralValue)
holds literal_value(render_number(n)) == n
// the layout rules only ever drop newlines
law layout_drops_only_newlines(ts: Tokens)
holds without_newlines(layout(ts)) == without_newlines(ts)
// lexing never fails on what the printer wrote
law printed_text_lexes(t: Module, view: Settings)
holds lex(print(t, view)) is Ok
1.12 Errors
The lexer reports the first of these, at its position:
| error | example |
|---|---|
| invalid UTF-8 | a lone byte 0xFF |
| byte order mark not at the start | |
| CR not followed by LF | |
| a character not allowed outside strings and comments | é, $, ;, a control character |
| a malformed number | 007, 1_, 0x, 12abc, 5u8 |
| an unknown escape | "\d" |
an escape \u{…} out of range or a surrogate | "\u{d800}" |
| a control character in a string | an LF inside "…" |
| a string not closed on its line | "abc |
} alone in an f-string's text | f"a}b" |
| an empty or unclosed interpolation | f"{}", f"{x" |
{{ in an f-string | f"{{x}}" |
//! after the first token |
2. Syntax
The parser reads the tokens of section 1 into a tree of section 3. This section gives the grammar, each sugar with the core form it is stored as, and how the printer writes a tree back.
2.1 The pipeline
parse gives a tree of core nodes, with Inferred where a type was left out (section 3.7). desugar turns each sugar into its core form, by syntax alone. elaborate checks the tree (section 6), fills in what inference gives (types, constructors, call targets) and stores it. print writes a stored tree as text, under a reader's settings.
- Parsing only ever turns sugar into core. A hand-written
matchis stored as amatch, even when it is written like a handler. - Choosing sugar is the printer's: it writes a sugar, or leaves out a type or a constructor, only where reading the text back gives the same tree.
- A type or a constructor left out is inference, not sugar.
- No parse depends on types. Where a form could mean two things, the grammar decides by its tokens alone. What names and types settle is
elaborate's, after parsing, and the parsed tree keeps the form as written until then: the constructors left out (section 6.4), a call's target, a bare argument's pun (section 2.6), a spread...r(which fieldsrgives),x[a, b]as a type application or an index, and which conversion a call names (section 12.4).
2.2 Modules
module = { module_doc } { import } { definition } ;
import = "use" module_path [ "as" identifier ]
| "use" module_path "." "{" imported { "," imported } [ "," ] "}" ;
imported = identifier [ "as" identifier ] ;
module_path = identifier { "." identifier } ;
Every /// line belongs to the definition, field, parameter or member that follows it; any other is an error.
2.3 Definitions
definition = { doc_comment } [ "pub" ] [ derive ] ( function | type_def | trait | impl | test | extern | law | constant ) ;
constant = "let" identifier ":" type "=" ( [ "-" ] literal | "comptime" expression ) ;
derive = "derive" bound { "," bound } "for" ;
function = "fn" identifier [ type_params ] "(" [ params ] ")" [ "->" result ]
{ contract } block ;
type_params = "[" type_param { "," type_param } "]" ;
type_param = identifier [ ":" bound { "+" bound } ] [ "=" type ] ;
params = param_group { "," param_group } [ "," ] ;
param_group = [ "mut" ] "self"
| { doc_comment } [ "mut" | "cap" | "comptime" ] identifier { "," identifier }
":" type [ "=" expression ] ;
result = type | "(" identifier ":" type "," identifier ":" type { "," identifier ":" type } ")" ;
contract = [ "assumed" ] ( "requires" expression | "ensures" expression )
| "decreases" expression { "," expression } ;
type_def = [ "distinct" ] "type" identifier [ type_params ] "=" type_value ;
trait = "trait" identifier [ type_params ] [ ":" bound { "+" bound } ]
"{" { trait_item } "}" ;
trait_item = method | { doc_comment } "ghost" identifier ":" type
| "ensures" expression | { doc_comment } law ;
impl = "impl" [ type_params ] [ type "for" ] type [ "{" { impl_item } "}" ] ;
impl_item = method | "ghost" identifier "=" expression
| "law" identifier "by" proof ;
law = "law" identifier [ type_params ] "(" [ params ] ")"
[ "requires" expression ] "holds" ( expression | block ) [ "by" proof ] ;
proof = step | proof_block ; (section 8.4)
method = { doc_comment } ( function | "fn" identifier [ type_params ] "(" [ params ] ")"
[ "->" result ] { contract } ) ;
test = "test" identifier [ "(" [ params ] ")" ] block ;
extern = "extern" language [ "blocking" ] [ "pure" ] "fn" identifier "(" [ params ] ")"
[ "->" type ] { contract } ;
language = "c" | "rust" | "python" | "ts" ;
Examples:
pub fn clamp(_x, lo, hi: s64) -> s64
requires lo <= hi
ensures lo <= it <= hi {
if _x < lo {
lo
} else if _x > hi {
hi
} else {
_x
}
}
fn divide(_n: s64, divisor: s64 where it != 0) -> (quotient: s64, remainder: s64)
ensures quotient * divisor + remainder == _n {
(_n / divisor, _n % divisor)
}
type Point = { x: f64 = 0.0, pub y: f64 = 0.0 }
type Shape =
| Circle { r: f64 }
| Square(f64)
| Empty
distinct type Meters = f64
derive Json for
type Order = { id: s64, total: Cents }
trait Area {
/// The area, in square units.
fn area(self) -> f64
fn describe(self) -> String {
f"an area of {self.area()}"
}
}
impl Area for Circle {
fn area(self) -> f64 {
3.14159 * self.r * self.r
}
}
impl Summary for Item
/// A clamped value never passes the upper bound.
test clamps_high {
assert clamp(5, lo: 0, hi: 3) == 3
}
extern c blocking fn sqlite3_step(statement: Statement) -> s32
- Grouped parameters.
x, lo, hi: s64is three parameters of types64. ⇒ eachParameterwith its type. - A parameter whose name starts with
_is passed without its name (section 2.6). Every such parameter comes before the others. self, ormut self, is a method's first parameter, with no type: its type is the impl's target, orSelfin a trait.- A parameter is always a name, never a pattern: a tuple is taken whole and taken apart in the body (
(p1, q1) := a), so every parameter has a name to be passed and documented by. - A parameter with
= ehas a default. ⇒Parameter.default. - A function with no
->returns(). - Named results need two or more elements, so
-> (a: s64) -> s64is a function type.-> (quotient: s64, remainder: s64)⇒ aTupleTyperesult whose elements are named inlocal_names. Contracts read them by name; they are stored asit.0,it.1. - A function's body is always a block. A method in a trait may have none (each impl gives it).
- Contracts each take a line of their own after the signature; the body's
{ends the last of them. - Contracts about one value are refinements.
desugarsplits eachrequiresandensuresat its top-level&&. Arequirespart that mentions exactly one parameter becomes that parameter's refinement, and anensurespart that mentions only the result (it, or one named result) becomes the result's refinement:requires divisor != 0⇒divisor: s64 where it != 0,ensures it >= 0⇒-> s64 where it >= 0. A part aboutselfalone becomesself: Self where …. A part that relates two or more terms stays a contract:fn sqrt(_x: Real) -> Real ensures it ** 2 == _xrelates the result and_x;requires lo <= hirelates two parameters. Amutparameter,mut selfincluded, gets no refinement, nor does a parameter of a trait's method: a refinement holds for the variable's whole life, and amutone changes, while a trait's method is a promise each impl keeps; their parts stay contracts. A part that mentions no term is refused as saying nothing about the call. The printer writes the refinement, andeditsays so in a warning that shows the rewritten signature, so whoever wrote the contract (a person or an agent) sees what is stored. Anensuresis a promise about what the function gives back: a part about the result alone refines the result's type, which only narrows it, so a caller may still treat the result as the wider type. Anensurespart that mentions one parameter and not the result stays anensures: it promises something about that parameter, and is never turned into a refinement of it, which would make it a condition on the caller. impl Tr for Twith no methods to give is written with no block.- Constants.
let name: T = valueat the top level,pub letfor a public one, is a constant: nevermut, its type always written. Its value is a literal, orcomptime efor any other expression, evaluated while compiling (section 7.7):let pi: f64 = 3.141592653589793,pub let table: List[u32] = comptime crc_table(). A constant is used like any value, anywhere. - Tests are named like functions. A
///doc comment above one is its description, whichstrata testshows. A test takes capability parameters in parentheses when it needs them (section 6.10), else none. derive Tr forbefore a definition derivesTrfor it: the trait's module providescomptime fn derived(T: Type) -> Impl(section 6.7), whicheditruns and stores the impl it gives, shown as thederiveline. Core derivesOrd; std derivesJson,TomlandCommandLine; any trait may provide one. The impl stores the derive it came from (Impl.derived), and the printer writes thederive Tr forline back above the type instead of the impl.- Ghost state. A trait may declare
ghost name: T, state its implementations represent differently (a ledger's balances), and each impl gives it:ghost name = e. Contracts and laws may read ghost state; code may not. A mock runs its trait's ghost state (section 6.10).ghostis the one keyword for it:modelis an ordinary name. - Trait-level
ensuresstates a rule everymutmethod of the trait keeps, those an impl adds included:ensures len(self.balances) >= old len(self.balances). - Laws.
law name(params) requires … holds … by …, withrequiresandbyoptional.holdstakes an expression, or a block of statements ending in one (somutmethods can be stated withoutold). At the top level a law is a theorem, proven once; a generic one (law agrees[T: Eq + Hash](a, b: T) requires a == b holds a.hash() == b.hash()) must follow from its bounds' laws. In a trait, a law is an obligation every impl meets, by the prover or bylaw name by …in the impl. A trait-level invariant is a law overSelf. - Proofs.
bytakes a single step (by arithmetic,by auto,by simplify by append_assoc,by other_law(a, b)) or a block holding a whole proof (by { match xs { … } }). Section 8.4 gives the steps, and section 8.9 the nodes. - A law, like a test, takes a
///doc comment as its description.verifyshows it with the law's verdict. - Sums.
| A { … } | B(T) | C⇒ aSumTypeof aNamedrecord, aNamedtuple and anAtom.with { … }after the last member ⇒ each shared field in every member's record (section 3.4). A member may be a type declared elsewhere:type Error = NotFound | Denied. - Records. A field is
name: type, with= defaultandpubbefore it as needed. - Impls.
impl Tr for Timplements a trait;impl TgivesTmethods of its own.
2.4 Types
A type is an expression (section 6). In the places that hold a type (after : in a parameter, field, binding or annotation, after ->, inside the brackets of a type application, and to the right of type X =), these forms read as types:
type = error_type ;
error_type = sum_type [ "!" sum_type ] ;
sum_type = [ "|" ] list_type { "|" list_type } ;
list_type = { "[" "]" } option_type ;
option_type = type_atom { "?" } ;
type_atom = named_type | "(" [ type { "," type } ] ")" | record_type
| function_type | type_atom "where" expression ;
named_type = identifier { "." identifier } [ "[" type_argument { "," type_argument } "]" ] ;
type_argument = type | expression ;
record_type = "{" [ field { "," field } ] [ "," ".." ] "}" ;
field = { doc_comment } [ "pub" ] identifier ":" type [ "=" expression ] ;
function_type = "(" [ function_param { "," function_param } ] ")" "->" type ;
function_param = [ "mut" | "cap" ] [ identifier ":" ] type ;
bound = named_type ;
type_value = type | member { member } [ "with" record_type ] | expression ;
member = "|" identifier [ "(" type { "," type } ")" | record_type ] ;
| written | core |
|---|---|
T? | Option[T] |
[]T | List[T] |
A ! E | Result[A, E] |
A | B | SumType { members: [A, B] } |
T where p | Refinement { base: T, predicate: p } |
{ x: f64, .. } | RecordType { open: true, … } |
- A function type's parameters may be unnamed,
(Reply[s64]) -> Get: each is then a_parameter, passed positionally (section 2.6). Unnamed parameters are named by position,_0,_1, …, so each has its own id. - A
type_valuethat isn't a type is a type function's body (section 6.7), an expression giving aType. Atype_argumentthat isn't a type is a value argument (Matrix[3, 4]). - Postfix
?binds tightest, then prefix[], then|, then!, which splits a whole type at most once:A | B ! C | DisResult[A | B, C | D].[]User?isList[Option[User]];([]User)?is an optional list. - A
?must touch the type before it, with no space or newline. - Elsewhere,
|,!and?are the value operators of section 2.5.
2.5 Expressions and precedence
The whole expression grammar, from the loosest form to the tightest. Section 2.4 gives type, section 2.6 argument, section 2.8 block and statement, section 2.9 the handlers' forms, section 8.4 proof.
expression = iff ;
iff = implies [ "<=>" implies ] ;
implies = disjunction [ "==>" implies ] ;
disjunction = conjunction { "||" conjunction } ;
conjunction = comparison { "&&" comparison } ;
comparison = piped [ "==" piped { "==" piped } | "!=" piped
| less piped { less piped } | greater piped { greater piped }
| "is" pattern ] ;
less = "<" | "<=" ;
greater = ">" | ">=" ;
piped = range { "|>" range } ;
range = bit_or [ ( ".." | "..=" ) bit_or ] | ".." bit_or | bit_or ".." ;
bit_or = bit_xor { "|" bit_xor } ;
bit_xor = bit_and { "^" bit_and } ;
bit_and = shift { "&" shift } ;
shift = additive { ( "<<" | ">>" ) additive } ;
additive = multiplicative { ( "+" | "-" ) multiplicative } ;
multiplicative = prefix { ( "*" | "/" | "%" ) prefix } ;
prefix = ( "-" | "!" | "mut" | "move" ) prefix | power ;
power = postfix [ "**" prefix ] ;
postfix = primary { "(" [ argument { "," argument } [ "," ] ] ")"
| "[" expression { "," expression } "]"
| "." identifier | "." digits
| "!" | "?"
| ( "except" | "or" ) handler } ;
handler = block | "{" { pattern "=>" expression "," } "}" | identifier block
| tight | "break" | "continue" | "return" ;
tight = primary { "(" [ argument { "," argument } ] ")" | "[" expression "]"
| "." identifier | "." digits } | "-" number ;
primary = literal | identifier | "self" | "Self" | "it" | hole
| "(" expression ")" | "(" expression ":" type ")" | tuple
| list | comprehension | record | collection
| block | if | match | lambda
| "return" [ expression ] | "break" { "break" } | "continue"
| "comptime" postfix | "old" postfix | "await" postfix
| spawn | "scope" block | select | race
| "arena" block | "frozen" expression "as" identifier block
| "mock" type [ "with" ( "Ghost" | "Generated" ) ] ;
literal = number | string | raw_string | f_string | "true" | "false" ;
tuple = "(" ")" | "(" expression "," expression { "," expression } [ "," ] ")" ;
list = "[" [ expression { "," expression } [ "," ] ] "]" ;
comprehension = "[" expression for_clause { for_clause } [ "where" expression ] "]" ;
for_clause = "for" pattern "in" expression ;
record = [ named_type ] "{" [ field_value { "," field_value } [ "," ] ] "}" ;
field_value = identifier [ ":" expression ] | "..." expression ;
collection = "Dict" "{" [ entry { "," entry } [ "," ] ] "}"
| "Dict" "{" entry for_clause { for_clause } [ "where" expression ] "}"
| "Set" "{" [ expression { "," expression } [ "," ] ] "}" ;
entry = expression ":" expression ;
if = "if" expression block { "else" "if" expression block } [ "else" block ] ;
match = "match" expression [ "as" identifier ] "{" { arm "," } "}" ;
arm = pattern [ "where" expression ] "=>" expression
| "where" expression "=>" expression ;
lambda = lambda_params "->" expression ;
lambda_params = identifier | "(" [ lambda_param { "," lambda_param } ] ")" ;
lambda_param = [ "mut" | "cap" ] identifier [ ":" type ] ;
spawn = [ "supervised" ] "spawn" [ "(" identifier ":" expression { "," identifier ":" expression } ")" ] expression ;
select = "select" "{" { expression [ "as" pattern ] "=>" expression "," } "}" ;
race = "race" "{" { [ "supervised" ] expression [ "as" pattern ] "=>" expression "," } "}" ;
pattern = alternative { "|" alternative } ;
alternative = "_" | [ "mut" ] identifier | literal | "-" number
| identifier ":" type
| named_type [ "(" [ pattern { "," pattern } ] ")" | "{" field_patterns "}" ]
| "(" [ pattern { "," pattern } ] ")"
| "[" [ pattern { "," pattern } ] [ "," ".." [ identifier ] ] "]"
| "{" field_patterns "}" ;
field_patterns = [ identifier [ ":" pattern ] { "," identifier [ ":" pattern ] } ] [ "," ".." ] ;
place = identifier { "." identifier | "[" expression { "," expression } "]" } ;
- A comparison's operands are
piped, so a comparison is never an operand of another without parentheses;lesschains andgreaterchains are the one form that reads several. - In the head of
if,while,matchandfor(between the keyword and its block),recordand thenamed_type { … }pattern are not read:{starts the block (below). identifier ":" typein a pattern tests the value's type and binds it narrowed (e: NotFound). In arecord,identifier ":"is a field.- A bare name in a pattern is a constant when it refers to an atom or another value in scope (
None), and a new binding otherwise (x). By section 5.6 atoms are capitalised and bindings aren't, so a reader sees which;elaboratedecides by what the name refers to. - A refinement's predicate runs as far as an expression can, so a refined member of a sum is parenthesized:
(Int where it > 0) | String. A parenthesized type is grouping:-> ({ x: f64 })gives a structural record as a result, where a bare{would open the body. - A
type_valueis read as a type when its tokens form one whole type, and as an expression otherwise (Record { … }in a type function). - In
type X = | A | B, a name in scope is that type, and any other declares a new atom of the module. A misspelt type therefore becomes an atom nobody uses, which R4 reports (section 6.1). extern rust,extern pythonandextern tsare the forms bindings are written and shown in (section 11.2); a program writes onlyextern cby hand.- A
wherearm is a pattern, not a guard: it narrows like one (section 6.5).match e as name { … }names the matched value, whichwhereconditions and bodies read. - A handler's
identifier blockis the binding form only for a lowercase identifier; an uppercase one is atightvalue followed by a block (section 2.9). returnwith a value isprimaryhere, but as a handler's operand only the bare jumps are allowed;breakandcontinuenever take a value.- A
tightoperand'sprimaryis never a lambda:x or a -> bis an error, writtenx or (a -> b). - In an expression,
{starts a block. A structural record literal writes each field's name,{ x: 1, y: 2 }(no puns), so{ x }is a block givingx, and{}an empty block. A{whose first item isname:followed by an expression and then,or}is a structural record; one whose first item holds=or:=at its top level is a block. Afterexcept {oror {, the arms form when the first item holds=>at its top level, else the block form. - A
Bind's pattern can't fail: a tuple, a record, a name. A pattern that can (Some(v) := opt) is an error; writev := opt or …, or amatch. A type test is never aBind's pattern. - A prefix
mutmarks the last call of the chain it stands before:mut a.f().g()marksg;f's mark needs parentheses,(mut a.f()).g(). - A pattern in parentheses with no comma is grouped, never a one-element tuple:
(Circle { r })is the record pattern.
From tightest to loosest (17 levels):
| level | forms | associativity |
|---|---|---|
| 1 | literals, names, (e), (e: T), tuples, lists, records, blocks, if, match, lambdas, spawn, scope, await, select, race, comptime e, old e, mock T, holes | |
| 2 | calls f(…), […], .f, .0, .m(…), postfix ! and ?, except and or | left |
| 3 | ** | right |
| 4 | prefix -, !, mut, move | |
| 5 | * / % | left |
| 6 | + - | left |
| 7 | << >> | left |
| 8 | & | left |
| 9 | ^ | left |
| 10 | | | left |
| 11 | .. ..= | none |
| 12 | |> | left |
| 13 | == != < <= > >= is | none |
| 14 | && | left |
| 15 | || | left |
| 16 | ==> | right |
| 17 | <=> | none |
-x ** 2is-(x ** 2), and2 ** 3 ** 2is2 ** (3 ** 2).- Handlers bind tight.
exceptandorsit with the postfix forms, read left to right. Without braces, their operand is one tight operand: a level 1 or 2 form with no handler of its own, or a negative number literal. Sox or d.fisx or (d.f),-x or dis-(x or d), and a handler used as a receiver or a field's base is parenthesized:(x or d).f. The prefixescomptimeandmuttake the whole handler:comptime m.name or ""iscomptime (m.name or ""), andmut q.pop() except ()marks the call inside the handler. - Ranges sit at level 11, tighter than comparisons and pipes. Whether they read better looser than comparisons is to try in the lab.
- Comparisons don't associate. A comparison can't be the operand of another without parentheses:
a != 0 == bis an error, written(a != 0) == b, and the printer writes the parentheses. Chained</<=and>/>=are the one form that reads several (below). - Chained comparisons.
a < b <= cmeansa < b && b <= c, withbevaluated once. A chain uses<and<=only,>and>=only, or==only:gcd(p1, q1) == gcd(p2, q2) == 1means each pair is equal.a < b > c,a == b < c, and any chain with!=oris, are errors. ⇒Andof the comparisons, with the middle operand bound first when it isn't a name or a literal. (e: T)checkseagainstT. It is no node: it setse's type.- A call's
(and an index's[must touch what comes before them (section 1.10), and so must a postfix!or?. x[a, b]is one form whateverxis.elaboratemakes it aTypeApplicationwhenxnames a type or a type function (Matrix[3, 4]), and a call ofIndexwhenxis a value. Several indices are one tuple key:m[3, 4]isIndex.at(m, (3, 4)), andgrid[r, 1..]passes a tuple of an integer and a range, as NumPy's arrays take them. That is name resolution, not typing: what a name refers to is known before any type is. The naming conventions (section 5.6) show it to a reader too: types are capitalised, and the lowercase machine types take no arguments.old eandcomptime etake a whole level-2 expression, handlers included:old len(x)isold (len(x)), andcomptime m.name or ""iscomptime (m.name or "").
Operators are calls of core's traits (section 12):
| written | core |
|---|---|
a + b, a - b, a * b, a / b, a % b, a ** b | Add.add(a, b), Sub.sub, Mul.mul, Div.div, Rem.rem, Pow.pow |
-a | Neg.neg(a) |
a == b, a != b | Eq.eq(a, b), Not { Eq.eq(a, b) } |
a < b, a <= b, a > b, a >= b | Ord.lt(a, b), Ord.le, Ord.gt, Ord.ge |
a & b, a | b, a ^ b, a << b, a >> b | BitAnd.bit_and(a, b), BitOr.bit_or, BitXor.bit_xor, Shl.shl, Shr.shr |
xs[i], xs[a..b] | Index.at(xs, i), Index.at(xs, range(a, b)) |
a..b, a..=b, ..b, a.. | range(a, b), range_inclusive(a, b), range_to(b), range_from(a) |
a && b, a || b, a ==> b, a <=> b, !a | the nodes And, Or, Implies, Iff, Not |
Each call is stored with the trait method as written_as (section 3.4), so the printer writes the operator back.
2.6 Calls and arguments
call = expression "(" [ argument { "," argument } [ "," ] ] ")" ;
argument = [ identifier ":" ] [ "mut" | "cap" | "move" ] expression
| "..." expression ;
Examples: send(to: admin, message), max(x, y), grow(items: mut list), grow(mut items), report(cap console), connect(host, port: 80, ...options), mut queue.claim(2).
- An argument for a parameter named
_xis written without a name, in order. Every other argument is named:name: value. A named argument whose value is a variable of the parameter's name is written bare (punning):send(to: admin, message)passesmessagetomessage. - A bare variable named like one of the callee's named parameters is a pun for it, unless a
_parameter without a default is still to be filled: then it fills that one. So forfn f(_a: s64 = 0, b: s64),f(b)passesbtoband_akeeps its default; forfn f(_a: s64, b: s64 = 0),f(b)passesbto_a. The rule reads only the callee's parameters, never types. Where a bare variable fills a_parameter while a named parameter of its name keeps its default, the printer writes that parameter too, so the call can't be misread:f(b, b: 0).elaborateapplies it once the callee is known: a method's callee, by its receiver's type. The parsed tree keeps the bare argument until then. - Arguments come in the order of the parameters. ⇒
Call.arguments, by parameter id, in parameter order. - A parameter with a default may be left out.
mut xandcap xmark an argument passed to amutorcapparameter. The marks are required and checked (section 6.9), never stored.- A method that takes
mut selfis called with the mark before the receiver:mut queue.claim(2). Inside another call it is parenthesized:f((mut queue.pop()), x). - Spawn options.
spawn(stack: s, on: p) egives a task its stack size and its placement (sections 9.1 and 9.9), each optional, named as arguments are. Afterspawn,(always opens the options, whatever space comes before it: a task that evaluates a parenthesized expression is writtenspawn { … }. ⇒Spawn.stack,Spawn.on. - Spreads.
...rfills every parameter not given otherwise from the field ofrwith its name. ⇒ the arguments written out,f(a, r.b, r.c), withrbound first when it isn't a variable. - Pipes.
a |> fisf(a), anda |> f(limit: 3)isf(a, limit: 3): the piped value fillsf'sselfwhen it has one, else its first_parameter:text |> trimmedistext.trimmed(). A step may instead say where the value goes with a_among its arguments:sum(xs) |> sqrt |> max(5, _)ismax(5, sqrt(sum(xs))). (Writtenxs |> sum |> max(5, _), it is the same tree, with two calls, and is printedmax(5, sum(xs)).) The_may also sit inside one argument's expression (print(_!, view),area(_.shape)). A step holds at most one_, never inside a lambda, and a step with none into a function with no_parameter is an error._in an expression anywhere else is an error. ⇒ the nested calls. The printer writes a pipe only for a chain of three or more calls, each feeding the next one's first_parameter: The chain starts with its first call written in full, arguments and all:h(g(f(a, b)))is printedf(a, b) |> g |> h, nevera |> f(b) |> g |> h(which reads back the same and is valid to write).g(f(a))stays as it is. Where the value goes to a parameter other than the first_one, the step is printed with_. A chain that is an argument of another call, an operand of an operator or a method's receiver is printed nested.
2.7 Values made of parts
| written | core |
|---|---|
(a, b), () | Tuple: none, or two elements or more. (x) is x, and there is no one-element tuple; a single value is wrapped by a named type (Replace(x)), which shows it. |
[a, b] | ListLiteral |
Point { x: 1.0, y } | Construct { named: Point, value: RecordLiteral { … } }; y is punned |
Point { ...p, y: 3.0 } | RecordLiteral { base: p, … } under Construct |
{ x: 1, y: 2 } | RecordLiteral alone, a structural record |
Some(x) | Construct { named: Some, value: x } |
None, true | Global of the atom |
Dict { "a": 1 }, Set { 1, 2 } | dict([("a", 1)]), set([1, 2]) |
[x * x for x in xs where x > 0] | xs.filter(x -> x > 0).map(x -> x * x) |
[(a, b) for a in xs for b in ys] | xs.flat_map(a -> ys.map(b -> (a, b))) |
Dict { w: len(w) for w in words } | dict(words.map(w -> (w, len(w)))) |
f"{name} has {n} items" | concat([Display.text(name), " has ", Display.text(n), " items"]) |
- Fields, like arguments, are written in the order the type declares them, so the order written is the order evaluated (section 7.1) and the order stored.
editrefuses another order and gives the declared one.
2.8 Statements and blocks
block = "{" [ statement { newline statement } ] "}" ;
statement = [ "mut" ] pattern ":=" expression
| [ "mut" ] identifier ":" type "=" expression
| [ "mut" ] place ( "=" | "+=" | "-=" | "*=" | "/=" | "%=" ) expression
| "while" expression { loop_clause } block
| [ "comptime" ] "for" pattern "in" expression { loop_clause } block
| "loop" block
| "assert" expression [ "by" proof ]
| "dbg" expression
| expression ;
loop_clause = "invariant" expression | "decreases" expression { "," expression } ;
| written | core |
|---|---|
x := e, (a, b) := e | Bind |
mut total: s64 = 0 | Bind of a mutable Binding of type s64 |
x += e | Assign { place: x, value: Add.add(x, e) } |
mut xs[i] = v | Evaluate { Index.set(mut xs, i, v) } |
loop { … } | While { condition: true, … } |
comptime for | For { unrolled: true, … } |
dbg e | Debug { value: e } |
mut grid[r][c] = v | a block of three: row := Index.at(grid, r), Index.set(mut row, c, v), Index.set(mut grid, r, row), with row a nameless binder |
mut xs[i].f = v | Index.set(mut xs, i, RecordLiteral { base: Index.at(xs, i), f: v }) |
- Changing part of a value is marked. An assignment to an element or a field (a place with
[ ]or.) is written withmut, as a call that changes a value in place is:mut xs[i] = 3,mut p.x += 1,mut grid[r][c] = v. Assigning a wholemutvariable is not:x = 3.editrefuses a missing or a wrong mark. - Nested places are assigned from the inside out: each outer place is set to its old value with the inner place changed, as the table shows. A field place of a record is a record update. The value is read once, at the innermost place's base.
- A block's value is its last statement when that is an expression, else
(). No newline is needed before}(section 1.10). - An expression used as a statement, other than the last, must give
(); a value thrown away is written_ := e, so a droppedResultis always visible. if c { a } else { b }is an expression. Withoutelse, its value is().dbg eprintse's text and value (total = 42) understrata run --debug, and is removed from every other build:strata runwithout the flag,test,build,verify. Its expression must be pure: no capability, nomut.
2.9 Handlers
| written | core |
|---|---|
x! | match x { Ok(v) => v, Err(e) => return Err(e) } |
x? | match x { Some(v) => v, None => return None } |
x except { b } | match x { Ok(v) => v, Err(_) => b } |
x except e { b } | match x { Ok(v) => v, Err(e) => b } |
x except { P => b, … } | match x { Ok(v) => v, Err(e) => match e { P => b, … } } when the arms cover every member of the error; otherwise a Result of the members left: match x { Ok(v) => Ok(v), Err(e) => match e { P => Ok(b), …, r => Err(r) } }, which ! after it passes on |
x or { b } | match x { Some(v) => v, None => b } |
x except d, x or d | as x except { d }, x or { d }, for a tight d |
- Heads before a block. In the head of
if,while,matchandfor, and in a function's signature after its parameters (its result type, refinements and contracts), and in a loop's clauses, a{always starts the block: a record literal or a record pattern in a head is written in parentheses,if s is (Circle { r }) { … },match (Point { x, y }) { … },ensures it == (Point { x, y }) {. The rule is by position. (The handler's binding form, section 2.9, is the one place case decides, through the enforced naming conventions.) - After
exceptoror, a{starts the block or arm form, and a lowercase identifier followed by{starts the binding form:x except e { … }. An uppercase name before{is a value:x except Header { module, entries: [] }. - Anything else is a tight operand (section 2.5: a literal, a name, a call, a field or index access) or a bare jump (
break,continue,returnwith no value):setting("port") or 8080,tx.send(v) except return,next() or break. - A fallback with an operator, and every jump with a value, goes in a block:
x except { return e + 1 }.x except return eandx or a + bare errors. - The binders the core forms introduce (
v,eabove) have no names in the tree (section 3.2). !returns only errors that fit the function's error type (section 6.8).
2.10 Printing
print(t, view)writes a stored tree under the reader's settings. They are kept in the reader's own configuration, never instrata.toml, and a command's flags override them:- each type notation of section 2.4 (
T?orOption[T],[]TorList[T],A ! EorResult[A, E]), all explicit by default; --types, which writes every type as(e: T);- how strings are written, plain or raw where they can be (section 1.6);
--core, which writes every sugar as its core form and every constructor inference put in;- the indentation, 2 spaces by default.
- each type notation of section 2.4 (
- The parser reads every notation under every setting.
- The printer writes the shortest form inference gives back exactly: a type left out wherever inference rebuilds it, a constructor left out wherever section 6.4 puts it back, and each sugar for the core form it stands for.
- Layout is canonical: the reader's indentation (2 spaces by default), lines broken at the reader's width (80 columns by default) as laid out at that indentation (line breaks are printing, never stored), a broken line continued with its operator first, a list broken one item per line with a trailing comma. Comments go above definitions and statements, and at the end of the line for parameters, fields and members (section 3.2).
2.11 Laws
// printing then reading gives back the stored tree, under every setting but `--core`, its ids matched by name in the module (section 3.1)
law stored_round_trip(t: Module where stored(it), view: Settings where !it.core)
holds print(t, view) |> parse |> desugar |> elaborate_into(t, _) == Ok(t)
// text the printer wrote prints the same again
law printing_is_stable(t: Module where stored(it), view: Settings where !it.core)
holds print(t, view) |> parse |> desugar |> elaborate_into(t, _) |> print(_!, view) == print(t, view)
// the printer chooses a sugar only where reading it back gives the same node
law sugar_choice(n: Node, context: Context, view: Settings, text: String)
requires chosen_sugar(n, context, view) == Some(text)
holds text |> parse_node |> desugar |> elaborate_in(context) == Ok(n)
// one tree for each text: two stored trees with the same ids for the same names never print the same under one setting
law print_injective(a: Module where stored(it), b: Module where stored(it), view: Settings where !it.core)
requires print(a, view) == print(b, view) && same_names_same_ids(a, b)
holds a == b
// each sugar's builder and reader are inverse (one pair per form)
law sugar_pairs(form: Sugar, n: Node)
requires reads_as(form, n)
holds build(form, read(form, n)) == n
stored_round_trip follows from sugar_choice by induction over the tree. Text back to the same text does not hold and isn't wanted: layout, a written constructor the types decide, a written type inference gives, and a hand-written handler-shaped match are all printed in their one canonical form.
3. The tree
A module is stored as a tree. This section lists every node and its fields. Section 4 gives the bytes, section 2 the text each node is written as, and section 6 the typing rules a stored tree obeys.
The tree is written here as Strata types. Option[T], List[T], Dict[K, V] and String are core's. A field whose name would be a keyword takes a leading _ (_type, _trait); a leading _ means nothing on a field.
3.1 Ids, keys and node indices
distinct type Id = u32 where it != 0
distinct type NodeIndex = u32
type Key = { module: ModulePath, id: Id }
type NodeKey = { definition: Id, node: NodeIndex }
type ModulePath = { package: Name, path: List[Name] }
type Name = String where is_identifier(it)
- These have an
Id: definitions (methods included), named types and atoms declared inside a sum (section 3.4), fields, parameters of functions, methods and function types, a trait's models, and laws (section 8).editgives each its id, so a call's target, a field access and a stamp's dependency can name any of them. - An id is unique among the ids of its module, and it stays the same through edits, renames and moves within the module.
editdraws a new id at random, never 0, and draws again while it is taken. - How text keeps its ids. Text carries no ids, so
editmatches names, each only within its own scope:- a definition written in a module keeps the id of the module's definition of that name;
- a field keeps the id of its type's field of that name, a member its sum's, a parameter its function's, a method its trait's or impl's;
- an impl, which has no name, keeps the id of the module's impl of the same trait for the same target type (section 6.6 allows one); its methods are matched by name within it, its law proofs by the law they prove;
- a name is never matched outside its scope: a field
nameof one record is never matched to a fieldnameof another, nor a parameter to a definition. - A name with no match gets a new id. A name that disappears takes its id with it:
editreports each definition, field or member removed. - A rename is never a text edit:
strata rename old newchanges one entry ofnames(section 3.2), and every id stays.
- A
Keynames something in any module: the module and the id. - A definition's nodes are every value of the types
Definition,Expression,Pattern,Statement,Parameter,TypeParameter,Field,Arm,SelectArm,RaceArmandContractreachable from it, except through the_typefield of an expression or a pattern. A type stored in that field is not a node of the definition and has no index. - The nodes are numbered from 0 in postorder: a node's children first, in the order of their fields in this section and of their lists, then the node. Bodies are numbered last, so the interface can be read alone (section 4):
- first the definition with each body left out, in postorder, which ends with the definition itself;
- then each body, in postorder, in the order of the functions that have them.
- A
NodeKeynames a node in its module: its definition's id and its index. Passes keep their results in tables keyed by it. - A local variable, a type parameter, a lambda's parameter and a pattern's binding have no id (a lambda's
Parameter.idisNone). A use refers to its binder by node index:Local { binder }. - Children. Each node's children are its node-valued fields, in the order this section lists them, each list's items in order.
children(n)gives them, andmap_children(n, f)givesnwithfapplied to each. Postorder numbering follows the same order. Every pass reads and changes trees through these two, and has its own recursion only where it gives each form a meaning of its own (lowering, inference, printing, encoding) or decides an order and joins (a flow analysis); for the forms it doesn't treat, it calls them. Nodes inside a field that is a record but not a node (Argument.value,FieldValue.value,FieldPattern.pattern,CalcStep) are children too, in that record's field order.
law children_first(d: Definition, parent: NodeIndex, child: NodeIndex)
requires is_child(d, parent, child) && !is_body(d, child)
holds child < parent
law bodies_last(d: Definition, body: NodeIndex, other: NodeIndex)
requires is_body(d, body) && !inside_a_body(d, other)
holds other < body
law binder_in_scope(d: Definition, usage: NodeIndex)
requires node(d, usage) is Local
holds in_scope(d, binder_of(d, usage), usage)
law map_identity(n: Node)
holds map_children(n, x -> x) == n
law map_children_maps(n: Node, f: Node -> Node)
holds children(map_children(n, f)) == children(n).map(f)
// what termination proofs over trees rest on
law children_smaller(n: Node, c: Node)
requires children(n).contains(c)
holds size(c) < size(n)
Section 5 defines in_scope.
3.2 Modules, names, docs and comments
No node holds a name, a doc or a comment. The module holds them in tables, keyed by id or by node.
type Module = {
doc: Doc,
imports: List[Import],
definitions: List[Definition],
names: Dict[Id, Name],
local_names: Dict[NodeKey, Name],
docs: Dict[NodeKey, Doc],
comments: Dict[NodeKey, Comment],
}
type Import =
| WholeModule { module: ModulePath, alias: Option[Name] }
| Names { module: ModulePath, names: List[ImportedName] }
type ImportedName = { key: Key, alias: Option[Name] }
distinct type Doc = List[String]
distinct type Comment = List[String]
Example: use std.time as t is WholeModule { module: std.time, alias: Some("t") }. use std.time.Clock is Names { module: std.time, names: [ImportedName { key: <Clock's key>, alias: None }] }.
namesgives the name of every id in the module, except anImpl's, which has none.local_namesgives the name of every node that binds a variable without an id (Binding,TypeParameter, the elements of named results) and of everyHole. A binder that a sugar's core form introduces (section 2.9) has no name: the text never shows it, andview --coregives it a fresh one.--coretext is for reading: the round-trip laws of section 2.11 hold under every setting but--core. A hand-writtenmatchwhose binders have names is printed as amatch, never as the handler whose binders have none.docsholds the///lines of definitions and fields.commentsholds the//lines of definitions, statements, arms, fields and parameters. A comment written above a node and one at the end of its line are both stored for that node. The printer chooses where to write it by the kind of node: above definitions and statements, at the end of the line for parameters and fields. A comment anywhere else (between arguments, inside a multi-line expression, before a closing}) is moved byeditto the nearest statement, arm, field or parameter that holds it, written above it, andeditsays so: no comment is ever dropped.docis the module's//!lines. The file gives the module's path, so a module doesn't store it.- A rename changes one entry of
namesorlocal_names, and no node.
law every_id_named(m: Module, id: Id)
requires declared_in(m, id) && !is_impl(m, id)
holds m.names.contains(id)
law every_binder_named(m: Module, n: NodeKey)
requires (binds_without_id(m, n) && !made_by_sugar(m, n)) || node_of(m, n) is Hole
holds m.local_names.contains(n)
3.3 Definitions
type Definition =
| Function {
type_parameters: List[TypeParameter],
parameters: List[Parameter],
result: Expression,
contracts: List[Contract],
body: Option[Expression],
}
| Extern {
language: ForeignLanguage,
_blocking: Bool,
_pure: Bool,
parameters: List[Parameter],
result: Expression,
contracts: List[Contract],
}
| TypeDefinition {
type_parameters: List[TypeParameter],
value: Expression,
}
| Trait {
type_parameters: List[TypeParameter],
supertraits: List[Expression],
models: List[ModelDeclaration],
contracts: List[Contract],
laws: List[Definition.Law],
methods: List[Definition.Function],
}
| Impl {
type_parameters: List[TypeParameter],
_trait: Option[Expression],
target: Expression,
models: List[ModelValue],
laws: List[LawProof],
derived: Option[Key],
methods: List[Definition.Function],
}
| Test { parameters: List[Parameter], body: Expression }
// a merge conflict that no smaller node can hold (section 4.9)
| Conflict { ours: Definition, theirs: Definition }
| Constant { _type: Expression, value: Expression }
with {
id: Id,
public: Bool,
}
type ForeignLanguage = | C | Rust | Python | TypeScript
type ModelDeclaration = { id: Id, _type: Expression }
type ModelValue = { model: Key, value: Expression }
Examples:
fn area(s: Shape) -> f64 { … }is aFunctionwith one parameter,resultthe expressionf64, no contracts, and a body.namesmaps its id toarea.type Positive = Int where it > 0is aTypeDefinitionwhosevalueis aRefinement(section 3.4).impl Mul[s64, Money] for Money { … }is anImplwhose_traitis the expressionMul[s64, Money]andtargetthe expressionMoney.
- A
Functionat the top level, or in anImpl, has a body. A method of aTraitmay have none; then each impl gives it. - Named results (
-> (low: s64, high: s64)) are aTupleTyperesult whose elements are named inlocal_names. Contracts refer to the result asit(section 3.6) and to its parts asit.0,it.1; the printer writes them by their names. - An
Implhas no name. Section 5 states how a reader finds it, by its trait and target. AnImplwith no_traitgives its target type methods of its own (section 6.6). - A method is a
Definition.Function, so it has an id of its own. A trait's methods, and those of an impl of a trait, are as visible as the trait. A method of an ownimpl Thas its ownpublic, so a type's module can keep helper methods private. - A trait's
ghost name: Tis aModelDeclaration, with an id. An impl'sghost name = eis aModelValue: a field of the impl, not a node; itsvalueis. - A trait's first type parameter is always its
Self, never written; a use of the trait (Mul[s64, Money]) gives the ones after it. In a default method, a call of another method of the trait isBound { type_parameter: <that Self>, … }, andSelfTypeis that parameter's type. - Laws are definitions too, with proofs as their bodies. Section 8.9 gives their nodes.
3.4 Expressions
Every expression has a type, which is itself an expression, in its field _type (section 6).
type Expression =
// literals
| Integer { value: LiteralNumber }
| Decimal { digits: LiteralNumber, exponent: s32 }
| Text { value: String }
// names
| Local { binder: NodeIndex }
| Global { key: Key }
| SelfType
// calls
| Call { target: Target, arguments: List[Argument] }
| Lambda { parameters: List[Parameter], body: Expression }
// values made of parts
| Construct { named: Key, value: Expression }
| RecordLiteral { base: Option[Expression], fields: List[FieldValue] }
| Tuple { elements: List[Expression] }
| ListLiteral { elements: List[Expression] }
| FieldAccess { record: Expression, field: Key }
| TupleElement { tuple: Expression, index: u32 }
// control
| Block { statements: List[Statement], result: Expression }
| If { condition: Expression, then: Expression, otherwise: Expression }
| Match { subject: Expression, name: Option[Pattern], arms: List[Arm] }
| Return { value: Expression }
| Break { loops: u32 where it >= 1 }
| Continue
// logic that skips its right side
| And { left: Expression, right: Expression }
| Or { left: Expression, right: Expression }
| Implies { left: Expression, right: Expression }
| Iff { left: Expression, right: Expression }
| Not { value: Expression }
| Is { subject: Expression, pattern: Pattern }
// tasks (section 9)
| Scope { body: Expression }
| Spawn { _supervised: Bool, stack: Option[Expression], on: Option[Expression], task: Expression }
| Await { tasks: Expression }
| Select { arms: List[SelectArm] }
| Race { arms: List[RaceArm] }
// memory (section 10)
| Arena { body: Expression }
| Frozen { value: Expression, body: Expression }
// the value a refinement, an ensures or a where-arm is about
| It
// tests
| Mock { _trait: Expression, behaviour: MockBehaviour }
// contracts and compile time
| Old { value: Expression }
| Comptime { value: Expression }
// types
| RecordType { fields: List[Field], open: Bool }
| TupleType { elements: List[Expression] }
| Named { id: Id, _type: Expression }
| Atom { id: Id }
| SumType { members: List[Expression] }
| FunctionType { parameters: List[Parameter], result: Expression }
| Refinement { base: Expression, predicate: Expression }
| TypeApplication { generic: Expression, arguments: List[Expression] }
// unfinished code
| Hole { choices: List[Expression] }
// a marker, never stored (section 3.7)
| Inferred
with {
_type: Option[Expression],
}
type LiteralNumber = | Small(u64) | Large(Bytes)
type Target =
| Static { definition: Key, written_as: Option[Key] }
| Bound { type_parameter: NodeIndex, method: Key }
| Dynamic { method: Key }
| Value { function: Expression }
type Argument = { parameter: Key, value: Expression }
type FieldValue = { field: Key, value: Expression }
type MockBehaviour = | DoesNothing | Ghost | Generated
type SelectArm = { operation: Expression, binding: Option[Pattern], body: Expression }
type RaceArm = { _supervised: Bool, task: Expression, binding: Option[Pattern], body: Expression }
Literals:
- A
LiteralNumberis a natural number.Smallholds it when it is below 2^64, so most literals take one word and no allocation.Largeholds a larger one as its bytes, least significant first, with no trailing zero byte. Integerholds the literal's value, with no sign.-1is the callNeg.neg(1). Checking that a literal fits its type (section 6.4) reads-and the literal together:-128fitss8, though128alone doesn't.Decimalis the exact valuedigits × 10^exponent, with no trailing zero indigits(1.50is{ digits: 15, exponent: -1 }); zero is{ digits: 0, exponent: 0 }. No float is ever stored: a decimal is exact.Textholds valid UTF-8. An f-string is stored as calls (section 2).
Names:
Localis a use of a variable or parameter of this definition (xinx + 1). It holds the index of the node that binds it.Globalis a use of a definition by its key: a function passed as a value (shapes.map(area)), a type (Shape), a generic (ListinList[Int]), a trait.SelfTypeisSelf: the type the enclosing trait or impl is for.
Calls:
Call.targetis what the call runs, decided at edit time:Staticnames the definition that runs: a function, an impl's method, or core's primitive for an operator on a built-in type.written_asis the trait method the source named, soa + bon twos64isStatic { definition: <core's s64 addition>, written_as: Some(<Add.add>) }. The printer writes+fromwritten_as.Boundis a method of a type parameter's bound. It is made static when the function is compiled for a type.Dynamiccalls a method through a trait value's method table. The trait value is the first argument.Valuecalls a function value.
- The printer writes a call of a method that takes
selfasx.m(…), and an operator or index wherewritten_asnames one. Nothing records which form the source used:a.add(b)andAdd.add(a, b)are one stored call, printeda.add(b). A method may also be called as a function with its receiver first,len(xs)forxs.len(): the same call, printedxs.len(). Call.argumentsholds the arguments given, in the order of the parameters. A parameter left out takes its default (section 7). A method's receiver is the first argument. The marksmutandcapat a call are not stored: they are the callee's parameter modes (section 6.9).
Values made of parts:
Constructmakes a value of a named type from its contents:Circle { r: 1.0 }isConstruct { named: <Circle>, value: RecordLiteral { … } }, andSome(x)isConstruct { named: <Some>, value: x }: a wrapper over one type holds the value itself.- An atom is its type's one value, so a use of it is a
Global:None,trueandfalseareGlobal { key: <None> },Global { key: <True> }andGlobal { key: <False> }. RecordLiteralholds the fields given, in the order the type declares them. Each field left out takes its value frombasewhen there is one (T { ...r, f: v }), and otherwise its default. So a field added to a type later fills every stored literal with no rewrite. With noConstructaround it, aRecordLiteralis a structural record ({ x: 1, y: 2 }). In a structural record type, and in a function type, a field or parameter is identified by its name: its key is{ module: core, id: h }, wherehis the first 4 bytes of its name's SHA-256 (the next 4 if those are 0), the same in every module and never among a module's own drawn ids, so{ x: f64 }written in two modules is one type. Structural fields and parameters are matched by name: the type stores each name, and the id only speeds up the lookup, so two names whose ids collide are still two fields.FieldAccessnames the field by key: the field of the record's type, or of the bound that declares it when the record's type is a type parameter.- Indexing has no node:
xs[i]is a call of core'sIndextrait (section 12),Static { …, written_as: Some(<Index's method>) }, and the printer writesxs[i]fromwritten_as.xs[i] = vand slicesxs[a..b]are calls of the same trait. Any type gets[ ]by implementingIndex.
Control and logic:
Return,BreakandContinueare expressions whose type is core'sNever.breakleaves the innermost loop;break breakleaves two, and each furtherbreakone more (Break.loops). Abreakcan't leave more loops than enclose it, nor a task's body.And,Or,ImpliesandNotare nodes, not trait calls.And,OrandImpliesevaluate their right side only when the left doesn't decide the result (i < len(xs) && xs[i] > 0never readsxs[i]out of range), and the prover uses the left side as a fact while proving the right.
Types:
- There are no variants. A sum is a sum of types:
SumType { members }. Each member is a type declared elsewhere (Global), or aNamedtype or anAtomdeclared in the sum. Named { id, _type }is a type with a name of its own, over a record (Circle { r: f64 }) a tuple of two or more elements, or one type (Replace(T), a wrapper).Atom { id }is a type with a name and exactly one value, written by its name:None,True,False.Never, the type with no value, is core's empty sum.- An open
RecordType({ x: s64, .. }) stands for any record with at least these fields (section 6.2). - A record has named fields (
Field, with ids). A tuple has unnamed elements, which are only types;.0,.1read them. - A sum with shared fields (
| A { x: s64 } | B with { id: Id }) is stored with each shared field in every member's record, under one id, and first, in the same order in every member: a read of a shared field finds it at one position whatever the member. Every member must then be aNamedrecord. The printer writeswithwhen every member starts with the same fields under the same ids. - On a sum value,
T { ...d, f: v }withfshared updates that field and keeps the member;M { ...d, own: v }makes memberMfrom any member, copying the shared fields;f(...d)spreads the shared fields. Shared fields may have defaults. TypeApplicationis a generic type with its arguments:List[Int],Result[Config, NotFound],Patch[User],Matrix[3, 4]. It isn't aCall, because a call's arguments are by parameter id and a type parameter has none.itis its own node,It, never aLocal: inside aRefinement's predicate, the value refined (the nearest enclosing one); in anensures, outside any refinement, the function's result; in a match arm'swherewith no pattern, the matched value. So aLocalalways refers to a node of its definition, in a stored type too (Array[u8, size]), and a stored type needs no indices of its own.
The _type field:
- Every expression's
_typeisSome(t), wheretis an expression whose own type isType. - The one exception is the expression naming core's
Typeitself, whose_typeisNone. So the chain of types ends: the type ofs64isType, andTypestores no type. - Nothing records whether a type was written. The printer leaves out every type that inference would give back exactly, and
view --typeswrites them all, as(e: T)(section 2).
Unfinished code:
- A
Holeis code still to write.?bodyis aHolewith no choices, namedbodyinlocal_names. Its type is the type its place expects. A definition holding a hole checks, andstrata holeslists it with its goal;build,runandtestrefuse a program that reaches one. - A merge conflict inside a definition is a
Holewhose choices are both sides' code, ours first, then the base's when it differs from both (?conflict_1). Filling the hole picks a choice or writes new code.
law one_form(n: LiteralNumber)
holds n is Large ==> value_of(n) >= 2 ** 64
law types_end(e: Expression)
holds (e._type == None) == (e == Global { key: core.Type })
3.5 Statements, patterns, arms
type Statement =
| Bind { pattern: Pattern, value: Expression }
| Assign { place: Expression, value: Expression }
| While {
condition: Expression,
invariants: List[Expression],
_decreases: List[Expression],
body: Expression,
}
| For {
pattern: Pattern,
iterable: Expression,
invariants: List[Expression],
_decreases: List[Expression],
unrolled: Bool,
body: Expression,
}
| Assert { condition: Expression }
| Debug { value: Expression }
| Evaluate { value: Expression }
type Pattern =
| Wildcard
| Binding { mutable: Bool }
| LiteralPattern { value: Expression }
| NamedPattern { named: Key, inner: Pattern }
| RecordPattern { fields: List[FieldPattern], rest: Bool }
| ListPattern { elements: List[Pattern], rest: Option[Pattern] }
| TuplePattern { elements: List[Pattern] }
| TypeTest { tested: Expression, binding: Option[Pattern] }
| Alternatives { patterns: List[Pattern] }
with {
_type: Option[Expression],
}
type FieldPattern = { field: Key, pattern: Pattern }
type Arm = { pattern: Pattern, condition: Option[Expression], body: Expression }
Examples:
x := f(y)isBind { pattern: Binding { mutable: false }, value: … }, the binding namedxinlocal_names.mut total: s64 = 0is aBindwhoseBindingis mutable and whose type iss64.x = eisAssign.x += eisAssign { place: x, value: Add.add(x, e) }.loop { … }isWhilewith the conditiontrue.comptime forisForwithunrolled: true.Some(x)as a pattern isNamedPattern { named: <Some>, inner: Binding }.Noneas a pattern isLiteralPattern { value: Global { key: <None> } }.e: NotFound => …is aTypeTest.
- A
Bindingbinds a variable. Its type is the variable's. Assert's proof (assert … by …) and the proof statements are section 8.9's.Evaluateis an expression used as a statement.
3.6 Parameters, fields, contracts
type Parameter = {
id: Option[Id],
_type: Expression,
mode: ParameterMode,
default: Option[Expression],
}
type ParameterMode = | Plain | Mutable | Capability | Comptime
type TypeParameter = {
_type: Expression,
bounds: List[Expression],
variance: Variance,
default: Option[Expression],
}
type Variance = | Covariant | Contravariant | Invariant
type Field = {
id: Id,
public: Bool,
_type: Expression,
default: Option[Expression],
}
type Contract =
| Requires { condition: Expression }
| Ensures { condition: Expression }
| Decreases { measures: List[Expression] }
with {
_assumed: Bool,
}
- A parameter named
_xis passed without its name (section 2). Its name keeps the_. - A function type's parameters are
Parameters with ids, because names are part of a function type. A lambda's parameters areParameters too, but bind like locals (section 3.1): theiridisNone, and their names are inlocal_names. A lambda passed where a function type is expected takes that type's names. A function type's parameter'sidis its name's hash, and its key's module iscore(section 3.4). - A
TypeParameter's_typeisTypefor a type parameter, or an integer,Boolor atom type for a value parameter (type Matrix[R: s64, C: s64]). varianceis computed by elaborate (section 6) and is part of the type's interface.itis anItnode (section 3.4).
3.7 Parsed trees and stored trees
parse and desugar give a tree with a marker for each type left to infer. elaborate fills them in and gives the stored tree.
Inferredstands where a type was left out. Every expression whose type wasn't written gets_type: Some(Inferred)fromparse.- A constructor left out (
Some,Ok,Err: section 6) has no marker, sinceparsecan't tell where one is missing.elaborateputs in theConstructwherever the expected type asks for one, or reports where the types don't decide which. The printer leaves it out again where inference would put it back. - A stored tree has no markers. A
Call's target and a node's type are known in every stored tree.
law stored_has_no_markers(d: Definition where stored(it))
holds !any_node(d, n -> n is Inferred)
Section 2 states how print, parse, desugar and elaborate round-trip on stored trees.
3.8 Laws
Stated above: children_first, bodies_last, binder_in_scope, map_identity, map_children_maps, children_smaller, every_id_named, every_binder_named, one_form, types_end, stored_has_no_markers. Further laws, sketched, proven on the code that builds and checks trees:
// ids are unique in their module
law ids_unique(m: Module where !has_conflicts(it), a: Id, b: Id)
requires declared_in(m, a) && declared_in(m, b) && a == b
holds declaration_of(m, a) == declaration_of(m, b)
// node indices are 0 to n - 1, each once
law indices_dense(d: Definition)
holds sorted(indices(d)) == range(0, node_count(d))
// a call gives each parameter at most once, in parameter order
law arguments_in_order(c: Call)
holds strictly_increasing(c.arguments.map(a -> parameter_position(c.target, a.parameter)))
// a record literal gives each field at most once, in declared order
law fields_in_order(r: RecordLiteral)
holds strictly_increasing(r.fields.map(f -> field_position(r._type, f.field)))
// a shared field has one id in every member of its sum
law shared_fields_one_id(s: SumType, f: Id)
requires shared_field(s, f)
holds s.members.all(m -> has_field(m, f))
// shared fields come first, at one position in every member
law shared_fields_first(s: SumType, f: Id)
requires shared_field(s, f)
holds s.members.all(m -> field_position(m, f) == shared_position(s, f))
// every stored tree is well typed: each node's type follows from its children's (section 6)
law stored_is_typed(d: Definition where stored(it) && !has_conflicts(it))
holds well_typed(d)
4. The binary format and hashing
A module is stored as one module file, NAME.strata, holding the tree of section 3 in the encoding below. Text is never stored. A package is a folder of module files and a strata.toml (section 5).
4.1 Primitives
| notation | encoding |
|---|---|
uint | unsigned LEB128: 7 bits per byte, least significant first, the high bit set on every byte but the last. Shortest form only, at most 64 bits. 300 is ac 02. |
int | a 64-bit signed integer, zigzag-encoded (0, -1, 1, -2 become 0, 1, 2, 3), then written as a uint. |
bool | one byte, 0 or 1. |
id | 4 bytes, least significant first: a u32, never 0. |
hash | 16 bytes: the first 16 bytes of a SHA-256 digest. |
offset | 8 bytes, least significant first: a position in the file, in bytes from its start. Fixed width, so the offsets at the start of a file can be written before the sections they point to are laid out. |
bytes | a uint length, then that many bytes. |
text | bytes that are valid UTF-8. |
list(T) | a uint count, then each item. |
option(T) | a bool, then the value when it is 1. |
| a record | its fields, in the order section 3 lists them. |
| a sum | a uint tag, then the fields of that member, in order. |
Every encoding is canonical: one value has exactly one encoding, and the decoder refuses any other (a uint not in its shortest form, a bool other than 0 or 1, invalid UTF-8, a list out of its stated order).
4.2 The file
module-file = "STRATA" version:uint kind:uint
interfaces_start:offset bodies_start:offset constants_start:offset texts_start:offset
header interfaces bodies constants
- A file starts with the six ASCII bytes
STRATA(53 54 52 41 54 41), then the format version,2, then0for a module file (1for a certificate, section 4.8). Version 1 is the lab's format, which this one doesn't read. - The four offsets say where the interfaces, the bodies and the constants begin, and where in the constants the texts' own constants begin (section 4.5), so a reader jumps to the part it needs. The header starts right after them.
- The sections hold, in order:
- the header (section 4.3): the module's doc, imports, ids and one entry per definition;
- the interfaces: each definition's interface, in the order of the entries;
- the bodies: each definition's bodies, in the same order;
- the constants (section 4.5): every string and large number of the file, once each, those only the texts use last, then each definition's local names, docs and comments.
- Checking code against the module, listing it, or recomputing its stamps reads the header and the interfaces, and the constants before
texts_startfor names. Bodies are read only for the definitions being compiled, proven or shown, and texts only for what is shown. - The file ends exactly after the constants. Written proofs are definitions in it (a law's body); proof results and certificates are kept outside it (section 4.8).
4.3 The header
The header is the module's table of contents. It holds what a reader needs without decoding any definition: the module's doc and imports, every id of the module and every key of another module it refers to, and one entry per definition with its visibility, hashes, dependencies, stamp and sizes. Listing a module, building the dependency graph, recomputing stamps and finding a definition's parts read only the header (and the pool, for names).
header = doc:list(uint) imports:list(Import) modules:list(ModulePath)
declared:list(Declared) refs:list(Ref) entries:list(Entry)
ModulePath = package:uint path:list(uint)
Import = 0 module:uint alias:option(uint)
| 1 module:uint names:list(ImportedName)
ImportedName = key:uint alias:option(uint)
Declared = id:id name:option(uint) owner:uint
Ref = module:uint id:id name:uint
Entry = definition:uint public:bool variant:uint
interface_hash:hash code_hash:hash
dependencies:list(uint) stamp:hash
interface_size:uint body_size:uint text_size:uint
- Every name, path part, alias and line of doc in the header is a
uint: an index into the constants pool (section 4.5). docis the module's//!lines.moduleslists every other module the file names, in imports or in references, sorted by package, then by path, comparing the bytes of their names. AnImport's and aRef'smoduleis an index into it.declaredlists every id of the module (section 3.1). For each definition in order: the definition's own id, then each id it declares (methods, models, named types and atoms, fields, parameters), in node order: its interface's, then its bodies'.nameis the id's name, from the module'snamestable. It is none only for anImpl.owneris the index indeclaredof the definition that declares the id. A definition is its own owner.
refslists every key of another module that the file refers to, sorted by module index, then by id.nameis the name its module gave it when this file was written. Section 5 says which name a reader uses when the two differ.- The id table is
declared, thenrefs. Everywhere else in the file, a key is auint: its index in this table. entrieshas one entry per definition, in the module's order.definitionis the index indeclaredof the definition's id,publicitspublic, andvariantits tag in theDefinitionsum (section 4.6).dependencieslists the keys whose interfaces the definition's check relied on (section 6), as id-table indices, sorted by key (module path, then id) so the order doesn't depend on the file's tables. A key may name a part of a definition, a member, a field or a method, when the check relied on that part only.- The two hashes and the stamp are in section 4.7.
interface_size,body_sizeandtext_sizeare the sizes in bytes of the definition's interface, of its bodies, and of its texts in the constants section. A definition's interface starts after the interfaces section's shared type list (section 4.4), plus theinterface_sizes of the entries before it; its bodies likewise in the bodies section, and its texts where the constants'textslist starts.
4.4 Interfaces and bodies
interfaces = types:list(TypeEntry) list(interface)
interface = local_types:list(TypeEntry) nodes:list(Node)
bodies = types:list(TypeEntry) list(definition_bodies)
definition_bodies = local_types:list(TypeEntry) bodies:list(list(Node))
TypeEntry = nodes:list(Node)
- Type indices count the interfaces' shared list, then the bodies' shared list, then a definition's own
local_types(its interface's, then its bodies'), in that order.
- A definition's interface is its nodes with each body left out. A body is the
bodyof aFunction(methods included) or of aTest, the proof of aLaw, and an impl's proofs of its trait's laws (LawProof.proof); a definition's bodies come in the order of the functions that have them. - Nodes are written in postorder (section 3.1), so the n-th node written is node index n, counting the interface's nodes and then each body's. Each node is:
Node = tag:uint flags:uint fields
tagis the node's tag in section 4.6.Inferredhas no tag, since a stored tree has none.flagsholds the node's yes-or-no fields, one bit each, the first in the lowest bit, in the order of its fields: eachBool, eachOptionof a node (set when the child is there) and each body (set when there is one). A node with none of these writes noflags. Bits past the last are 0, and the decoder refuses a set one.fieldsare the node's fields in the order section 3 lists them, each written as follows:- a node (an
Expression,Pattern,Statement,Parameter,TypeParameter,Field,Arm,SelectArm,RaceArm,Contract, or a method'sDefinition.Function): nothing, since it was written before as a child; - an
Optionof a node: nothing here, its bit is inflags; - a
Listof nodes: auint, the number of children; - a
Listof non-node records (Argument,FieldValue,LawProof,ModelValue) or of keys (Unfold.functions):list(…), each item by these same rules; - an
Optionof a non-node (Parameter.id,Option[Key]):option(…); - a body (
Function.body,Test.body): nothing here, its bit is inflags; its nodes are in the bodies section; - the
_typeof an expression or pattern: auint,0for none (onlyTypeitself), else 1 plus an index into the module's type list, or into the definition's own (local_types, numbered after the module's) for a type holding aLocal; - a
Key, or anIdthe node declares: auint, its index in the id table; - a
NodeIndex: auint; - a
LiteralNumber: tag0then auint(Small), or tag1then auint, the index of its constant (Large); - a
String(Text.value): auint, the index of its constant; - an
s32: anint; - a
u32(TupleElement.index): auint; - a
Bool: nothing here, its bit is inflags; - a sum with no fields (
ParameterMode,Variance,ForeignLanguage,MockBehaviour): auint, its member's position from 0; - a record that isn't a node (
Argument,FieldValue,FieldPattern,ModelDeclaration,ModelValue): its fields in order, by these same rules, except that itsBools are each abooland anOptionof a non-node anoption, since it has noflags.Argument.parameteris a key: the callee's parameter, an index in the id table; - a
Target: its member's position from 0, then that member's fields by these same rules.
- a node (an
- A decoder keeps a stack of nodes. Reading a node, it takes its children off the stack, the last child first, and refuses a child of the wrong type. A count of children is checked against the stack, not the bytes left. After a definition's interface, the stack holds the definition alone. After each body, it holds that body's root alone.
Types. Each distinct type stored in a _type field is written once per module, as a TypeEntry: the type's nodes, in postorder. The interfaces section starts with the types every interface uses, and the bodies section with the further types the bodies use, with indices continuing. A type enters the list the first time a node being written needs it, after the types its own nodes need. A type's nodes are not nodes of any definition (section 3.1). A node that is itself a type writes no _type: its type is Type, or follows from its form. A node that isn't a type (a literal or a call in a refinement's predicate, a value argument as in Matrix[3, 4]) writes its _type as any node does. A type holding a Local (Array[u8, size]) refers to a node of one definition, so it is written in that definition's part instead, as before.
4.5 Constants
constants = count:uint offsets:(count × 4 bytes) pool:(count × Constant) texts:list(DefinitionTexts)
Constant = 0 text
| 1 bytes
DefinitionTexts = local_names:list(NodeName) docs:list(NodeLines) comments:list(NodeLines)
NodeName = node:uint name:uint
NodeLines = node:uint lines:list(uint)
- The pool holds every string of the file (names, local names, docs, comments,
Textliterals) as atext, and everyLargenumber as itsbytes, least significant first. Each distinct constant is there once. - The pool is in order of first use, reading the file from its start: the header, the interfaces, the bodies, then the texts. So the constants only the texts use (local names, docs, comments) come last;
texts_startis the byte offset of the first of them in the file. The pool starts with a table of each constant's offset, 4 bytes each, so a constant is found by its index without reading the ones before it. Elsewhere a constant is auint, its index in the pool. textshas oneDefinitionTextsper definition, in the order of the entries: its entries oflocal_names,docsandcomments(section 3.2), each sorted by node index.
4.6 Tags
| tags | nodes |
|---|---|
| 0–6, 8 | Definition: Function, Extern, TypeDefinition, Trait, Impl, Test, Conflict; Constant is 8 |
| 16–51 | Expression: Integer, Decimal, Text, Local, Global, SelfType, Call, Lambda, Construct, RecordLiteral, Tuple, ListLiteral, FieldAccess, TupleElement, Block, If, Match, Return, Break, Continue, And, Or, Implies, Not, Is, Old, Comptime, RecordType, TupleType, Named, Atom, SumType, FunctionType, Refinement, TypeApplication, Hole |
| 52–56 | Expression, tasks: Scope, Spawn, Await, Select, Race |
| 57–61 | Expression: Mock, Iff, Arena, Frozen, It |
| 64–70 | Statement: Bind, Assign, While, For, Assert, Evaluate, Debug |
| 80–88 | Pattern: Wildcard, Binding, LiteralPattern, NamedPattern, RecordPattern, TuplePattern, TypeTest, Alternatives, ListPattern |
| 96–104 | Parameter, TypeParameter, Field, Arm, Contract's Requires, Ensures, Decreases, SelectArm, RaceArm |
Within a row, tags are numbered from the first in the order listed: Integer is 16, Hole 51. Conflict is 6; section 8.9 adds Law (7) and the proof statements (71 to 78).
4.7 Hashes and stamps
All hashes are SHA-256, kept to their first 16 bytes. strata shows a hash as the hex of its first 8 bytes. 16 bytes are far past any accidental collision; they don't stop someone forging a file, which no part of this format tries to.
The hashes are taken over a definition's hashed form: its interface and bodies as stored, with each index into a file-wide table written out in full. A constant is written as its text or bytes. A key of the file's own module is 0 then its id; a key of another module is 1, its ModulePath with each part as text, then its id. So a definition's hashes don't depend on the rest of the file.
| hash | of | changes when |
|---|---|---|
interface_hash | public, the variant's tag, and the hashed interface part | what other code relies on changes: types, signatures, contracts, visibility |
code_hash | interface_hash and the hashed body part | anything the definition does changes |
text_hash, computed when needed, not stored | code_hash, the names of the ids the definition declares (in declared order), and its local names, docs and comments, each written out in full | anything a reader of this definition sees changes, names, docs and comments included |
- No hash holds a name of another definition. So a rename changes the
text_hashof the renamed definition only. Every cache keyed byinterface_hashorcode_hash(checks, proofs, compiled code) stays valid. Compiled code names its symbols by key. stampis the hash of the definition'sdependencies' hashes, written one after another, in their order, as they were when the definition was last checked. A dependency on a whole definition contributes itsinterface_hash. One on a part (a member, a field, a method) contributes the hash of that part's hashed form alone, computed from the interface when stamps are recomputed. So a change to one field re-checks only the definitions that used that field. A dependency whose body the check relied on (a proof that saw through a callee,unfold f, acomptimeevaluation, an inlined call) contributes that callee'scode_hash, not itsinterface_hash, so a change to the body re-checks the definition and invalidates its cached verdicts, constants and compiled code.- A reader recomputes each stamp from the current headers of the modules it reads. A definition whose stamp differs is checked again before it is used (after a pull, a merge, a checkout or a fetched dependency). The result goes into the local cache (
~/.cache/strata), keyed by the definition's code hash and its dependencies' interface hashes, so the next read doesn't check it again; files change only throughedit, which writes the new stamp.strata check --fullchecks every definition whatever its stamp.
law stamp_unchanged_check_holds(d: StoredDefinition, now: Headers)
requires stamp_of(d.dependencies, now) == d.stamp
holds checks(d, now)
4.8 Proofs outside the module file
- A module file holds no proof result. Verdicts are kept in the package's proof cache,
strata.proofs, and the proofs themselves only in a certificate, written on request (sections 8.7 and 8.8). - Neither enters any hash. Adding, changing or deleting either never changes a definition's hashes, and a module file is complete without them.
- A certificate's file starts like a module file, with kind
1. Section 8.8 gives what it holds.
4.9 Merging
- git merges a module file through
strata merge-file(set up bystrata setup-git), definition by definition, matched by id. - A definition changed on one side only takes that side. One changed on both sides is merged node by node against the base: each part changed on one side only takes that side, and the conflict is kept at the smallest subtree changed differently on both. Where that subtree is an expression (a type included, since types are expressions), it becomes a
Holeholding both sides (section 3.4), re-elaborated into the merged definition so all its nodes share one numbering. Where it isn't (a parameter, a field, a statement, an arm), the conflict moves up to the nearest enclosing expression, or else to the definition, which becomes aConflictholding both whole definitions. - Two branches that drew the same id for different definitions: the incoming side's (theirs) gets a new id, taken from the SHA-256 of its old id and its code hash (the next 4 bytes while taken or 0), and its references are rewritten, so the merge gives the same result on every machine.
- Two definitions given the same name on the two sides: one
Conflictdefinition holding both, until it is resolved. checkandholeslist every conflict,buildrefuses a program holding one, and aneditresolves it.- In text, a conflict is printed by the reader's setting
conflicts:markers, the default: git's markers around each side's code, at the conflict's place, so editors show and resolve it as any git conflict:
<<<<<<< ours
total + tax
=======
total + tax(rate)
>>>>>>> theirs
block: a Strata form,?conflict { ours: total + tax, theirs: total + tax(rate) }, withbase: …third when the base differs from both. Its grammar:"?conflict" "{" "ours" ":" expression "," "theirs" ":" expression [ "," "base" ":" expression ] "}". With markers, the base is the|||||||part git writes between ours and=======.?conflictfollowed by{is read as this form, never as a hole; the marker lines (<<<<<<<,|||||||,=======,>>>>>>>at the start of a line) are tokens of their own. Both forms round-trip, so the laws of section 2.11 hold for modules with conflicts too.
edit reads either back as the same conflict, and text with one side chosen resolves it.
- A definition deleted on one side and changed on the other keeps the changed one, and the merge says so.
- The constants, tables and header are rebuilt from the merged definitions, never merged as bytes.
4.10 Reading safely
A decoder never crashes on a file. It reports the first of these as an error:
- a wrong magic, version or kind;
- a primitive not in canonical form, or a length past the end of the file;
- an offset or an index out of its range (the sections, the id table,
modules,declared, the type list, the pool,entries); - a constant given twice in the pool, or out of its order of first use;
- an unknown tag, a child of the wrong type, or a stack holding anything but the expected root at the end of a part;
- a key given twice, an id that is 0, or two ids of the module that are equal;
- a list out of its stated order, or sizes that don't add up to the length of their section;
- a
Largenumber below 2^64, or aDecimalwhosedigitsend in a zero; - an entry whose
variantorpublicdiffers from its definition's; - an
ownerthat isn't the definition whose nodes declare the id, or ids indeclaredout of the order the nodes declare them; - a key, module or constant that nothing uses.
The decoder checks no hash: hashes are computed when a definition is stored, and trusted on read, which keeps reading fast. strata check --full, and every merge, recompute them and refuse a file whose hashes are wrong. Fuzzing the reader found every other kind of change refused or written back the same.
4.11 Laws
law decode_encode(m: Module where stored(it))
holds decode(encode(m)) == Ok(m)
law encode_decode(b: Bytes where decode(it) is Ok && hashes_right(it))
holds encode(decode(b)!) == b
The second law is what canonical means: any file the decoder accepts, with right hashes, is exactly the file the encoder writes for its module. A file with a wrong hash is accepted by decode and refused by check --full.
Further laws, sketched, proven on the encoder and decoder:
// a definition's hashes don't depend on the rest of its file
law hashes_are_local(d: Definition, a: Module, b: Module)
requires d in a.definitions && d in b.definitions
holds hashes_in(a, d) == hashes_in(b, d)
// a rename changes no interface or code hash, and only the renamed definition's text hash
law rename_changes_one_text_hash(m: Module, id: Id, name: Name, d: Definition)
holds code_hash(rename(m, id, name), d) == code_hash(m, d)
&& (text_hash(rename(m, id, name), d) == text_hash(m, d) || declares(d, id))
// a change to a body leaves the interface hash as it was
law bodies_outside_interface(d: Definition, e: Definition)
requires same_interface(d, e)
holds interface_hash(d) == interface_hash(e)
// proofs are outside every hash
law proofs_outside_hashes(m: Module, proofs: Certificate)
holds all_hashes(with_proofs(m, proofs)) == all_hashes(m)
// decoding is total: an answer for every byte string, never a crash
law decode_total(b: Bytes)
holds decode(b) is Ok || decode(b) is Err
5. Names and modules
This section says what a name written in the text refers to, and who may refer to what. elaborate resolves every name when a definition is stored, so the stored tree holds keys and binder indices (section 3) and no name is looked up again.
5.1 Packages and modules
[package]
name = "shop"
[dependencies]
money = { path = "../money" }
http = { git = "https://example.org/http.git", tag = "v1.2.0" }
- A package is a folder holding a
strata.toml.[package]gives itsname, an identifier insnake_casethat is neithercorenorstd.[dependencies]names each package it uses, by apathto its folder or by agitURL with atagorrev. strata.lock, besidestrata.toml, records the commit of each git dependency. A build uses the commits it records, and onlystrata updatechanges them.- A module is one file
NAME.stratain the package's folder or below it. Its path is its folder names and file name from the package's folder, without.strata:billing/invoice.stratais the modulebilling.invoiceof its package. Each part is asnake_caseidentifier. A module and a folder beside it can't share a name (billing.strataandbilling/), so a path names one thing. [foreign]names foreign libraries, which are dependencies too: a C library, a Rust crate, a Python module or a TypeScript package (section 11.2).coreandstdare packages every package has without declaring them.strata.toml's sections:[package](name),[dependencies](section 5.1),[foreign](section 11.2; each library's notes innotes/NAME.strata),[native](C sources andlinklibraries, section 11.1),[run](task_stack, section 9.10). No other section is read.- A program starts at
fn mainin the modulemain(main.strata) of its package.
5.2 Imports
import = "use" module_path [ "as" identifier ]
| "use" module_path "." "{" imported { "," imported } [ "," ] "}" ;
imported = identifier [ "as" identifier ] ;
module_path = identifier { "." identifier } ;
Examples: use orders, use std.time as t, use money.{Money, Currency as Cur}, use std.time.Clock.
- A
module_pathwhose first part is the name of a module or folder of the package refers to a module of the package (use orders,use billing.invoice). One whose first part is a dependency's name,coreorstdnames a module of that package (use money.rates,use std.time). - A package may also name its own modules through its own name: inside std,
use std.jsonisuse json. The printer writes the short form. - A dependency named like a top-level module or folder of the package is refused when
strata.tomlis read, naming both, so nouseis ever ambiguous. use mputs the name of its last part (timeforuse std.time), or its alias, in scope as a module name.m.xthen refers to thepubdefinitionxofm.use m.{x, y as z}putsxandzin scope as the definitionsxandyofm, which must bepub.use m.x, whose last part is a definition rather than a module, is the same asuse m.{x}.- An import used nowhere is an error at edit, naming the import.
5.3 What a name refers to
A name written in a definition's text refers to the one thing in scope at that point with that name. In scope are:
- the locals whose binder is in scope there (section 5.4);
- the module's own definitions, including the types and atoms declared in its sums;
- the imports: the names
use m.{…}brings in, and the module namesusebrings in; - core's names: every module of core but
core.runtime(section 12.1) is imported in every module, as if byuse core.task,use core.channel, …, and everypubname of these modules is in scope bare (Task,Sender,Option).core.runtimeis never bare, and only core and std may import it (section 12.12). std has no such import: its modules are always imported byuse.
A module's own definition may take one of core's names. In that module the bare name is the module's own, and core's is written by its path (core.task.Task, or task.Task). edit warns when it adds such a definition, and check warns for each: "Task shadows core's core.task.Task; core's is now written by its path".
No two of the first three may have the same name at any point, except a local taking one of its module's definitions' names (below), and no rule picks between them:
- Two definitions of a module have different names. A type, a function, a trait and a type declared in a sum all share this one set of names.
- No shadowing. A binder may not take a name already in scope as a local, a parameter or an import. It may take the name of one of its module's own definitions, as it may take one of core's: within the binder's scope that definition is then written with its module's path (
shop.total), andeditwarns. So adding a definition to a module never breaks a local elsewhere in it.x := x.trimmed()is an error. A binder may take one of core's bare names (count,text): core gives way, as below, and in that binder's scope core's is written with its module (iter.count), and a local named like one of core's modules (text) hides the module too, which is then writtencore.text. Write a chain (text.trimmed().lowercase()) or a pipe (text |> trimmed |> lowercase), or give the new value its own name. - An import may not bring in a name the module defines or another import brings in.
- Core gives way. A module may define or import a name that core also has, and a local may take one. There the bare name means the module's own or the local, and core's is written with its core module:
task.Task,channel.Sender. A sum's member named like one of core's (Some) is the module's own in every pass. Core's names are keys like any other (section 3), so the two never mix.
An error says which two things have the name, and where each comes from.
A module's name is used only in a use and before a .: channel() calls core's function channel, while channel.Sender names the module's type. So a module and a definition may share a name (core's channel module and its channel function).
What follows a . is resolved by section 6 when it is a field or a method of a value (order.total, xs.len()). After a module name it is a definition of that module (orders.ship). After a type, a trait or Self it is a method of that type or trait (Money.zero(), Add.add), or, for a field, a key path (Todo.title, a KeyPath[Todo, String], section 12.10). A type's fields and its own methods have different names, so the two never meet. key_of(Todo.title) is the field's key. A call f(x, …) where no f is in scope calls the method f of x's type, len(xs) being xs.len(), which gives u64 where it < 2 ** 62.
law one_meaning(m: Module, d: Definition, at: NodeIndex, name: Name)
holds count(in_scope_named(m, d, at, name)) <= 1
5.4 Scopes
in_scope(d, binder, at) (section 3.1) holds when the node at is inside the region its binder covers:
| binder | covers |
|---|---|
a TypeParameter | the whole definition |
a function's Parameter | its contracts, its body, and the defaults of the parameters after it |
a Lambda's Parameter | the lambda's body |
a Binding in a Bind | the statements after the Bind in its block, and the block's result |
a Binding in an Arm's pattern | the arm's where condition and body |
a Binding in a For's pattern | the loop's invariants and body |
a Binding in an Is pattern | what follows it in an And chain or an Implies it starts, and the then of an If (or the body of a While) whose condition is the Is or an And chain holding it: if a && x is Some(v) { v } binds v |
it (an It node) | a refinement's predicate, an ensures, an arm's where with no pattern |
name in match e as name | the match's arms, their conditions and bodies |
5.5 Visibility
- A definition marked
pubcan be used by any module that imports it. Any other definition can be used only in its own module. - A field marked
pubcan be read, written and given in a record literal outside its module. Other fields can't. Outside its module, a record can be built only when all its fields arepub, and apubtype with nopubfield is opaque: other modules hold and pass its values and use its functions. - The types and atoms declared in a sum are as visible as the sum. A
pubsum makes its atoms, records and wrapperspub: other modules build them and name them in matches. - A
pubdefinition's interface may name onlypubtypes. That covers apubfunction's signature, apubtrait's or capability's methods, the methods of animplof apubtype, and apubtype'spubfields and its members. A private field may name a private type: other modules never see it.checkreports any other type: "Xis used by pubf; makeXpub". - A trait's methods are as visible as the trait. An impl's methods can be called wherever both its trait and its target type are visible (section 6 gives which impl a call takes).
- An extern function can't be
pub. Its module wraps it in a function, whose contracts say what the foreign code promises. A handle type can bepub; its values are capabilities (section 11.2), held as section 6.9 allows. Core's functions overcore.runtimeare ordinarypubfunctions of core, so no extern is everpub. - A sugar expands to code that is legal where it is written. A key path
Todo.titlewritten outsideTodo's module needstitleto bepub, asx.titledoes. Every core type a sugar builds (KeyPath, ranges, iterators) haspubfields, so its expansion can build it in any module.
5.6 Naming conventions
edit refuses a name that doesn't follow these, and its message gives the name that would:
| what | form | examples |
|---|---|---|
| types, types declared in sums, atoms, traits, type parameters | UpperCamel: [A-Z][A-Za-z0-9]* | Order, NotFound, T, R |
| functions, methods, parameters, fields, locals, tests, modules, packages | snake_case: [a-z_][a-z0-9_]* | total, _x, unit_price |
- Core's machine types (
s1…s128,u1…u128,f16,f32,f64,bf16) are the only types not inUpperCamel. Core declares them, and no other module can declare a type with a lowercase name. - A leading
_means something only on a parameter (section 2). - A test is named like a function, in
snake_case; its sentence is its///doc (section 2.3). The lab's tests, named by sentences, are renamed by script. - A foreign function keeps its foreign name as its symbol (section 11.2).
5.7 No cycles
- A module depends on another when it imports it or refers to one of its keys. The modules of a package, with these dependencies, form a graph without cycles. So do packages with their dependencies.
- An import or reference that would close a cycle is an error at edit, naming the modules on the cycle.
- Within a module, definitions may refer to each other in any order, recursion included.
- Core's runtime is one module,
core.runtime(section 11.1). Its parts refer to each other freely, which as separate modules would be a cycle. - So checking and compile-time evaluation go module by module in dependency order, and a stamp never depends on its own definition's module through another module.
5.8 Names when reading
- A reference stores a key (section 3). Its name is the one its owning module's
namestable gives now. - A file also keeps, in its header's
refs(section 4.3), the name each key had when the file was written. That name is used only when the owning module isn't being read with it, as when one file is shown alone. Writing the file again updates it. - A key whose owning module has no such id any more is an error naming the old name: the definition was deleted or moved.
renamechanges one name in its module's tables and nothing else.movegives the definition a new key in its new module and rewrites every reference to it in the package.
5.9 Laws
Stated above: one_meaning. Further laws, sketched, proven on the resolver and printer:
// a name the printer writes resolves back to the key it was printed from
law printed_names_resolve(m: Module, d: Definition, at: NodeIndex, k: Key)
requires refers_to(m, d, at, k)
holds resolve(m, d, at, printed_name(m, d, at, k)) == Ok(k)
// a rename keeps every reference's meaning
law rename_keeps_meaning(p: Package, id: Id, name: Name, at: NodeKey)
requires renamable(p, id, name)
holds reference_at(rename(p, id, name), at) == reference_at(p, at)
// modules and packages form a graph without cycles
law no_cycles(p: Package, m: ModulePath)
holds !reaches(dependencies(p), m, m)
// a reference to another module's definition is to a pub one
law references_are_visible(m: Module, k: Key)
requires refers_to_key(m, k) && k.module != path_of(m)
holds is_public(k)
// every stored name follows its convention
law names_follow_conventions(m: Module, id: Id)
requires m.names.contains(id)
holds follows_convention(kind_of(m, id), m.names[id])
6. Types
Every type is an expression whose type is Type (section 3). elaborate checks each definition when it is stored and gives every node its type. A program the rules below don't type is refused at edit, with the reason at the node where it arises. Nothing is typed by a default that accepts anything.
6.1 The types
| type | written | values |
|---|---|---|
| core's built-in types | Bool, String, s1 … s128, u1 … u128, f16, f32, f64, bf16, Int, Natural, Real, List[T], Dict[K, V], Set[T], Option[T], Result[T, E] | section 12 |
| a nominal record | type Point = { x: f64, y: f64 } | Point { x: 1.0, y: 2.0 } |
| a structural record | { x: f64, y: f64 } | { x: 1.0, y: 2.0 } |
| an open record | { x: f64, .. } | any record with at least a field x: f64 |
| a tuple | (s64, String); () has one value, () | (1, "a") |
| a sum | Circle { r: f64 } | Square(f64) | Empty, NotFound | Denied | a value of any member |
| a function type | (item: T) -> U | functions and lambdas |
| a refinement | s64 where it > 0 | the base's values for which the predicate holds |
| a distinct type | distinct type Meters = f64 | Meters(3.0) |
| a generic type applied | List[s64], Patch[User], Matrix[3, 4] | |
| a packed array | Packed[f32], for an element type implementing core's Machine | elements of a machine type, packed at their own size (section 10.2), passed to C as a pointer (section 11.1); a[i..j] and mut a[i..j] are views of part of it, read or changed without a copy, as mut xs[i] lends an element. a[i..j] as an argument, with or without mut, is lent without a copy; anywhere else it is Index.at's value, a copy. A view is never a value that can be stored or returned, so values keep their meaning (section 7.2); an element type's refinement holds of every element read |
| a trait used as a type | Drawable where Drawable is a trait | any value whose type implements it (section 6.6) |
Type | Type | the types |
Never | Never | none |
- A
typedefinition whose body is a record, a sum, or a tuple written in place makes a new type with its own key: two nominal records with the same fields are different types. One whose body is a refinement (type Positive = Int where it > 0) names that refinement and makes no new type (R1c). A body that is just another existing type is R1c's error. - A
distincttype has none of its underlying type's impls but the structural ones (Eq,Hash,Debug,Display):Meters + Metersneedsimpl Add for Meters, written or derived (derive Add for distinct type Meters = f64). Its value is reached with.value. - Two structural records with the same fields are one type whatever order the fields are written in; the printer writes them in name order.
- A type definition must add something (R1); each part is allowed as
distinct type, which makes a new type with the same values, converted by its constructor (Meters(3.0), or R3 in section 6.4) and its.value:- R1a. A sum whose members, flattened (a member sum counts as its members), all come from outside its module is an alias, and an error. The module's own members are the atoms, records and wrappers it declares, and generics applied to one of them (
List[CursedType],Option[MyRecord]). - R1b. Two sums of one package whose flattened members are the same set are an error. A subset is allowed.
- R1c. A definition whose whole body is another type, a generic applied included (
type K = List[CursedType],type M = Dict[String, s64],type R = Result[T, E]), with nowhere, hides what it is, and is an error. With awhereit names a refinement, not a new type:type Positive = Int where it > 0isInt where it > 0wherever it is written (section 12.2). - R1d. A sum doesn't list another module's atom by itself (
None | Bar:Noneis core's). It may list that module's whole sum or generic sum (s64 | Option[s64] | MyAtom,std.io.IoError | ParseFailed).
- R1a. A sum whose members, flattened (a member sum counts as its members), all come from outside its module is an alias, and an error. The module's own members are the atoms, records and wrappers it declares, and generics applied to one of them (
- R4. A member of a sum that is never used is a warning in
checkand in a build, and an error inbuild --release. - A sum is a sum of types, never of variants (section 3).
A | (B | C)isA | B | C, and a member written twice is there once.Neveris the empty sum. - A type parameter in a sum is wrapped, in a
typedefinition and in a sum written in a signature (fn f[T](x: T | Missing)is refused) alike, unless it is bounded byError.type Change[T] = T | Keepis an error:Tmay overlapKeep, and the sum would then collapse for someT, so generic code would mean different things for different types. WriteKeep | Replace(T), orLeft(A) | Right(B)forA | B. A parameter bounded byErrormay stand bare, because error sums merge on purpose (section 6.8):T ! E | TimedOut. A sum a type function builds while compiling is checked on its actual member types. T?isOption[T],[]TisList[T]andA ! EisResult[A, E]: notations section 2 gives, chosen per reader. They never change the tree.- There are no implicit conversions between number types. Core's conversions are named by their target type (section 12).
6.2 Subtyping
S <: T (a value of S can stand where a T is expected) holds exactly when one of these rules gives it:
T <: T, andS <: UwithU <: TgivesS <: T.- A member of a sum is a subtype of the sum:
Circle <: Shape,NotFound <: NotFound | Denied. A sum is a subtype of a sum holding all its members. T where p <: T.T where p <: T where qwhenpimpliesq(section 8); until that is proven, the place where it is needed holds an obligation.Never <: Tfor everyT.- A record with the fields of an open record, with field types that are subtypes, is a subtype of it:
Point <: { x: f64, .. }. Two closed records are subtypes only when equal. G[S1, …] <: G[T1, …]when each argument pair agrees with that parameter's variance (section 6.3):Si <: Tifor covariant,Ti <: Sifor contravariant,Si == Tifor invariant.(a: A1) -> R1 <: (b: A2) -> R2whenA2 <: A1andR1 <: R2. Parameter names don't count. Amutparameter's type must be equal on both sides.- A type implementing a trait used as a type is a subtype of it:
Circle <: Drawablewhenimpl Drawable for Circle. A value of a trait type is the value with its impl's method table: passing aCirclewhere aDrawableis expected pairs it with that table, and aList[Circle]passed as aList[Drawable]is converted element by element, a copy--copiesreports.
A distinct type is a subtype of nothing but itself.
6.3 Variance
Each type parameter of a type definition gets a variance, computed when the type is stored, from the positions it appears in:
- A position in a field or a result is covariant. A position in a function type's parameter flips the variance around it. A
mutparameter's position is invariant. - A parameter used in covariant positions only is covariant, in contravariant positions only contravariant, in both or in none invariant.
- Through another generic type, a position composes with that type's own variance for the argument.
- Core states its built-ins' variances:
List,Dict(both parameters),Set,Option,Result,TaskandReceiverare covariant;Senderis contravariant. - The variances are part of the type's interface. A change that allows fewer subtypes (covariant to invariant, for one) changes the
interface_hashand is a breaking change.
6.4 Checking
- Checking is bidirectional. An expression is either checked against the type its place expects, or its type is inferred from its parts. Expected types flow down (into arguments, branches, elements, bodies), inferred types up.
- Signatures are written: every parameter's type, and every function's result type but
(), which a function with no->returns (section 2.3). Inference only fills the types inside a definition, with unification. A type variable that would contain itself is an error (the occurs check). At the end, every node's type is known, or the definition is refused with "write the type here". - Literals. An integer literal checked against a number type must fit it (
300againstu8is an error at edit). A decimal literal againstRealis exact; against a float type it is the nearest float, ties to even. A literal takes the type its place expects. An operator's literal operand is expected to have the type that makes exactly one impl fit: in3 * price, onlyimpl Mul[Money, Money] for s64takes aMoneyon the right, so3is ans64. When several impls fit, the literal's type is written:(3: s64) * price. A conversion's literal argument is checked by its value:u8(5)gives5,u8(300)is an error at edit. With no expected type at all, an integer literal is anInt, a decimal one aReal, a text one aString, always. - A binding's type is fixed where it is bound: the written type, or else its value's type, with literals as above and no refinement. Later uses never change it. So after
mut x := 5,x = "hello"is an error, and a variable meant to hold several types says so where it is bound:mut x: Int | String = 5. Afterx := 5,total += xwithtotal: s64is an error too: writex: s64 = 5. Andu8(x)gives aResult, whileu8(5)andx: u8 = 5don't. Unification fills the types inside expressions (a lambda's parameters, a generic call's type arguments), never a binding's. - Constructors the types decide. The stored tree holds every constructor.
viewleaves out those R2 and R3 would put back, wherever they were written, andeditputs back every one the text leaves out before storing. Both read the type each place expects and its value's type there.- R2. At a place whose expected type is a generic sum, a value that isn't one of the sum's values is wrapped in the member whose single field is a type parameter, when exactly one such member accepts it. Otherwise the constructor is written. No type is special:
Option[T]isSome(T) | NoneandResult[T, E]isOk(T) | Err(E), sof(3)for anOption[s64]parameter isf(Some(3)), and indivreturningResult[s64, DivideByZero],DivideByZeroanda / bareErr(DivideByZero)andOk(a / b).p.patched(name: "Bob")isReplace("Bob"). AResult[String, String]needs its constructor written. - R3. At a place whose expected type is
distinct D, a value of one ofD's members, or of its underlying type, becomes aD. Twodistincttypes never convert into each other. - R2 and R3 apply at most once each at a place, R3 inside R2:
3whereOption[KeyValue]is expected isSome(KeyValue(3)). - The places are results and returns, arguments (a generic built-in's when the arguments before it settle its type), fields, typed bindings and assignments to them, list and tuple elements and lambda bodies, and each branch of an
ifor amatch(and a block's last value) at one of them. A binding without a declared type (x := Replace(5)) is not a place: leaving its constructor out would changex's type. A typed binding (x: Change[s64] = 5) is one.
- R2. At a place whose expected type is a generic sum, a value that isn't one of the sum's values is wrapped in the member whose single field is a type parameter, when exactly one such member accepts it. Otherwise the constructor is written. No type is special:
- Constructors as functions. A member with fields, written as a value with no arguments, is its constructor function:
Getis(Reply[s64]) -> Get,Someis[T](T) -> Option[T]withTinferred, and a record member's fields are its parameters' names (Circleis(r: f64) -> Circle). It is stored as the member'sGlobalwith that function type. An atom is a value already. The member's type is a subtype of its sum (section 6.2), socounter.ask(Get)passes where a(Reply[s64]) -> Requestis expected. - Calls. The callee is resolved first (section 6.6 for methods), then each argument is checked against its parameter's type. Arguments are named or unnamed as section 2 says. A function type's parameter names count for calls through it and for passing a named function where a function type is expected (its names must match, or a lambda wraps it), never for subtyping.
6.5 Narrowing and exhaustiveness
- In the part of the code an
istest or amatcharm covers (the table of section 5.4), the tested variable has the narrower type: inif s is Circle { … },sis aCircle. - After an
ifone of whose branches always leaves the block (return,break,continue, a panic), the variable keeps the type the other branch narrowed it to, for the rest of the block: afterif !(s is Circle) { return },sis aCircle. !(x is V)narrows the other way: in its true part,xhas its type withoutV.- Narrowing ends at the first assignment to the variable, wherever it is narrowed: in a branch or after an exit, it holds up to that assignment and not after.
- Every
matchcovers every value of its subject's type: each member of a sum, each atom, each value of a refinement's base the patterns leave. Amatchthat doesn't is an error listing what is missing. An arm'swherecondition is a refinement of what its pattern matches (Some(x) where x > 0, orwhere 3 <= it <= 5alone, on the subjectit): a condition comparingit, its length or a bound name with constants is counted exactly, and any other is left toverify, which proves some arm matches or reports a value none does. An arm no value can reach is an error.
6.6 Traits and impls
trait Shape {
fn area(self) -> f64
fn describe(self) -> String {
f"a shape of area {self.area()}"
}
}
impl Shape for Circle {
fn area(self) -> f64 {
3.14159 * self.r * self.r
}
}
impl Circle {
fn diameter(self) -> f64 {
2.0 * self.r
}
}
- A trait has type parameters, supertraits, and methods, each with or without a default body. It has no associated types: what varies per impl is a type argument (
Mul[Int, Money]). impl Tr for TgivesTevery method ofTr. It defines each method without a default, may replace a default, and must match each signature, parameter names included. It may add parameters with defaults; a call through a bound or a trait value passes their defaults.impl T { … }, with no trait, givesTmethods of its own. It is written only inT's module.- One meaning per method call.
x.m(…)on a value of a known typeTtakesT's ownm, ormof the one traitTimplements that has anmand is visible. A type can't have its ownmand a trait'smboth (an error where the second is declared). Two traits givingTanmmakex.m(…)an error naming both;Tr.m(x, …)says which. On a value whose type is a type parameter,x.m(…)takesmfrom the parameter's bounds (aBoundtarget). On a trait value, it is aDynamiccall. - Coherence. For a trait with its arguments and a type, there is at most one impl in the program. Two impls that could apply to one type are an error, wherever they are.
- The orphan rule. An impl is written in the package of its trait, of its target type (for an applied generic, the generic's package), or of a type among the trait's arguments:
impl Mul[Money, Money] for s64, giving3 * price, lives inMoney's package. A blanket impl,impl[T: Bound] Tr for T, is written only inTr's package, and it is part ofTr's interface. - Core's
Eq,Hash,DebugandDisplayhave a structural impl for every type whose parts all have one. Functions, capabilities (foreign handles among them), and types holding aSharedor aWeakhave noEqorHash;same(a, b)compares the last two by identity. A type's own impl of one of them replaces it; this is the one replacement core allows. - A trait can be used as a type when its methods mention
Selfonly as their receiver and have no type parameters of their own.
6.7 Generics
fn largest[T: Ord](items: List[T]) -> Option[T] { … }
type Change[T] = Keep | Replace(T)
type Patch[T: Record] = Record { fields: [Field { name: f.name, _type: Change[f._type], public: f.public, default: Some(Keep) } for f in T.fields] }
- A function or type has type parameters, each with bounds (traits, or an open record). A value parameter (
R: s64) takes an integer,Boolor atom. - Type arguments are never written at a call. They are inferred from the arguments and the expected type, and must all be known.
- A generic function is checked once, for every type meeting its bounds: its body uses only the bounds' methods and fields. It is verified once the same way (section 8), and compiled once per type it is used with (section 10).
- In generic code, value arguments are compared after normalizing linear arithmetic (
R + 1,2 * C). Anything else is an error asking for a simpler form. - Type functions. A
typedefinition with parameters whose value is an expression computes a type while compiling. It must be proven to terminate when it is stored (section 8). A type it makes is identified by the function's key and its arguments' keys:Patch[User]is the same type wherever it is written. comptime. Acomptimeparameter is a value known while compiling.comptime eevaluatesewhile compiling; an expression that can't be is an error where it is.comptime forunrolls a loop over a list known while compiling.- Keys and hashes while compiling.
key_of(x)gives theKeyof whatxnames: a definition (key_of(area),key_of(Point)), a type or atom declared in a sum (key_of(Circle)), or a field (key_of(Point.x)).interface_hash(x),code_hash(x)andtext_hash(x)give a definition's hashes (section 4.7). Each is evaluated while compiling and gives a constant that run-time code may use. Applied to anything without an id (a local, an expression), it is an error where it is written.- A key is stable through edits and renames, so it refers to the same definition in the proof kernel (section 8), in derived code and in stored data, one to one.
- Reading a hash makes that definition a dependency of the reader, so a change to it is seen through the reader's stamp. A definition can't read the hash of itself or of a definition that depends on it.
Keyis a core type withEqandHash(section 12).
6.8 Errors
Option[T]andResult[T, E]are core's sums:Some(T) | NoneandOk(T) | Err(E).- The error side is usually a sum of error types:
Result[Config, NotFound | Denied | BadToml], writtenConfig ! NotFound | Denied | BadToml. Equal types merge:NotFound | NotFoundisNotFound. x!givesx's success value, or returns its error from the function; each of the error's types must be a member of the function's error type.x?does the same forNonein a function returning anOption.x except { b },x except e { b }andx except { Pattern => … }handle errors (section 2). Arms that cover some of the error's types leave the rest as errors: the result is then aResultof what remains.- A pattern
e: NotFoundmatches the memberNotFoundof an error sum and binds it narrowed. - An error type implementing core's
Errorcarries a trace: the places it was raised and passed through, each!adding one, readable ase.trace. The trace takes no part in==orHash: two errors equal but for their traces are equal. This is the one exception to section 7.2's rule that equal values can't be told apart: a trace is read for debugging, never to decide what a program computes. - A panic is not a value and has no type. Section 7 says what panics.
6.9 Capabilities
- A capability is a value whose type implements core's trait
Capability, which has no methods:trait Files: Capability { … }. - Capabilities come from four places only: the runtime gives them to
main's and a test's parameters; a capability's methods may return capabilities (net.connect()gives aTcpStream); a foreign library's calls return handles (section 11.2); amockof a capability trait makes one, in tests only. No other code makes one. A capability may come inside anOptionor aResult, held as the capability is. - A capability is held only in parameters and locals. A named record can't hold one in a field. Several travel together only as a structural record holding nothing but capabilities:
cap io: { files: Files, net: Net }. - A lambda can't capture a capability. A lambda that needs one takes it as a
capparameter. So a function value reaches the outside world only through the capabilities its caller passes it, and a function type with nocapparameter reaches none (it may stillspawninto an enclosing scope, section 9.1, and callpureexterns). - A lambda captures the values of the variables it uses when it is made. A
mutvariable it uses is read then, and the lambda can't assign it: changes go through amutparameter. - Capabilities and tasks. A
spawnmay use the capabilities in scope, each passed with its mark. It isn't amutcapture: the task gets the capability as a capture shared by the scope (section 10.5), which the spawned task never counts, so no count is ever changed from two threads.- A capability whose methods change no Strata state of its own (std's: their state is the operating system's or the runtime's, and each call is one request to it) may be given to several tasks at once.
- A capability whose methods change state of its own (a
mock … with Ghost, a program's own capability with fields it writes) is lent to one task at a time: while a task of the scope holds it, no other task and not the spawner may use it, until that task is awaited.editchecks it. A capability changes state of its own when one of its methods takesmut self, which its trait's signatures say, so a capability known only by its trait is judged the same way.
- Marks. A capability parameter is declared
cap name: T, and is passed in place, as amutparameter is (capimpliesmut). A call passing one writescap x; a call passing amutparameter writesmut x. The marks are not stored: they are the callee's parameter modes. The printer always writes them, andeditrefuses text that leaves one out or writes a wrong one. This holds for every call, through a bound or a trait value too:mut x.push(v)wherex: TandT: Stackasks the mark, sinceStack.pushtakesmut self. A method called on a capability (console.print(…)) needs no mark on its receiver: the receiver's type says it is one. - Capability code is the methods of an impl of a capability trait for a concrete type (std's
Console, a binding's library): the one place a program meets the outside world, and the only placeassumedmay be written (section 8.1). - A capability passed must be used. A function given a capability it never uses, itself or through a callee, is an error naming the parameter;
strata fix --deadremoves it. Each field of a record of capabilities counts on its own. A method of a trait's impl, and a lambda passed where a function type is expected, are exempt: their signature is fixed by the trait or the type. - A function with no capability parameter, no call of an
externother than apureone (section 11.1), nospawnand no channel operation (send,recv,select,race,await) is pure. Core's own calls intocore.runtimefor memory (allocation, counts) don't count: they change no result (section 10). Purity is worked out over the calls' stored targets (section 3.4), to a fixed point.viewshows which functions are. - Output needs a capability:
printis a method ofConsole. Onlydbgwrites without one, and it is removed from every build butstrata run --debug.
6.10 Mocks
mock T, in a test, makes a value implementing the traitTwhose methods do nothing: each returns(),None,Ok(())for aResult[(), E], theErrof its error type's do-nothing member for any otherResult(the one the type names, else the first whose fields all have zeros), or the zero of its result type (numbers 0,false,"", empty collections, records of their defaults and zeros). A method whose result has no zero (a sum outsideErr, a trait, a type parameter, a function, a refinement the zero doesn't meet) is an error naming it.mock T with GhostsimulatesT's ghost state: it holds each ghost value, starts from its zero, and each method gives the result and the next ghost values itsensuresdetermine; a method whoseensuresdon't determine them is an error naming it.mock T with Generatedgives, for each call, a generated result meeting the method'sensures.Ghost,GeneratedandDoesNothingareMockBehaviour's atoms, not keywords. A test reads a ghost mock's ghost state as fields of the mock (console.written), which only tests may do.- A test's capability parameters get a do-nothing mock of their type, unless the type is a concrete capability the runtime gives tests (
Filesgets a temporary folder,ClockaVirtualClock,RandomaSeededRandom: section 13.1; a folder). - Each do-nothing method's contracts and the trait's laws are proven at the mock (section 8). One that fails is an error naming the method and the clause.
6.11 Mutability
- A binding is immutable unless declared
mut. Amutparameter is passed in place: the callee's changes are made to the caller's variable. Its argument must be a place: amutvariable, amutparameter, a field of one, or an element (bump(mut xs[i])). - Two
mutarguments of one call can't overlap, and amutargument can't overlap another argument of the call:f(mut xs[i], len(xs))is an error; bindn := len(xs)first. - No reference to a value can be stored or returned: a
mutparameter is the only way to change something the caller holds. - Mutability belongs to the variable. A
mutvariable reaches everything it holds: its fields, its elements, their fields. There is nomutinside a type (List[mut T]) or a comprehension. Fields that must never change are kept so by the type's API, not by a mark. f(mut xs[i])lends one element: it is taken out of the list when no other argument refers to the list, changed by the callee, and set back withIndex.setafter the call.Shared[T]andWeak[T]are section 10's, and so isOwned[T](section 10.7, to try in the lab), whose moves are writtenmove xand checked by the same path analysis as section 9.3's duty to close.
6.12 Laws
Sketched. Those about the checker are proven on its code. Those about running programs (marked run) are proven against section 7's model: they are what makes the checker's answers true.
// subtyping is a preorder
law subtype_reflexive(t: Type) holds subtype(t, t)
law subtype_transitive(a: Type, b: Type, c: Type)
requires subtype(a, b) && subtype(b, c)
holds subtype(a, c)
// at most one impl for a trait with its arguments and a type
law one_impl(p: Program, tr: TraitApplication, t: Type)
holds count(impls_for(p, tr, t)) <= 1
// a method call resolves to exactly one target, or is refused
law one_target(p: Program, c: Call where stored(it))
holds count(targets(p, c)) == 1
// every stored match covers its subject's type
law matches_exhaustive(m: Match where stored(it))
holds covers(m.arms, m.subject._type)
// key_of gives each definition its own key, and different definitions different keys
law ids_one_to_one(a: Definition, b: Definition)
holds (key_of(a) == key_of(b)) == (a == b)
// a sum's members never overlap, except error types meant to merge
law sum_members_disjoint(s: SumType where stored(it), a: Type, b: Type, i: u32, j: u32)
requires i != j && member(s, i) == a && member(s, j) == b && !(is_error(a) && is_error(b))
holds disjoint(a, b)
// a hash read while compiling is the hash the definition has
law hash_read_is_current(reader: Definition, d: Definition)
requires reads_hash(reader, d)
holds hash_read(reader, d) == code_hash(d) && depends_on(reader, d)
// every capability parameter is used, itself or through a callee
law capabilities_used(f: Function, p: Parameter where it.mode == Capability)
holds uses(f, p)
// a function shown as pure reaches no capability, extern call other than a pure one, or spawn
law pure_is_pure(f: Function where shown_pure(it))
holds !reaches_capability(f) && !reaches_impure_extern(f) && !reaches_spawn(f)
// run: a value has its node's type (preservation)
law values_have_their_types(d: Definition where stored(it), n: NodeIndex, run: Run)
requires evaluates(run, d, n)
holds has_type(value_at(run, d, n), type_of(d, n))
// run: a narrowed variable holds a value of the narrowed type where the narrowing holds
law narrowing_holds(d: Definition, v: NodeIndex, at: NodeIndex, run: Run)
requires narrowed(d, v, at)
holds has_type(value_of(run, v, at), narrowed_type(d, v, at))
// run: a variance computed for a parameter is safe for every subtype pair
law variance_safe(g: TypeDefinition where covariant(it, 0), s: Type, t: Type)
requires subtype(s, t)
holds subtype(apply(g, [s]), apply(g, [t]))
7. Semantics
What a program does when it runs. Section 8 says which of the checks below are proven away; whatever isn't proven runs as written here.
7.1 Evaluation order
Evaluation is strict, and goes left to right in the order the text is written:
- A call evaluates its callee (the receiver of a method call first), then its arguments in parameter order, which is the order they are written (section 2.6), then defaults for the parameters left out, in parameter order, then calls.
- An operator evaluates its left operand, then its right.
&&,||and==>evaluate their right side only when the left doesn't decide;<=>evaluates both. - A chained comparison
a < b <= cevaluatesa,bandconce each, in that order, and stops at the first comparison that fails. - A record literal evaluates its
...rbase first, then its fields in the order they are written, which is the order the type declares them (section 2.7). A list, tuple or dict literal evaluates its elements in order. - A block runs its statements in order, then gives its last expression.
ifevaluates its condition, then one branch.matchevaluates its subject once, then tries the arms from the first: the first whose pattern matches and whosewherecondition holds runs.- A pipe is the nested calls it stands for (section 2.6), and evaluates as they do, arguments in parameter order:
a() |> f(b(), _)runsb()beforea(). Binda()first to run it first. A spreadf(...r)evaluatesronce, before the arguments around it.
7.2 Values and bindings
- A value never changes.
ys := xsgivesysthe same value asxs, and nothing done later toxschangesys. Whether the program copies or shares memory underneath (section 10) can't be observed. x := ebindsxtoe's value for the rest of the block. Amutvariable may be assigned again:x = egives ite's value from then on.- A
mutparameter is passed in place: when the call returns, the caller's place holds what the callee left in it. Sincemutarguments never overlap anything else in the call (section 6.11), this is the same as copying the value in and back out. ==on two values of a type with core's structuralEqcompares them part by part. Values have no identity: two equal values can't be told apart.- Defaults are evaluated at each call that leaves the parameter out, in the callee's scope, after the given arguments. A record field's default is evaluated at each literal that leaves the field out.
7.3 Numbers
- Machine integers (
s1…s128,u1…u128) hold their range exactly. An arithmetic operation whose exact result is outside the range panics. Wrapping and saturating arithmetic are separate, named methods (section 12). - Bit operations (
&,|,^,<<,>>) never panic. A shift drops the bits shifted out; a shift by the width or more gives 0, or, for>>on a signed number, all sign bits. Rotations are named methods (rotate_left,rotate_right). Intis an integer of any size;Naturalis its refinementInt where it >= 0(section 12.2), son - 1withn: Naturalis anInt, and giving it to aNaturalis an obligation.Realholds exact rationals.- Division.
/and%on integers are Euclidean:a == b * (a / b) + a % band0 <= a % b < |b|, so-7 / 2 == -4and-7 % 2 == 1. Division by zero panics. - Floats (
f16,f32,f64,bf16) hold finite values only. Each operation rounds to nearest, ties to even, as IEEE 754 does; one whose result would be NaN or infinite panics. So==is an equivalence and<a total order on floats. There is no negative zero: an operation whose IEEE result is-0.0gives0.0, so equal floats print and hash alike.f64,f32andf16compute in their own format.bf16computes each operation inf32and rounds the result back tobf16.- Each format's limits (an exact result at or past the overflow threshold rounds to infinity, so it panics; section 8 makes these the obligations):
| format | largest | overflow threshold | relative error of one rounding | half the least subnormal |
|---|---|---|---|---|
f64 | 2^1024 − 2^971 | 2^1024 − 2^970 | 2^-53 | 2^-1075 |
f32 | 2^128 − 2^104 | 2^128 − 2^103 | 2^-24 | 2^-150 |
f16 | 65504 | 65520 | 2^-11 | 2^-25 |
bf16 | 2^128 − 2^120 | 2^128 − 2^119 | 2^-8 | 2^-134 |
- A decimal literal rounds to its type's format; one that rounds to infinity is an error at edit.
- A float is shown as the shortest decimal that reads back as the same value in its format.
- Formats don't mix:
a + bwith anf32and anf64is an error; one is converted first.
7.4 Strings
A String is always valid UTF-8. It is made from bytes only by a function that checks them and returns a Result (section 12). Positions in a string are byte offsets, and a string isn't indexed by [ ]: its parts are read by named functions (bytes, code points, graphemes).
7.5 Errors and panics
- An expected failure is a value: an
Optionor aResult(section 6.8), passed on with!and?and handled withexceptandor. - A panic stops the task at once. In a task that isn't supervised it ends the program (section 9.2); under
strata test, the test. It prints its message and the trace of calls that led to it. Nothing catches a panic but supervision. - A program panics when:
- an integer operation overflows, or divides by zero;
- a float operation would give NaN or infinity;
- an index is out of range;
- an unproven
requires,ensures, refinement orassertis false when checked (section 7.6); panic(message)runs;- a
matchwhose arms the checker couldn't show cover every value (awherearm left toverify, unproven) meets a value none matches; - a task's stack overflows, or memory runs out;
- every task waits forever (a deadlock, section 9.7).
panic(message)is core'sfn panic(_message: String) -> Never, for a state the code holds impossible. Section 8 must prove it unreachable, as any other check; until it does, the call stays and is reported as unproven.
7.6 Checks
Every condition the program states or the language implies (section 8 lists them) is either proven, and then never runs, or checked when the program reaches it. Where each unproven one is checked:
- a
requires, at the call, after the arguments are evaluated; - an
ensures, when the function returns, with eachold eevaluated when the function was entered; - a refinement, where a value is given the refined type: a call's argument, a return, a binding, a field, a conversion;
- an
assert, where it is written; an unproven loopinvariant, before the first pass and after each pass (onceverifyhas proven it, it is never checked); - an implicit check (overflow, division by zero, range, a float's finiteness), at the operation.
assumed contracts are never checked: they are trusted, and verify tests them (section 8).
7.7 Compile time and debugging
comptimecode runs while compiling, with this section's meaning. It has no capability, so it can't reach the outside world, and it must end: a type function is proven to terminate (section 6.7), and other compile-time code that runs too long is an error where it is written.dbg eprints understrata run --debugand does nothing anywhere else (section 2.8).
7.8 Laws
Sketched, about running programs: proven against a model of this section, the reference the compiler, the prover and core's contracts are checked against.
// equal arguments give equal results to a function without capabilities
law pure_is_deterministic(f: Function where shown_pure(it), a: Arguments, b: Arguments)
requires a == b
holds call(f, a) == call(f, b)
// Euclidean division
law euclidean(a: Int, b: Int where it != 0)
holds a == b * (a / b) + a % b && 0 <= a % b < abs(b)
// a value bound once never changes
law values_never_change(run: Run, x: Binding, at: Time, later: Time)
requires at <= later && !mutable(x)
holds value_of(run, x, at) == value_of(run, x, later)
// a float operation gives a finite value or panics
law floats_stay_finite(run: Run, op: Operation where is_float(it))
holds is_finite(result(run, op)) || panics_at(run, op)
// a check is left out of the compiled code only when it is proven
law checks_removed_only_when_proven(d: Definition, check: NodeIndex)
requires !compiled_check(d, check)
holds proven(d, check)
// a mut argument holds what the callee left in it
law in_place(run: Run, c: Call, p: Parameter where it.mode == Mutable)
holds after_call(run, c, place_of(c, p)) == at_return(run, c, p)
8. Verification
What verify proves, how, and what a verdict means. Every condition a program states or the language implies is an obligation. A proven obligation is never checked at run time; one that isn't proven runs as section 7.6 says. Proving never changes what a program computes.
8.1 Obligations
verify makes one obligation for each of these, keyed by its node (section 3.1):
- Written conditions:
- a callee's
requires, at each call; - a function's
ensures, at each of its returns; - a refinement, wherever a value is given the refined type: an argument, a return, a binding, a field, a conversion, a subtype
T where p <: T where q(section 6.2); - an
assert, where it is written, and a loop'sinvariant, on entry and after each pass; - a law (section 8.4), and each trait law at each impl of the trait;
- the contracts of a mock's do-nothing methods, and its trait's laws, at the mock (section 6.10).
- a callee's
- Implicit conditions (section 7):
- an integer operation stays in its type's range, and a divisor isn't zero;
- a float operation's exact result stays below its format's overflow threshold (section 7.3);
- an index is in range (
Index.at,Index.set, slices); panic(message)is unreachable;- an extern's
requires, and aCString's refinement, at each call (section 11.1).
- Termination: a function whose body a proof sees through, and every type function (section 6.7), ends (section 8.3).
- Correctness is total. A function's
ensuresproven means: it holds, and the function ends. A function whose termination isn't proven gets the verdict "proven if it ends", which--require provendoesn't accept. - Outside the logic (
verifymakes no obligation): a capability's own effects, a non-pureextern'sensures(callers' proofs trust them, and each call checks them after it returns, section 11.1), and the conditions the checker decides at edit (types, exhaustiveness, the duty to close).
assumed is written only in capability code, where a contract states what the outside world does. An assumed contract is trusted and never checked; verify --assumed lists every one.
8.2 The ladder
Each obligation climbs until a rung proves or refutes it. A rung that can't decide passes it up.
| rung | what | decides |
|---|---|---|
| 1. static | one pass over the typed tree: integer ranges, values known nonzero, difference bounds x - y <= c, lengths, Booleans, the variants a value may be made by | deterministic, no search; proves or refutes, else passes up |
| 2. solver | Z3 under a budget of 2M resource units per query, on hash-consed terms | proves, refutes with a counterexample, or passes up when the budget is spent |
| 3. kernel | a written proof (section 8.4), checked by the kernel (section 8.5) | proves, or fails with the step and goal |
| fuzzing | random inputs meeting the requires, for what no rung decided | reported as fuzzed, never as proven |
- The order for one obligation:
- a law or
assertwith a written proof goes to the kernel alone. A failed proof is reported with its step and its goal, and the solver is never asked; by autoruns the kernel's ownautofirst, then the ladder from rung 1;- an obligation with no proof starts at rung 1.
- a law or
- Quantifiers. A quantifier the encoder adds (an
allover a list, every key of a dict) is instantiated by the encoder at the positions the code reads, so the solver gets ground facts only. Where that doesn't prove it, the obligation is reported as needing a lemma (rung 3), never sent again with the quantifier. A quantifier a person writes (a law's parameters,holdsover a generic) goes to the kernel. - Arithmetic in the kernel is our own procedure for linear integer arithmetic, which produces kernel steps. Other theories (nonlinear arithmetic, bit vectors) reach Z3 as named oracles, recorded in the theorem's basis (section 8.6).
- Verdicts. Each obligation gets one: proven (by which rung), proven if it ends (section 8.1), refuted (with a counterexample), fuzzed, unknown, or a failed proof. Termination is part of an
ensuresonly: a function meant to run forever (a server's loop) states noensuresabout its end, and its other obligations are proven as usual.verifyprints each with its rung ([static],[z3],[kernel]), and ends with the count per verdict.--require provenfails on any verdict but proven.--rung static,--rung z3or--rung kernellets only that rung decide, and leaves the rest unknown. - Vacuity.
verifyalso reports arequiresthat no value meets, and anensuresthat the types alone imply: both say nothing.
8.3 What the logic means
The solver and the kernel read a program through one translation of its stored tree. Its meanings:
- Values. Integers are mathematical integers, with each machine type's range as a fact. A float is the real number it holds exactly; each operation's result is the exact result rounded, its error bounded by its format's (section 7.3);
==and<on floats compare those reals. AStringis a sequence of bytes that is valid UTF-8. - Collections. A
List[T]is a sequence. ASet[T]is a membership predicate,(T) -> Bool, and two sets are equal when they have the same members. ADict[K, V]is a function(K) -> Option[V]; itsitems()have no order in the logic.xs[i]out of range is an unknown value: the obligation that it is in range is separate. - Core's functions (
len,map,filter,sorted, …) are Strata code with their own names in the logic, never clashing with a module's ownallorcontains. Core's built-ins that are C have models in core, tied to the C by contracts thatverifyfuzzes (section 11.1). - Refinements are facts wherever a value has the refined type. In a kernel proof they are hypotheses, assumed at the binder. A refinement the logic can't state (a regular expression, a length in graphemes) is left out: the obligation that needs it stays unknown and is checked at run time.
- Calls. A call is known by its callee's contracts. Its body is seen through only when the callee is non-recursive, or its termination is proven: a body is used in a proof only once it is known to end. Two calls of a pure function (section 6.9) with equal arguments give equal results, except across a write to a
Shared(section 10.6). Calls that reach a capability, a non-pureextern or a channel are never assumed equal. - Loops. A
forloop that changes one variable is a fold over its elements, and gets anensuresover the elements visited. A loop that changes several variables is a fold over a tuple of them (to try in the lab). Any other loop is known by its invariants.verifyandbuildnever search for invariants:editandfixdo, and write what they find. - Termination is proven in order: structural recursion on a sum, then a measure inferred from the code, then a written
decreases. A traversal of a tree throughchildren(section 3.1) terminates by the lawchildren_smaller. - Generics. A generic function or law is proven once, for every type meeting its bounds, from the bounds' contracts and laws only (parametricity). The proof holds for types written later. A law over every record (the
Patchlaws) is proven once over the record's fields, in the kernel. - Keys. Every constant in the logic is named by its definition's key (section 3.1): a rename changes no proof. Generated items take keys derived from their parent's (a recursor, a constructor, an equation lemma: parent, part, index), and a made type (
Patch[User]) the key of its type function with its arguments' keys. Locals and lambdas need no names.
8.4 Laws and proofs
/// Appending is associative.
law append_associative[T](a, b, c: List[T])
holds (a + b) + c == a + (b + c)
by {
match a {
[] => simplify,
[head, ..rest] => {
append_associative(rest, b, c)
simplify
},
}
}
trait Hash: Eq {
fn hash(self) -> u64
law agrees_with_eq(a, b: Self)
requires a == b
holds a.hash() == b.hash()
}
impl Hash for Point {
fn hash(self) -> u64 {
combine(self.x.hash(), self.y.hash())
}
law agrees_with_eq by auto
}
lawis the one form for a named, proven statement. Its parameters are what it holds for, itsrequiresits hypotheses, andholdsits statement: an expression, or a block ending in one (so amutmethod can be stated withoutold). With noby, the ladder proves it.- Where a law sits says who proves it.
- At the top level, it is a theorem, proven once. A generic one must follow from its bounds' laws; if it doesn't, that is an error, never a new obligation on callers.
- In a trait, it is an obligation each impl meets, written
law name by …in the impl, or left out for the ladder. A trait that adds a requirement across traits names the other as a supertrait (trait Hash: Eq). - A trait's invariant is a law over
Self.
- A proven law is a fact. Callers use it by name (
by l(a, b), a linel(a, b),simplify by l), and the ladder uses the laws of the types in an obligation. - Induction is recursion. A proof splits a value with
matchand calls the law on a smaller value in a recursive arm, asappend_associative(rest, b, c)above. The call is checked to terminate like any recursive call. A condition is split withif.
Proof steps.
proof = step | proof_block ;
proof_block = "{" [ proof_line { newline proof_line } ] "}" ;
proof_line = step
| "match" expression "{" { pattern "=>" proof "," } "}"
| "if" expression proof "else" proof ;
step = "simplify" [ "once" ] [ "by" expression { "," expression } ]
| expression
| "unfold" identifier { "," identifier }
| "witness" expression
| "assume" [ expression ]
| "lemma" identifier ":" expression "by" proof
| "calc" "{" { [ relation ] expression [ "by" proof ] newline } "}"
| "arithmetic" | "nonlinear" | "bits" | "compute" | "auto" ;
relation = "==" | "<" | "<=" | ">" | ">=" ;
| step | does |
|---|---|
simplify by l1, l2 | rewrites the goal with the named laws, and the definitions in scope, until nothing changes; simplify once by l rewrites once |
l(a, b) | a law, or a named hypothesis, at those arguments: on a line, adds its statement as a fact; as the last line, or as by l(a, b), closes the goal when its statement matches it, its requires becoming goals |
unfold f | replaces calls of f by its body |
witness e | gives the value for an exists |
assume p | takes p as a hypothesis; the goal becomes p ==> goal |
assume | closes the goal by trusting it: allowed only in capability code and notes modules (section 11.2), and listed by verify --assumed |
lemma h: p by … | proves p and names it h for the rest of the proof |
calc { a == b by … < c } | a chain of equalities and inequalities, each step with its own proof |
arithmetic | linear integer arithmetic, after simplifying the facts |
nonlinear, bits | nonlinear arithmetic, bit vectors (Z3 as a named oracle) |
compute | evaluates the goal |
auto | the ladder |
- There is no
useorexact: a law written as a call is the step.useis only the import keyword. - There is no
intro: hypotheses are named inrequires, and the variables are the law's parameters. Afor allor==>inside a goal is stated as a lemma with its own parameters andrequires. assert p by proofin a function body provespthere, with the facts of that point.- Proofs are erased from compiled code. A law and its proof are definitions like any other: stored in their module, hashed, merged.
8.5 The kernel
- The kernel checks written proofs. Its logic is a dependent type theory with inductive types and their recursors, chosen over higher-order logic in the lab: its trusted part is smaller, it proves a law once for every record where higher-order logic needed a proof per type.
- The trusted part,
kernel_core: terms, type inference, reduction and conversion, inductive types and recursors, the built-in constants and axioms, and the three ways to add a constant (define,declare,add_inductives), each checking that its terms are closed and well typed. It has no name table: constants are numbered, and named only in messages. - Everything else is untrusted and checked by it: the proof checker (names to constants), the translation from the stored tree, the proof steps, the arithmetic procedure. Each untrusted function states, as a proven contract, that its answer is
kernel_core's. - Datatypes are made from the program's types by one function,
datatype_of(T: Type), over the same type values as section 6.kernel_corestill checks each one it is given. - Axioms are definitions: each is a function of the statements it is about, returning the theorem (
and_gives_left(p, q)), built as kernel terms. A law's text never makes an axiom. - A proof's term is cached by the law's keyed code hash (section 8.3), and a term read from the cache is checked again.
8.6 What is trusted
A verdict "proven" rests on:
kernel_core, for rung 3;- Z3, for rung 2 and for the named oracles of a kernel proof. Checking Z3's proof objects in the kernel is a later option;
- the contracts of core's runtime externs (
core.runtime), and of any extern a proof relies on; - the
assumedcontracts of capability code (section 8.1); - the compiler, for compiling what was proven.
Rung 1 is not trusted on its own word: it is Strata code whose laws (its ranges' join, the soundness of each operation on them) are proven by the kernel alone, verify --rung kernel, with written proofs. So its soundness rests on kernel_core, never on itself or on Z3.
8.7 The proof cache
- A package keeps its verdicts in one file,
strata.proofs, besidestrata.toml. For each obligation it holds the definition's code hash and stamp, the obligation's node, the verdict, and the rung that gave it. - A verdict is reused when the definition's code hash and stamp are the ones it was found with, and the prover's version is the same. The compiler's own build doesn't enter the key: rebuilding
stratainvalidates nothing. - When a stamp changes, the obligations of that definition are proven again; the others' verdicts stand.
verifythen costs about the work of what changed. - With each Z3 verdict it also keeps the obligation's unsat core: the names of the few facts the solver used. After an edit that changes a stamp,
verifyasks the solver again with those facts and the facts of what changed, and falls back to the full query only if that fails. A core is a speed aid, not a proof: it is never checked as one. - The file holds no proofs. It is a local cache, never committed (
strata newadds it to.gitignore): it can be deleted at any time, and the nextverifyproves everything again. What a release ships is its certificate (section 8.8).
8.8 Certificates
- A certificate is a file holding the proofs themselves, so a reader can check a release's verdicts without trusting the machine that found them. It is made only on request:
strata build --release --certifywritesNAME.certificatebeside the executable. - For each obligation proven:
- by rung 1: nothing more; the static step is deterministic and is run again to check;
- by rung 2: the facts the solver used (its unsat core), each named by origin, stamp and a hash of its term, so the solver is asked again on those facts alone;
- by rung 3: the kernel term, checked again by
kernel_core.
- Tying it to the executable. The certificate records the executable's SHA-256, the compiler's version and hash, and the code hash of every definition compiled into it. A build is reproducible: its bytes depend only on the code and the compiler. So a reader rebuilds from the source, compares the hash, and checks the proofs. Signing a certificate is outside this specification.
strata check-certificate NAME.certificatedoes that check and reports each proof that doesn't replay.
8.9 Nodes
Section 3 gains:
type Definition =
…
| Law {
type_parameters: List[TypeParameter],
parameters: List[Parameter],
_requires: Option[Expression],
_holds: Expression,
proof: Option[Expression],
}
type LawProof = { _law: Key, proof: Option[Expression] }
type Statement =
…
| Simplify { laws: List[Expression], _once: Bool }
| Fact { _law: Expression }
| Unfold { functions: List[Key] }
| Witness { value: Expression }
| Assume { condition: Expression }
| Lemma { condition: Expression, proof: Expression }
| Calc { first: Expression, steps: List[CalcStep] }
| Decide { procedure: Procedure }
type CalcStep = { relation: Key, value: Expression, proof: Option[Expression] }
type Procedure = | Arithmetic | Nonlinear | Bits | Compute | Auto
- An
Implgainslaws: List[LawProof], a field like its models.Assertgainsproof: Option[Expression]. - A proof is an
Expression: aBlockof proof statements, or aMatchorIfwhose arms are proofs. A single stepby sis a block holdings. - A
Lemmabinds its name inlocal_names. ALaw's body is its proof, numbered last as a body (section 3.1). - Section 4's tags:
Lawis 7 among the definitions; the proof statements are 71 to 78 in the order above.
8.10 To measure in the lab
The rules of sections 8.7 and 8.8 bind; the lab measures how they perform:
- A loop that changes several variables as a fold over a tuple of them.
strata.proofskeyed by code hash, stamp and prover version, with the rung recorded.- Certificates: written with
--certify, checked bycheck-certificate, on a release of the compiler. - Reproducible builds checked from a second machine.
8.11 Laws
Sketched. Those marked checked are proven on the compiler's code; the others are about running programs, proven against section 7's model.
// checked: a proven obligation's check is not in the compiled code
law proven_removed(d: Definition, o: Obligation where verdict(it) is Proven)
holds !compiled_checks(d).contains(o.node)
// a proven obligation holds on every run that reaches it
law proven_holds(run: Run, o: Obligation where verdict(it) is Proven)
requires reaches(run, o.node)
holds condition_holds(run, o)
// checked, by the kernel alone: rung 1 never proves what is false
law static_sound(o: Obligation where static_answer(it) is Proven)
holds valid(o)
// checked: every untrusted kernel function agrees with kernel_core
law checker_agrees(env: Environment, name: Name, term_type, value: Term)
holds define(env, name, term_type, value).map(core) == kernel_core.define(core(env), name, term_type, value)
// checked: a cached verdict is used only for the code it was found for
law cache_exact(entry: CachedVerdict, d: Definition)
requires used_for(entry, d)
holds entry.code_hash == code_hash(d) && entry.stamp == stamp(d)
// a renamed definition keeps every proof
law rename_keeps_proofs(m: Module, id: Id, name: Name, o: Obligation)
holds verdict_in(rename(m, id, name), o) == verdict_in(m, o)
// checked: a certificate's proofs replay on the code it names
law certificate_replays(c: Certificate, source: Package)
requires executable_hash(build(source)) == c.executable
holds c.proofs.all(p -> replays(p, source))
9. Concurrency
Tasks are structured and have no colour: any function can start tasks and wait for them, and no function is marked async. A task lives inside the scope that started it. Tasks talk through channels. No value is shared mutably between tasks, and no object is counted by two threads.
9.1 Scopes and tasks
total := scope {
a := spawn sum(left)
b := spawn sum(right)
await a + await b
}
scope { body }runs its body, then waits until every task spawned in it has ended. Its value is the body's.spawn estarts a task that evaluatese, and gives its handle, aTask[T]whereTise's type. Aspawnmust be written inside ascopeblock of the same function, a lambda's body included, so a task never outlives the call that started its scope. A helper that sets up a long-lived task (an actor, a pool) returns its parts, and its caller writes thespawn(section 9.6).- A task has its own stack (section 9.10), of the program's size or the one a spawn asks for:
spawn(stack: mebibytes(64)) search(tree)(section 2.6). Where it runs is the runtime's choice, or the one a spawn asks for withon:(section 9.9). await hwaits for the task and gives its value.awaiton a tuple or a list of handles waits for all of them and gives a tuple or list of their values, in the same order.- A handle can't leave its scope: it can't be returned from it, stored in a value made outside it, or captured by another task. A task never awaited still runs to its end before its scope ends, and its value is dropped.
- A spawned expression is a body of its own.
return,!and?in it end the task with that value;breakandcontinuecan't leave it. - A lambda whose body spawns into an enclosing scope can't leave that scope, as a handle can't: it can't be returned, stored outside it, or captured by a task.
- A task captures the values it uses. Each crosses as section 9.6 says. A
mutvariable ormutparameter can't be captured by a task.
9.2 Panics and supervised tasks
- A panic in a task that isn't supervised ends the program: every task stops. Under
strata test, it ends only the test that started the task. supervised spawn estarts a supervised task.await hon its handle givesResult[T, Panic].- When a supervised task panics, every task it started stops at its next cancellation point (section 9.5), and its copies of senders close (section 9.3). Its siblings and the task that started it go on, and
awaitgivesErr(panic). - A panic in a task started by a supervised task, not itself supervised, counts as the supervised task's panic.
- A stack overflow is a panic of the task that overflowed, like any other, caught by a guard page below its stack.
9.3 Channels
(tx, rx) := channel()
scope {
for url in urls {
spawn {
tx.send(fetch(url)) except return
}
}
tx.close()
for page in rx { save(page) }
}
channel()makes a channel and gives its two ends,(Sender[T], Receiver[T]).Tis inferred from how the ends are used, or written on the binding.channel()has no buffer: asendwaits until arecvtakes the value.channel(capacity: n)has room fornvalues,n > 0.- Any number of tasks may hold a copy of either end. A copy given to a task is that task's copy.
send(self, value: T) -> Result[(), NoReceiver]waits until the value is taken, or there is room. It givesErr(NoReceiver)once every copy of the receiver is gone, and drops the value.tx.send(v) except returnends the task then (section 2 gives the formexcept+break,continueorreturn).recv(self) -> Option[T]waits for a value. It givesNoneonce every copy of the sender is closed and nothing is left to take.for v in rxtakes values untilNone.close(self)closes this holder's copy of the sender. The channel ends for its receivers when every copy is closed.- The duty to close follows the sender. A value whose type holds a
Sender(a sender alone, or inside a record, tuple, list or sum) carries the duty to close it.Senderis oneResource(section 11.1): the same duty holds for every type implementingResource, such as a file or a database connection. A block that holds such a value, other than a task's, must on every path out of it do one of these: close it (tx.close(), or a method of the record that closes its senders), return it, which hands the duty to its caller, or give it to a task.editrefuses a path that does none of them. A list or a record of senders carries the duty for all of them: its block closes each (for tx in senders { tx.close() }), returns it, or gives it to a task. Copies of a sender within one task are one holder: closing any closes the task's copy. - Giving it to a task ends the giver's duty when the
spawn's capture is the block's last use of it: the sender moves into the task. A capture inside a loop is not a last use, so in the example above each task gets a copy and the block still closes its own. - Parameters are borrowed. A function given a value with a duty doesn't take the duty: its caller keeps it. A function that closes what it is given takes it by
move(section 10.7, to try). - Early exits. A path that leaves the block by
!or?closes what the block holds with a duty, as a task's end does. On every other path the close stays written. - A task's copies close when the task ends, on any path: its end,
return, a panic, or cancellation. Inside a task,tx.close()only closes a copy sooner. - Every other
Resourcea task holds is closed the same way when it ends, on any path: a panic or a cancellation closes its files and connections as its end would. - Using a copy after its
close, in the same task or block, is an error at edit. - So a program usually writes one
tx.close(), in the block that made the channel or that holds the handle, as in the example above. A task writes one only to stop sending before it ends.
- The duty to close follows the sender. A value whose type holds a
- A copy of the receiver lasts until the task or block holding it ends. Receivers have no
close. - A message can't hold a
Sender. Asendof a value whose type holds one is refused at edit: a sender in a message would be a copy the runtime doesn't count, whose duty nobody could meet. Reply[T]is the one exception: a sender for one answer, which carries no duty. Itssend(self, value: T)takes theReply, so a secondsendis a use after a move, an error at edit, and gives(): an answer to an asker that has gone is dropped; the asker keeps the receiver and has nothing to close. AReplydropped unanswered closes its sender, so the asker'saskgivesNone, as it does when the server has ended. A request that needs an answer carries aReply[T](section 12).- Subscriptions send a receiver back, never a sender. A task serving events (a chat room, std.web's live pages) makes a channel for each subscriber, keeps the sender, and answers with the receiver. Its senders are its duty, and close when it ends. A subscriber that stops reading drops its receiver, and the next
sendto it givesErr(NoReceiver):
// the subscriber
events := hub.ask(Subscribe) or return
for event in events { show(event) }
// in the hub
Subscribe(reply) => {
(tx, rx) := channel()
mut subscribers.push(tx)
reply.send(rx)
}
…
mut kept: List[Sender[Event]] = []
for s in subscribers {
match s.send(event) {
Ok(()) => mut kept.push(s),
Err(NoReceiver) => s.close(),
}
}
subscribers = kept
9.4 select
select {
jobs.recv() as job => run(job),
results.send(last) as sent => sent except return,
clock.after(ms(100)) => flush(),
}
selectwaits until at least one arm is ready, runs the operation of one ready arm, and then its body. The other arms' operations don't happen.- A
recvarm is ready when a value can be taken or the channel has ended. Itsasbinding is theOption[T]. - A
sendarm is ready when the value can be taken, or when no receiver is left. Itsasbinding, which a send arm must have, is theResult[(), NoReceiver]. clock.after(d)is ready oncedhas passed on that clock since theselectbegan. It binds nothing.- When several arms are ready, which one runs is not promised. Under
strata test, the seeded scheduler (section 9.7) chooses.
9.5 race and cancellation
race {
fetch(primary) as page => page,
supervised fetch(mirror) as attempt => attempt except panic { fallback(panic) },
clock.after(seconds(5)) => timed_out(),
}
racestarts each arm's operation as a task. The first to end wins. Every other arm is cancelled, theracewaits until each has stopped, then runs the winner's body with itsasbinding.- A
supervisedarm's binding is aResult[T, Panic], and its panic is its result: an arm that panics first wins the race. - Cancellation. A cancelled task stops at its next cancellation point: any wait (
recv,send,await,select,race, a sleep, the end of ascope, an I/O wait), every function entry, and the back edge of every loop, so a deep recursion is cancelled too. It then unwinds asreturnwould: what it holds is dropped, its copies of senders close, and the tasks it started are cancelled. Code between two cancellation points always runs to its end. - Deadlines. A deadline is a
raceagainstclock.after(d). Cancellation reaches every task below the cancelled one, so every call made inside a raced arm is under its deadline, with nothing passed down.
9.6 Values across tasks
- A value given to a task (captured by
spawn, sent on a channel, or given back byawait) is copied, or moved when nothing else holds it, or shared when it is frozen (section 10). AnOwned[T]given withmovechanges owner with no copy (section 10.7, to try). - No object is ever counted by two threads, so no count is atomic.
strata run --copiesreports each copy made at aspawn,sendorawait, with its size and place.- Shared mutable state between tasks is an actor: one task owns the state and serves requests that arrive on a channel, one at a time, so no change is lost. Read-mostly state is published as frozen snapshots (section 10).
- Within one task, several places that must see each other's changes to one thing hold a
Shared[T](section 10.6, built late). It is about references, not concurrency: aSharedcan't be sent or captured byspawn. - std's
actor(initial, update)makes an actor's two parts: a handle holding the sender (withsend, andaskfor requests carrying aReply), and a server holding the receiver, the state andupdate. The caller starts the server:
scope {
(counter, server) := actor(
initial: 0,
update: (count, request) -> match request {
Add(n) => count + n,
Get(reply) => {
reply.send(count)
count
},
},
)
spawn server.run()
counter.send(Add(3))
total := counter.ask(Get) or 0
counter.close()
}
server.run() loops over the requests and ends when every copy of the handle is closed, giving back the final state. counter.ask(Get) passes the constructor Get as a function, (Reply[s64]) -> Request (section 6.4).
9.7 Scheduling and deadlocks
- Tasks are scheduled by the runtime (sections 9.8 to 9.14), not the operating system. The runtime runs one carrier thread per core. A task runs on one carrier for its whole life and never moves to another; which carrier is the runtime's choice. So no object is counted by two threads, and counts stay plain.
- Time slices. Every function entry and every loop back edge checks whether the task has used up its time slice while other tasks on its carrier are ready; if so, it yields. Code between two such points runs without interruption. Nothing about the order of tasks is promised beyond what channels,
awaitandscopegive. - Foreign calls. A call of an
extern cfunction runs in place, on the task's carrier, at the cost of a plain call. A C library that keeps state per thread keeps it, since a task's carrier never changes. - A function declared
extern c blocking fnmay wait (I/O, a sleep, a lock). Its calls run on a helper thread while the task is parked, so the carrier's other tasks go on. Such a call costs microseconds, can't be cancelled midway (a cancelled task stops when it returns), copies aStringresult back, and may run on a different helper thread each time. - A call that waits but isn't marked
blockingholds its carrier: the carrier's other tasks wait until it returns. - Core's own
extern cdeclarations, the runtime's (section 11.1), are notblocking. - A C library that both waits and keeps state per thread is served by a task spawned
on: OwnThread, which has a thread to itself (section 9.9). - Under
strata test, tasks run on a scheduler seeded per test, whose time slice is a fixed number of checks (function entries and back edges), not a time, so a busy task still yields and the order depends only on the seed. A failing order is reported with its seed, and the seed replays it. - A deadlock is a panic. When every task is waiting and no wait can end on its own, the program stops and reports what each task waits on and where, with the number of sender copies each waited-on channel has left (and, in a test, the seed). A wait on a real timer, a socket, a file or a foreign call ends on its own; a wait on a channel, a task or a
VirtualClockdoesn't. - Time comes from a
Clockcapability (section 6). WithVirtualClock, sleeps andafterarms end in deadline order, each once everything else is waiting, so a test of timers takes no real time.
9.8 Carriers and runs
The numbers in sections 9.8 to 9.13 (8 helper threads, a 10 ms ticker, 256 kept stacks, round-trip times) are the reference runtime's defaults and measurements, not rules.
The runtime is the part of a program that runs tasks and waits. It is C (runtime/), declared to Strata by extern c in core's runtime module (section 11.1).
- A carrier is an OS thread that runs tasks. The runtime starts one per core. Each carrier has a ready list, a run-next slot (a task woken by the running one goes next), a timer heap and a readiness poller (kqueue on macOS, epoll on Linux).
- A run is a program, or one test under
strata test. It holds its tasks, scopes, waiters and, under aVirtualClock, its virtual time. - A task stays on one carrier for its whole life (section 9.7). A thread's own state, the allocator's lists and a C library's per-thread state included, is therefore the task's for as long as it runs.
- A ticker thread looks at every carrier each 10 ms. It flags a carrier that has run one task since its last look while another is ready there, or that has a timer due. The flag is the word that the checks at function entries and loop back edges read (section 9.7).
9.9 Where a task runs
scope {
parts := chunks(items, count: carriers())
tasks := [spawn(on: Carrier(i)) part.map(transform) for (i, part) in parts.enumerate()]
await tasks
}
spawn(on: p) eplaces the task byp, aPlacementfrom core'staskmodule:
type Placement =
| Anywhere
| Here
| Carrier(Natural)
| OwnThread
Anywhere, the default: the carrier with the fewest tasks living on it (ready, running or parked) when the task starts, the spawner's own on a tie. A carrier not started yet has none.Here: the spawner's carrier. Tasks that mostly talk to each other ask for it: a round trip between two tasks on one carrier costs about 0.2 µs, between two carriers 9 to 13 µs on macOS under load (about 4 µs on a quiet machine, up to 160 µs in a Linux VM). A task that answers one request and ends, such as std.http's handler, is spawnedHere.Carrier(i): carrierimodulocarriers(), the number of carriers.Carrier(0)is the program's main thread.map_parallelcuts its list intocarriers()parts and places partion carrieri.OwnThread: a new OS thread that runs only this task. Every call the task makes runs in place on that thread,blockingones included (section 9.13). It is for a C library that both waits and keeps state per thread, such as an embedded interpreter: an actor serving it is spawnedon: OwnThread. Such a task costs a thread. AHerespawn from anOwnThreadtask is placed asAnywhere.- The options combine (
spawn(on: Here, stack: mebibytes(1))), andsupervised spawn(on: p) etakes them too. - Once placed, a task never moves. Under
strata test, every task runs on the test's one carrier, so that the seed alone decides the order (section 9.7), except anOwnThreadtask, which keeps its thread: what it receives and sends crosses the carrier in the order the seed gives.
9.10 Stacks
- A task's stack is reserved with
mmapand a guard page below it. Pages are committed only when touched, so an idle task costs one page (16 KB on Apple silicon) and about 1 KB of records. - Its size is the program's (
task_stackunder[run]instrata.toml, in bytes or as"8 MiB", 8 MiB by default; the environment variableSTRATA_TASK_STACKoverrides it) or the spawn's (spawn(stack: mebibytes(64))). It costs address space, and memory only as deep as the task goes. It never grows or moves: frames can't be moved while C may hold pointers into them. - A touch of the guard page is a stack overflow: the signal is taken on the carrier's own signal stack and becomes a panic of the task (section 9.2).
- Up to 256 freed stacks are kept per carrier for reuse.
- Switching tasks saves and restores the registers a call must keep: a short assembly routine per architecture. On x86-64 it also saves MXCSR and the x87 control word, which the System V ABI makes callee-saved. It doesn't use
ucontext. Only stacks of the program's size are kept for reuse.
9.11 Waiting
Every wait in a program is a park, and every wake is an unpark of one task. Core's runtime module declares the two, and nothing else in the runtime waits.
park(locks, deadline)parks the running task. It lets the given locks go once the task is parked and takes them back before it returns. A waker takes the same lock, so no wake is lost between the check and the park.- An unpark that arrives while the task still runs is kept, and the task's next park returns at once. Every wait looks again after it wakes.
- Ways to unpark. A channel operation, a task's end and a scope's end unpark their waiters. So do the runtime's own sources:
- timers (a sleep, a
clock.afterarm); - descriptors, through the carrier's poller (sockets, pipes, standard input);
- helper calls (section 9.13).
- timers (a sleep, a
A new kind of wait, such as a file watcher or a process's exit, is a new way to unpark, never a new way to wait.
- Targeted wakes. A channel keeps a queue of tasks waiting to receive and one of tasks waiting to send. It wakes one receiver per value; a receiver that leaves without the value wakes the next. A task keeps a queue of the tasks awaiting it. Nothing wakes every waiter.
- A
selectwaits in each of its channels' queues at once and is woken once: the first wake marks it, and later ones pass it by. The mark is cleared at each park.
9.12 Locks and the order at a task's end
- There is no global lock. Three kinds of lock cover what tasks share:
- each carrier has one for its ready list, run-next slot, timers and its tasks' states. Another thread takes it only to unpark one of those tasks;
- each channel has one for its buffer, queues and counts;
- each run has one for its tasks, scopes, waiters and virtual time.
- Locks are always taken in this order: channels (by address), then the run, then the carrier. A
selecttakes its channels' locks in address order, then the run's. - Deadlocks. A run counts its tasks that aren't in a counted wait (section 9.7: a wait on a channel, a task or a
VirtualClock). The count changes only at a park and an unpark. A park that would take it to zero looks for a stuck run: it advances the virtual clock, or reports the deadlock (section 9.7), or parks after all. A task's end looks too. No wait walks the run's list of waiters. - The order at a task's end. A task gives back its memory (its allocator lists and tallies) before it marks itself done under its run's lock. Marking it done is where any other task first sees its end. A helper thread marks its call done and unparks the task under the task's carrier's lock, so the task can't end before the wake. A task's records are freed only by its own carrier.
9.13 Helper threads and blocking calls
- Up to 8 helper threads run calls that wait in the operating system: file reads and writes,
getaddrinfo, and everyextern c blocking fncall. The task is parked meanwhile, and the carrier runs its other tasks. - For a
blockingcall, the arguments are stored in a block in the caller's frame and the helper calls the function with them. AStringorCStringresult is copied on the helper, because C may give a buffer its thread reuses. - A blocking call can't be cancelled midway: a cancelled task stops when the call returns.
- In an
OwnThreadtask, ablockingcall runs in place, since nothing else waits on that thread. - Stalls. A call that waits without being marked
blockingholds its carrier.strata run --stallsreports every call that held its carrier past a time slice, with its place and its time. A stall is a time-slice request still pending one look of the ticker later, measured from the request in 10 ms steps. Its place is the carrier's call stack when the stall is first seen, with the task's spawn site. A call that waits while nothing else waits on its carrier isn't a stall. A built program reports stalls underSTRATA_STALLS=1.
9.14 Platforms
- macOS on arm64: kqueue, the arm64 switch routine, helper threads.
- Linux on arm64 and x86-64: an epoll poller woken through an eventfd, and the x86-64 switch routine.
- Nothing in this section changes with the platform except these two parts.
9.15 Nodes
Section 3 lists the nodes: Scope, Spawn, Await, Select and Race among the expressions, and SelectArm and RaceArm. Section 4 gives their tags.
9.16 Laws
Sketched. Those marked checked are proven on the checker's code; the others are about running programs, proven against section 7's model. The runtime's own laws (waking, lock order, the order at a task's end) are about C code: they are tested, by fuzzing and by the seeded scheduler's runs, until the runtime is written in Strata.
// checked: a task's handle never leaves its scope
law handles_stay_in_scope(d: Definition, h: NodeIndex)
requires is_task_handle(d, h)
holds !escapes_scope(d, h)
// checked: on every path out of a block holding a sender, the sender is closed, returned or given to a task
law close_duty_met(d: Definition, block: NodeIndex, path: Path)
requires holds_sender(d, block) && exits(path, block)
holds closes(path) || returns_it(path) || gives_to_task(path)
// a scope ends only after every task spawned in it has ended
law scope_waits(run: Run, s: ScopeId)
requires ended(run, s)
holds tasks_of(run, s).all(t -> ended_before(run, t, s))
// recv gives None exactly when every copy of the sender is closed and nothing is left
law recv_none(run: Run, c: Channel, at: Time)
holds (recv_at(run, c, at) == None) == (open_senders(run, c, at) == 0 && buffered(run, c, at) == 0)
// send gives an error exactly when no copy of the receiver is left
law send_no_receiver(run: Run, c: Channel, at: Time)
holds (send_at(run, c, at) is Err) == (receivers(run, c, at) == 0)
// checked: no message holds a Sender, Reply excepted
law no_sender_in_messages(d: Definition, send: NodeIndex)
requires is_send(d, send)
holds !holds_sender_type(sent_type(d, send)) || is_reply(sent_type(d, send))
// the values one sender sends are received in the order it sent them
law per_sender_order(run: Run, c: Channel, a: Message, b: Message)
requires same_sender(a, b) && sent_before(run, a, b) && received(run, a) && received(run, b)
holds received_before(run, a, b)
// a select carries out exactly one arm's operation
law select_one(run: Run, s: SelectId)
requires ended(run, s)
holds count(operations_done(run, s)) == 1
// a race runs its winner's body only after every loser has stopped
law race_waits(run: Run, r: RaceId)
holds losers(run, r).all(l -> stopped_before(run, l, body_start(run, r)))
// a task runs on one carrier for its whole life
law task_stays(run: Run, t: TaskId, a: Time, b: Time)
holds carrier_at(run, t, a) == carrier_at(run, t, b)
// no object is counted by two carriers
law one_counter(run: Run, o: Object, a: Time, b: Time)
holds counting_carrier(run, o, a) == counting_carrier(run, o, b)
// a cancelled task does no work past its next cancellation point
law cancellation_prompt(run: Run, t: TaskId)
requires cancelled(run, t)
holds work_after(run, t, next_point(run, t)) == []
// when every task waits on something that can't end by itself, the program panics with the report
law deadlock_reported(run: Run, at: Time)
requires all_wait_forever(run, at)
holds panics_with_report(run, at)
// a test run with one seed gives one order of tasks
// for a test with no blocking call, no OwnThread task and no real I/O but its temporary folder
law seed_replays(test_case: Test where replayable(it), seed: u64)
holds schedule(run_test(test_case, seed)) == schedule(run_test(test_case, seed))
// a task placed on a carrier runs there for its whole life
law placement_kept(run: Run, t: TaskId, c: u32, at: Time)
requires placed(run, t) == Carrier(c)
holds carrier_at(run, t, at) == c % carriers()
// an OwnThread task shares its thread with no other task
law own_thread_alone(run: Run, t: TaskId where placed(run, it) == OwnThread, u: TaskId, at: Time)
requires u != t
holds thread_at(run, u, at) != thread_at(run, t, at)
// no wake is lost: a task parked on an object that is then unparked runs again
law no_lost_wake(run: Run, t: TaskId, at: Time)
requires parked(run, t, at) && unparked_after(run, t, at)
holds runs_after(run, t, at)
// locks are taken in the one order: channels by address, then the run, then the carrier
law lock_order(run: Run, carrier_thread: Thread, a: Lock, b: Lock, at: Time)
requires holds_lock(run, carrier_thread, a, at) && takes_lock(run, carrier_thread, b, at)
holds lock_rank(a) < lock_rank(b)
// a task's memory is given back before any other task can see its end
law end_after_memory(run: Run, t: TaskId)
requires ended(run, t)
holds memory_returned_before(run, t, end_visible(run, t))
// a blocking call never holds its carrier
law blocking_frees_carrier(run: Run, call: CallId where is_blocking(it))
requires placed(run, task_of(call)) != OwnThread
holds during(run, call).all(at -> parked(run, task_of(call), at))
10. Memory
How values are held in memory. None of it changes what a program computes (section 7): values never change and have no identity, so whether memory is shared or copied can't be observed. It changes only how much memory and time a program takes.
10.1 Counting
- A value too large for a register lives in a block on the heap. Each block holds a count of the places holding it, and is freed when the count reaches zero.
- No block is counted by two threads (section 9): counts are plain, never atomic.
- A parameter is borrowed by default: a function that only reads it doesn't change its count. The compiler infers which parameters a function keeps.
- A block held in one place only is changed in place by an update (
mut xs.push(x),p.x = 1), not copied. The compiler proves "held once" where it can, and tests the count where it can't. - No cycles. A value only ever holds values made before it, so no block reaches itself, and counting frees everything.
Shared[T]keeps this at the writes that could break it: amutatemay store a strongSharedlink only where it doesn't make a block reach itself, and a link that would close a loop must be aWeak[T](section 10.6). AShared's block is freed like any other when its count reaches zero, and first cuts itsWeaklinks.
10.2 Layout
- Machine integers and floats are held in registers, and in records and lists at their own size: a field of type
u3takes 3 bits, packed with the fields next to it.Intis a word when small, a block when large. - A record small enough is held in registers or inline, with no block of its own. An
Optionof a block is a pointer that may be null. - A value of a sum's member carries its member's tag, whatever type it is seen as: a
Circleis aShapewith no conversion, soList[Circle]is aList[Shape]as it is. A sum with a member that has no tag of its own (s64 | Missing) stores a tag beside the value, so aList[s64]given as aList[s64 | Missing]is converted, a copy--copiesshows. Only a trait used as a type pairs a value with a method table (section 6.2). - A
Listholds its elements one after another. AStringholds its UTF-8 bytes. - A task's stack is reserved with a guard page and committed only as deep as the task goes (section 9.10). Values on it are freed when their frame ends.
- A
Shared[T]handle points to a block holding a state word, the value and a pointer to its link block. AWeak[T]points to the link block, two words holding theSharedblock's address, made at the firstweak(), so aSharedthat never gives one out has none. A snapshot is a counted read;mutatemoves the value out and back. - The layout is never visible to a program.
10.3 Arenas
for req in requests {
arena {
if req.bad { continue }
served += 1
respond(req)
}
}
arena { body }runs its body with everything it makes going into one region, freed all at once when the body ends.- In: a value from outside used inside isn't copied. When a pointer to an outside block is stored into one of the arena's blocks, a write barrier on those stores adds one to the outside block's count and puts it on the arena's list; the arena gives those counts back when it ends. Only stores into an arena's blocks pay: counting elsewhere is unchanged. The arena's list never holds the last count of an outside block.
- An arena belongs to one task. Work it spawns or awaits isn't in it: an awaited result is copied in. std's request handlers run the handler in a task of its own, with the request's arena in that task.
- Out: a value leaves an arena only by copy: its result, a value it returns, and every value stored into a place outside it (an outer variable, an element or field of one, a
Sharedmade outside). Each outer variable orSharedthe arena changed is copied out once, at the arena's end, and held once more by the arena while it runs; so an update the compiler proves in place outside an arena isn't in place for those variables inside it. Nothing outside an arena ever points into it. Areturncrossing two arenas at once is not built yet. - Changes to outer values are safe. A
mutupdate makes the variable hold a new value; it never changes a value someone else holds. No other task can reach these values (section 10.5), and code outside the arena doesn't run while its body does. - Inside an arena, blocks are counted as anywhere else, so updates in place still work.
break,continueandreturnleave an arena as they leave any block, andmutvariables from outside may be assigned inside it.- When to use one. An arena pays for a unit of work that makes many short-lived values, keeps few, and repeats: one request, one definition compiled, one frame. A large result is built in a list made before the arena, so each element is made outside and only the work in between is freed. An arena isn't for a whole long-lived task, whose memory would then grow until it ends. std's request handlers run each request's handler in an arena, so most programs get it without writing one. Arenas are never added implicitly.
10.4 Frozen values
frozen routes as shared {
scope {
for connection in connections { spawn serve(connection, shared) }
}
}
- When to use one. Many tasks read one large value that doesn't change: a server's routes and settings, a search index queried by several workers, a game's static map. Small values, values one task uses, and data that changes (an actor's) don't need it. A frozen value lives as long as its block: a snapshot published again and again (an actor's state for readers) needs another form, to settle with the memory trial.
frozen e as name { body }copiese's value once into a frozen region and binds it tonamefor the body. A block reached twice while copying is copied once, so the frozen value has the original's structure and size.- Blocks of a frozen region are never counted. Any task may read
name: aspawncaptures it, and a channel sends it, without a copy. namecan't leave the block: it can't be returned, stored in a value made outside, or kept by a task that outlives the block. The checker refuses each, so no copy is hidden. (The lab copies such a value out at the block's end instead; that stays only as a safety net until the check is built.) The region is freed when the block ends, after its result is copied out.- A value holding a channel end or a task handle can't be frozen.
- A frozen region's blocks reach only frozen and static blocks.
10.5 Values between tasks
- A value given to a task (captured by
spawn, sent on a channel, returned byawait) is copied into the receiving task, moved when nothing else holds it, or shared when it is frozen (section 10.4). - Captures shared by the scope. A
scopeoutlives its tasks, so a value aspawncaptures from outside the scope can be shared instead of copied. It is marked shared for the scope; while the scope is open, only the scope's own task counts it, through the runtime, and the spawned tasks read it without counting. Immutability isn't enough on its own: a shared block's count would otherwise be changed by two threads. Values sent on channels aren't covered;frozenstays for them, and for code that wants a share guaranteed. - A task's result that holds a shared capture is copied at
await. - A task's own captures are freed when the task ends, and shared captures when the scope ends; a finished task, when its handle is dropped.
strata run --copiesreports each copy made between tasks, with its type, size and place.
10.6 Shared[T] and Weak[T] (built late)
Shared[T]is the one type with identity: several places in one task that must see each other's changes to one thing hold copies of one handle, made byshared(v).s.snapshot()gives its value;mut s.mutate(mut x -> body)changes it in place, and its value isbody's. Amutatebody can't jump out, and asnapshotormutateof aSharedduring its ownmutatepanics.s.weak()gives aWeak[T], which doesn't keep the value alive;w.shared()givesOption[Shared[T]],Noneonce the value is gone.- Both are invariant in
T. A type holding aSharedor aWeakhas no==and no hash;same(a, b)says whether two handles share one value. - A type holding a
Sharedor aWeakcan't cross tasks: it can't be captured by aspawn, sent, or be a task's result. The check goes by type. State shared between tasks is an actor's; read-only state isfrozen. - Forward and back links aren't told apart by type: a tree's
Node { children: List[Shared[Node]], parent: Option[Weak[Node]] }is allowed, thoughNodereachesNodethrough a strong link. What matters is each write. Amutatethat stores a strong link from blockato blockbholds the obligation thatbdoesn't reacha, so a link down a tree is fine and a link back up must be theWeakone.verifyproves it where it can (a fresh child reaches nothing); elsewhere the write checks it, walking fromb, and panics on a cycle, naming the link to makeWeak. - What verification knows. A snapshot is a valid value of
T, refinement included, and the same until the next write. A write is amutate, or a call that may reach one: "may write aShared[T]" is inferred from bodies, since a handle copies and amutmark on it doesn't cover every write.mutatemust put back a validT.
10.7 Owned[T] (to try in the lab)
Counting stays the default. Owned[T] is ownership asked for on the few values that need it, as C++'s unique_ptr or Rust's Box: a borrow check on those values only.
buf: Owned[Bytes] = Owned(read_file(path)!)
alias := buf // error: `buf` is `Owned`: write `move buf`
total := checksum(buf) // borrowed: buf is still yours
compress(mut buf) // changed in place
tx.send(move buf) // the receiving task owns it now, with no copy
console.print(f"{buf.len()}") // error: `buf` was moved to `tx.send` on line 5
- An
Owned[T]has one owner and no count word. It is never copied, only moved, and it is freed at its owner's last use: there is nofreeto write. - Every move is written
move x:y := move x,return move x,T { f: move x },y = move x,tx.send(move x).y := xis an error at edit ("xisOwned: writemove xto give it toy"). A use after a move is an error naming the line of the move. So the marks at a use are one family: plain borrows,mut xchanges in place,cap xpasses a capability,move xgives the value away. - "Moved, then used" is checked by the same path analysis as section 9.3's duty to close. Freeing in a set order stays
Resource's; there is no uncheckedfree. - Between tasks: a value moved into a
sendor aspawnchanges owner with no copy and nofrozen, and no two threads ever count it (section 9.6). - Foreign memory: C and GPU buffers, mapped files and handles can be
Owned, with no count (section 11). - An
Owned[T]goes only into a type itself declared owned (how it is declared is for the trial to settle). This first rule loosens if a real program needs it. - The trial measures the count operations left in hot paths after Perceus, and handing a large buffer between tasks as
Owned, asfrozenand as a copy.
10.8 Laws
Sketched, about running programs, proven against section 7's model with this section's memory.
// no block is counted by two threads
law blocks_one_counter(run: Run, b: Block, at: Time, later: Time)
holds counting_thread(run, b, at) == counting_thread(run, b, later)
// a block in use is never freed
law no_dangling(run: Run, b: Block, at: Time)
requires reachable(run, b, at)
holds !freed(run, b, at)
// no block reaches itself
law no_block_cycles(run: Run, b: Block, at: Time)
holds !reaches(run, b, b, at)
// nothing outside an arena points into it
law arenas_closed(run: Run, a: ArenaId, b: Block, at: Time)
requires !inside(run, b, a)
holds !points_into(run, b, a, at)
// frozen blocks reach only frozen and static blocks
law frozen_closed(run: Run, b: Block where is_frozen(it), c: Block, at: Time)
requires points_to(run, b, c, at)
holds is_frozen(c) || is_static(c)
// an arena's list never holds the last count of an outside block
law arena_never_last(run: Run, a: ArenaId, b: Block, at: Time)
requires on_list(run, a, b, at) && !inside(run, b, a)
holds count_at(run, b, at) > 1
// a Weak never keeps a value alive: its link reads 0 once the Shared's block is freed
law weak_never_keeps(run: Run, w: WeakLink, at: Time)
requires freed(run, target(w), at)
holds address(run, w, at) == 0
// freezing keeps the value, and its size
law freezing_keeps_values(v: Value)
holds freeze(v) == v && size(freeze(v)) == size(v)
// memory never changes a result
law memory_invisible(p: Program, input: Input)
holds result(run_counted(p, input)) == result(run_model(p, input))
11. Foreign code
Foreign code is reached through extern c. A single C function can be declared by hand: core does so for the runtime's C (runtime/, in core's runtime module), and a module may do so for a function of the C library. Everything else, a C library, a Rust crate, a Python module or a TypeScript package, is a dependency: the compiler reads its declarations from the library itself.
A new language lacks libraries. Strata answers with two things: a large std (files, networking, terminals and user interfaces), and calls into code that already exists, so that a program can use a library today and replace it with Strata code later, one part at a time.
11.1 extern c
extern c pure fn cbrt(_x: f64) -> f64
extern c fn edit_distance(a, b: String) -> s32 where it >= 0
extern c blocking fn sqlite3_step(statement: Statement) -> s32
- An
extern cdeclaration declares a C function by its symbol, with a signature and contracts and no body. Section 5.5's rule holds: it isn'tpub, and its module, or a binding (section 11.2), wraps it. - Values that cross:
| Strata | C |
|---|---|
s8 … s64, u8 … u64 | int8_t … uint64_t |
f16, bf16, f32, f64 | _Float16, __bf16, float, double |
Bool | bool |
() (as a result) | void |
a handle type, distinct type Statement = Ptr | a pointer C made |
Option[H] of a handle | a pointer that may be NULL |
String, Bytes (a parameter) | two parameters: const uint8_t *, size_t |
CString (a parameter) | const char *, NUL-terminated |
CString (a result) | const char *, copied at once |
mut x: T | a pointer to T, copied in and back out |
Packed[T] (a parameter) | a pointer to its first element; its length is another parameter, tied to it by a requires (requires n == len(a)) |
Result[T, ForeignError] (a result) | T, with C++'s exceptions caught by a wrapper the compiler generates and given as Err |
Intdoesn't cross: its size isn't fixed. A record whose fields all cross crosses as a Cstruct, laid out as C lays it out, by value or, as amutparameter, by pointer; this is how section 11.2 reads a Cstruct. Lists, other records and sums don't cross, except in core's own runtime declarations, which pass values as compiled code holds them. A float a foreign call returns that isn't finite givesErrwhen the extern returns aResult, and is a panic of the calling task otherwise (section 7.3).- A
StringorBytesargument is the value's own bytes, borrowed for the call: no copy. C must not keep the pointer. Its length has the C type the header gives it: asize_t, or anint(assqlite3_bind_texttakes), for which the call addsrequires byte_len(text) < 2 ** 31. - A
CStringargument is the string copied with a NUL added.CStringis core'sString where !it.contains("\0"): the refinement holds at each call, proven byverifyor else checked at run time. A wrapper that tests for a NUL and returns an error, as std's do, makes it provable. - A string result of a known length comes back through
mutparameters for its pointer and length. The C side keeps its buffer, which Strata copies. - Foreign memory as
Owned(to try, section 10.7): a C or GPU buffer or a mapped file may be anOwned[T], freed at its owner's last use with no count. - Handles and
Resource. A handle is opaque: Strata passes it back and never frees it. A handle type may have methods and operators of its own, given in its module. A handle that must be freed implements core'sResourcetrait (modulecore.resource, in the prelude), whose one method isclose(self): it takes the value, so nothing can use it after. It is called on a value the block owns (a local, or one returned to it), never on a borrowed parameter: a helper that closes what it is given takes it bymove(section 10.7), and until that is built, returns it for its caller to close. std.net's streams close the same way. Section 9.3's duty to close then applies to it: a block holding one must close it, return it or give it to a task on every path, andeditchecks this.Senderis aResourcetoo. - Marks.
blockingsends the calls to a helper thread (section 9.13).purepromises the function has no effect outside its result: no I/O, no global state, the same result for the same arguments. A function calling onlypureexterns can be pure (section 6.9). Neither mark is checked: each is the C author's promise, asnoallocis.pureis a bit of the extern'sflags(section 4.4). - Contracts. An extern's
requiresare proven at each call, as any function's. Itsensuresare trusted, and are listed bystrata verify --assumed.verifyfuzzes theensuresofpureexterns only, each as a target of its own built with the package's[native]C, against random arguments meeting therequires. It never runs any other extern, since it can't know what the C writes or deletes. A non-pureextern'sensuresare checked after each call instead, except core's runtime declarations (core.runtime), whoseensuresare trusted and never checked: they are part of the trusted base (section 8.6). - The C side is compiled from the package's
[native]sources or linked from itslinklibraries. Core's runtime is linked into every program. - A call through a wrapping Strata function costs nothing over the direct call: the wrapper is inlined.
11.2 Foreign libraries
[foreign]
sqlite = { c = "sqlite3.h", link = "sqlite3" }
regex = { rust = "regex@1" }
numpy = { python = "numpy" }
zod = { ts = "zod" }
use numpy.Numpy
fn spread(cap np: Numpy, xs: List[f64]) -> Result[f64, PythonError] {
np.std(xs)
}
[foreign]instrata.tomlnames foreign libraries as dependencies.useimports one by its name, as any dependency (section 5.2).- Bindings. The compiler reads the library's own declarations and writes a binding: a package of Strata declarations, with the library's own docs (header comments, rustdoc, docstrings, TSDoc) as their
///docs. It is cached, stamped by the library's version and the notes (below). Nothing in it is written by hand. - A binding is read like any package.
strata view sqlite -k fnlists every function sqlite3 offers, with its signature and doc;strata view sqlite -k typeits types;strata view numpy.linalgone module. Whatviewshows is exactly what a program can call. - Names follow section 5.6 in the binding (
sqlite3_stmtis the typeSqlite3Stmt), and each keeps its foreign name as the symbol. A foreign name that is a Strata keyword takes a trailing_(np.where_, a parameterin_), never a leading one, which would make a parameter positional; the symbol called is unchanged. A simple#defineis a function of no arguments. A binding's doc is the first paragraph of the library's. - The capability is named after the library; when that name is one of the library's own types (the crate
regexand itsRegex), it is followed byLibrary:RegexLibrary. - A foreign library is a capability. Its binding defines a capability type named after it (
Numpy), and its functions are that type's methods.mainand tests ask for it like any capability, and a test can mock it. Itspurefunctions are plain functions of the binding and need no capability. A library's submodules are reached through it,sk.linear_model, and a class is a type with its constructor,sk.linear_model.LinearRegression(). - How each language is read and called:
| read from | runs | values | |
|---|---|---|---|
| C | the headers, by clang | in the program | as section 11.1; struct → record, enum → sum, simple #define → constant, a pointer to an opaque struct → handle |
| Rust | the crate's public API | in the program, through glue the compiler generates and cargo builds | struct → record, enum → sum, Option, Result, Vec, String, &str, &[T] → their Strata forms, borrowed where Rust borrows; any other type (generic, with lifetimes, a trait object) → a handle |
| Python | signatures, type hints, .pyi stubs | embedded, the interpreter served by an actor on: OwnThread | int, float, str, bytes, list, dict, tuple, None, dataclasses → their Strata forms; a Packed argument is lent to Python as a buffer, without a copy; anything else, a NumPy array among them, → a Python object handle |
| TypeScript | the .d.ts files | in a Node worker process | data as JSON; class instances → handles |
- A Python
intcrosses asInt: both are unbounded. - A call that raises an exception, or a result that isn't of its declared type, gives
Errof the library's error type. - Typed Python results need type hints or
.pyistubs: NumPy's functions carry no hints at run time, so without its stubs every result is aPyObject. An attribute that appears only after a call (coef_afterfit) is read from the class's documented attributes.
//! What sqlite3's header doesn't say.
extern c blocking fn sqlite3_open(filename: CString, mut db: Option[Sqlite3]) -> s32
extern c blocking fn sqlite3_step(statement: Sqlite3Stmt) -> s32
extern c pure fn sqlite3_libversion() -> CString
extern c pure fn sqlite3_libversion_number() -> s32 where it >= 3000000
impl Resource for Sqlite3 {
fn close(self) {
_ := sqlite3_close_v2(self)
}
}
/// The version as text and as a number agree.
law versions_agree()
holds version_number(sqlite3_libversion()) == sqlite3_libversion_number()
by assume
- An
externwritten there replaces the generated declaration of the same name.editchecks that it agrees with the library: the same number of parameters, and each, and the result, of the same C form (a number of the same width, or a pointer: aString, aCStringwhere the header haschar *, a handle or anOptionof one). - For C, a note may also add an
externfor a function the binding left out (one whose parameter doesn't cross, such assqlite3_prepare_v2'sconst char **), sinceextern cmay be written anywhere. - A function a note names as a handle's
closeleaves the capability: only theResourcecalls it, so no handle is freed twice. - An
implthere may implement a trait for the binding's types, as if written in the binding. - A
lawthere states what the library promises,by assume.verify --assumedlists it. One aboutpurefunctions only is fuzzed like theirensures.
Foreign values and foreign objects
What crosses from a foreign library is one of two kinds.
- Foreign values are data the binding can convert: numbers, strings, lists, dicts, tuples, dataclasses, C structs, Rust structs and enums it can mirror. They are copied into Strata values, with no identity, and are used like any value.
- Foreign objects are everything else: a NumPy array, a scikit-learn model, a Rust
regex::Regex, a C pointer to a struct the program doesn't own. Each is held by a handle.
fn fitted_slopes(cap sk: Sklearn, x: List[List[f64]], y: List[f64]) -> Result[List[f64], PythonError] {
regression := sk.linear_model.LinearRegression()!
regression.fit(x, y)!
regression.coef_()
}
- A handle is a capability (section 6.9). The library's capability, or another handle's method, gives one:
sk.linear_model.LinearRegression(). It follows every rule of section 6.9: it is held only in parameters and locals, or in a structural record of capabilities, never in a named record's field or a list; it is passed withcap; a lambda can't capture it; a test can mock it. A function that touches a foreign object says so in its signature. - Methods come from the library's declarations (a class's stubs, a Rust
impl, nothing for C) and are called as Strata methods.- A Python method can always raise, so it gives
Result[T, PythonError]. A TypeScript method givesResult[T, TsError]. - A Rust method gives what Rust gives. A Rust panic is caught at the boundary: it gives
Errof the binding's error type when the method returns aResult, and is a panic of the calling task otherwise. - A Rust struct that only borrows (fields with lifetimes, such as
regex::Match) is read as a record of its getters' values, copied, so no lifetime crosses into Strata (to try on a second crate).
- A Python method can always raise, so it gives
- Fields and attributes.
- A Rust
pubfield, and a field of a C struct reached through a handle, are read with field syntax,matcher.pattern: reading one runs no code. - A Python attribute is read with a method call,
regression.coef_(), and gives aResult: reading it can run code (a@property) and raise. Setting one ismut regression.set_coef_(v).
- A Rust
- Operators and protocols map onto core's traits:
- Python's
__add__…__pow__,__eq__,__lt__,__getitem__,__setitem__,__iter__,__len__and__str__becomeAdd…Pow,Eq,Ord,Index, iteration,lenandDisplay.a + badds two NumPy arrays. An operator gives its trait's type, never aResult, so an exception raised in one (two arrays of different shapes) is a panic, as integer overflow is; the named method (a.add(b)) gives aResultinstead. - Rust's
std::opstraits,PartialEq,PartialOrd,DisplayandIteratormap the same way.
- Python's
- Lifetime. A Python or Rust handle is counted like any Strata block (section 10.1). When the last reference goes, the binding releases the Python reference, or runs the Rust
Drop. Nocloseis written. A C handle is never freed by Strata: it is aResourcewhen a note names itsclose(section 11.1), since a header doesn't say who frees what. - Across tasks.
- Every Python object lives in the interpreter, on its
OwnThreadactor. A call on a handle, from any task, is a request to that actor, and the calling task parks until the answer comes. Any task may hold a Python handle. A handle given to another task is a new handle on the same object (the actor takes one more Python reference), counted and released by that task alone, so no count is shared between threads. - A Rust handle may be given to another task only if its type is
Send, which rustdoc states. Otherwise it stays in the task that made it. - A C handle may be given to another task unless a note says otherwise.
- TypeScript objects live in the worker, and calls are requests to it, as for Python.
- Every Python object lives in the interpreter, on its
- Without types. A Python or TypeScript object with no declared type is a handle of type
PyObjectorTsObject. It is reached by name:obj.call("fit", args),obj.get("coef_"). Each gives aResultholding a converted value or another handle. - No identity in Strata's sense. A handle has no
==or hash of its own, only the foreign__eq__orPartialEqmapped toEqwhere the library has one.same(a, b)says whether two handles hold the same object.
11.3 To try in the lab
- The TypeScript importer, on zod.
- Python results typed from
.pyistubs. Sendon a crate where it decides something, and borrowing structs read as records of their getters.- Tuples and lists of tensors across C, which TorchScript models need.
- Notes modules: an extern replaced, an
implfor a binding's type, a lawby assume. - Foreign objects as capabilities: methods, Rust and C fields read with field syntax, Python attributes as methods, operators and protocols mapped onto core's traits, counted handles released on the last reference (Python's reference, Rust's
Drop), Python calls as requests to the interpreter's actor,Senddeciding which Rust handles cross tasks,PyObjectandTsObjectfor untyped objects. Measured on NumPy arrays and a scikit-learn model, and onregex::Regex.
11.4 Laws
Sketched. Those marked checked are proven on the compiler's code.
// checked: a Resource is closed, returned or given to a task on every path out of a block holding it
law resource_duty_met(d: Definition, block: NodeIndex, path: Path)
requires holds_resource(d, block) && exits(path, block)
holds closes(path) || returns_it(path) || gives_to_task(path)
// checked: a note's extern agrees with the library's declaration it replaces
law notes_agree(note: Definition, library: Library)
requires replaces(note, library)
holds foreign_signature(note) == declared_signature(library, symbol(note))
// checked: verify runs no extern that isn't pure
law fuzz_only_pure(f: Definition where is_extern(it), run: VerifyRun)
requires runs(run, f)
holds is_pure_extern(f)
// checked: a foreign object's handle is held only where a capability may be
law handles_are_capabilities(d: Definition, n: NodeIndex)
requires is_foreign_handle(type_of(d, n))
holds holds_capability_only(d, n)
// a Python or Rust object is released exactly once, when its last handle goes
law released_once(run: Run, o: ForeignObject)
requires ended(run)
holds count(releases(run, o)) == 1 && released_after_last_handle(run, o)
// a non-Send Rust handle never reaches another task
law send_respected(run: Run, h: Handle where !is_send(rust_type(it)))
holds len(tasks_holding(run, h)) <= 1
// checked: a CString argument holds no NUL
law cstrings_hold_no_nul(d: Definition, call: NodeIndex, i: u32)
requires passes_cstring(d, call, i)
holds argument(d, call, i) |> no_nul |> proven(d, _)
12. The core library
core is the package every program has, below std. Its modules are imported in every module and their pub names are bare (section 5.3), except core.runtime. Core is Strata wherever it can be; what must be C is declared in core.runtime with contracts (section 11.1).
12.1 Modules
| module | holds |
|---|---|
types | Bool, Option, Result, Type, Never, the refinements of section 12.2 |
numbers | the integer and float types, Int, Real, conversions, OutOfRange, the named arithmetic of section 12.4 |
ops | the operator traits, Eq, Ord, Hash (section 12.3) |
text | String, Display, Debug, concat, the string functions (section 12.5) |
collections | List, Dict, Set, the ranges, dict, set (section 12.6) |
iter | Iterator, FiniteIterator, Iterable (section 12.7) |
errors | Error, panic |
task | Task, Panic, Placement, carriers (section 12.8) |
channel | channel, Sender, Receiver, NoReceiver, Reply |
resource | Resource, Capability |
memory | Shared, Weak, Owned, same (section 12.9) |
keys | Key, key_of, the hashes, KeyPath (section 12.10) |
foreign | Ptr, CString, Packed, Machine, ForeignError (section 12.11) |
runtime | the C runtime's declarations (section 12.12); never bare |
12.2 Types
- Numbers:
Int(any size),Real(exact rationals), the machine integerss1…s128andu1…u128, the floatsf16,f32,f64,bf16(section 7.3). - Refinements of
Int, each a plain refinement, so a value outside one is an obligation like any other (section 8.1):
| type | is | so |
|---|---|---|
Natural | Int where it >= 0 | 0, 1, 2, … (ℕ with 0) |
Positive | Int where it > 0 | 1, 2, 3, … (strictly) |
Negative | Int where it < 0 | −1, −2, … (strictly) |
NonZero | Int where it != 0 |
Each name means the same in every language: Positive never includes 0. NonEmpty[T] is List[T] where len(it) > 0, and NonEmptyString is String where byte_len(it) > 0.
Boolis the sum of the atomsTrueandFalse, writtentrueandfalse.()is the empty tuple.Option[T]isSome(T) | None,Result[T, E]isOk(T) | Err(E),Neveris the empty sum, andTypethe type of types (section 6.1).- Types as values. A
Typehasname,parameters, andkind:Recordwith itsfields,Sumwith itsmembers, or one of the built-in kinds. A field is{ name: String, _type: Type, public: Bool, default: Option[Expression] }, as section 3.6'sFieldis. Type functions (Patch[T], section 6.7) read these while compiling.T: Recordbounds a type parameter by kind:Tis a record type. A field'sdefaultthere is code, not a value: an expression written in its place (KeepinPatch) is taken as that code, unevaluated. ThisFielddescribes a type's field as a value; section 3.6'sFieldis the stored node. - Logic only.
for_all((x: T) -> p)andexists((x: T) -> p)state quantified facts in contracts and laws (section 8.4,witness). They have no run-time meaning, and code outside contracts and laws can't call them.
12.3 Operator traits, equality and order
trait Add[Right = Self, Output = Self] {
fn add(self, other: Right) -> Output
}
trait Index[K, V] {
fn at(self, key: K) -> V
fn set(mut self, key: K, value: V)
}
trait Eq {
fn eq(self, other: Self) -> Bool
law reflexive(a: Self) holds a == a
law symmetric(a, b: Self) holds (a == b) == (b == a)
law transitive(a, b, c: Self)
requires a == b && b == c
holds a == c
}
trait Ord: Eq {
fn lt(self, other: Self) -> Bool
fn le(self, other: Self) -> Bool {
self < other || self == other
}
law irreflexive(a: Self) holds !(a < a)
law transitive(a, b, c: Self)
requires a < b && b < c
holds a < c
law total(a, b: Self) holds a < b || a == b || b < a
}
trait Hash: Eq {
fn hash(self) -> u64
law agrees_with_eq(a, b: Self)
requires a == b
holds a.hash() == b.hash()
}
- The operators:
Add,Sub,Mul,Div,Rem,Pow,Neg,BitAnd,BitOr,BitXor,Shl,Shr, written as section 2.5's table says. A binary one is declaredtrait Add[Right = Self, Output = Self], so itsRightandOutputareSelfunless an impl names them:impl Mul[s64, Money] for MoneyisMoney * s64givingMoney. A type has at most one impl of an operator trait perRight:Outputis decided bySelfandRight, sox + 1always has one meaning.Neghas one method,neg(self) -> Self. Indexis[ ](section 2.5). AList, aString's parts and aPackedimplement it for every integer type, soxs[0]andxs[i]withi: u32both work, each requiring the key in range. Its key may be any type: an integer, a string, a range, or a tuple of them, which several indices give (m[i, j],a[0, 1..3]); a type implementsIndexonce per key type it takes. AList'satrequires0 <= key < len(self); aDict's requiresself.contains(key), and itssetinserts or replaces. Both haveget(key) -> Option[V], which never fails. A slice isatwith a range.Ord'sgtandgeare written fromltandlethe same way.Eq,Hash,DebugandDisplayhave a structural impl for every type (section 6.6);Ordhas none, and is written or derived.- A float's
EqandOrdare IEEE's, which with finite values only are an equivalence and a total order (section 7.3).
12.4 Numbers
- Conversions are core's one overload:
elaboratepicks the one for the argument's type, refinement included, as it picks an operator's impl, and the result type comes with it. They are named by the target type:s8(x)…u64(x),f16(x),bf16(x),f32(x),f64(x),Int(x),Real(x). Each gives a plain value when every value of the argument's type fits (its refinement included), andResult[_, OutOfRange]otherwise (section 7.3). - Floats to integers:
truncated_s64(x),rounded_s64(x),floor_s64(x),ceiling_s64(x)and the same for every integer target, each aResult[_, OutOfRange]. - Named arithmetic on machine integers, for when overflow is wanted:
wrapping_add,wrapping_sub,wrapping_mul,saturating_add,saturating_sub,saturating_mul,checked_add, … (givingOption),rotate_left,rotate_right, andwrap_u8(x)… to keep an integer's low bits. - On floats:
sqrt,abs,min,max,floor,ceiling,exp,ln,sin,cosand the like, each with the obligation that its result is finite. /and%on integers are Euclidean (section 7.3).min(_a, _b)andmax(_a, _b)work on anyOrd.
12.5 Text
- A
Stringis valid UTF-8, read by byte offsets (section 7.4).byte_len(s), and its parts as iterators:s.bytes(),s.code_points(),s.graphemes().s.slice(a, b)requiresaandbto be on code point boundaries.code_points()givesCodePoints,u32 where it <= 0x10FFFF && !(0xD800 <= it <= 0xDFFF);graphemes()givesStrings. Bytesisdistinct type Bytes = Packed[u8].String.from_utf8(b: Bytes) -> Result[String, InvalidUtf8]is the one way from bytes to text, whereInvalidUtf8 = { at: Natural }gives the first bad byte's offset.s.to_bytes()goes back.Display.text(x)is what a user reads;Debug.debug(x)what a programmer reads (dbgwrites it). An f-string isconcatof its parts'text(section 2.7).trimmed,lowercase,uppercase,split,join,starts_with,ends_with,contains,replace,parse_int,parse_float, each total or giving aResult.
12.6 Collections
List[T]:len,push,pop,insert,remove,map,filter,flat_map,fold,all,any,find,sorted,reversed,take,drop,slice,contains,enumerate,zip, and+to concatenate. An update is in place when the list is held once (section 10.1).Dict[K: Hash, V]:d[k],get,contains,insert,inserted(a copy with one entry set),remove,keys,values,items,len. Its items come in an order that depends on its contents alone, so two equal dicts give the same order (section 7.2); which order isn't promised. ASetlikewise.Set[T: Hash]:contains,insert,remove,union,intersection,difference,len.- Ranges:
range(a, b)isa..b,range_inclusive(a, b)isa..=b,range_to(b)is..b,range_from(a)isa... A range is a value: iterable, and a slice when indexed with. dict(pairs)andset(items)build whatDict { … }andSet { … }write (section 2.7).- Laws sit next to the functions they are about, so the ladder finds them by the types in an obligation (section 8.3):
slice_step,slice_all,map_append,set_push, and the like. std'slemmasmodule moves here.
12.7 Iteration
Iterator[T]hasnext(mut self) -> Option[T].FiniteIterator[T]is one proven to end, whichforloops in a proof need.Iterable[T]hasiter(self), andfor x in etakes anyIterable.map,filter,take,drop,enumerateon an iterator are lazy: they build adapters, and nothing runs until a value is asked for.- A
Receiver[T]is anIterator[T](section 9.3).
12.8 Tasks and channels
Task[T], the handlespawngives (section 9.1);Panic, what a supervised task'sawaitgives on a panic, with its message and trace.Placementandcarriers()(section 9.9).channel()andchannel(capacity: n),Sender[T]withsendandclose,Receiver[T]withrecv,NoReceiver, andReply[T](section 9.3).- A
select'sclock.after(d)arm gives a coreDeadline = { at: s64 }, a time on its clock in nanoseconds, which the runtime waits on; so core never names std'sClock.
12.9 Resources and memory
Resourcehasclose(self);Senderimplements it (section 9.3).Capabilityhas no methods (section 6.9). Core declares no capability: std does (section 13).Shared[T]andWeak[T](section 10.6), built late;Owned[T](section 10.7), to try.same(a, b)says whether two handles share one value.
12.10 Keys and compile time
Key(section 3.1) hasEqandHash.key_of(x)gives the key of whatxnames;interface_hash(x),code_hash(x)andtext_hash(x)its hashes, at compile time (section 6.7).KeyPath[R, T] = { pub name: String, pub get: (R) -> T }is whatR.fieldgives (section 5.5).
12.11 Foreign values
Ptr, a pointer C made; a handle type isdistinct type H = Ptr(section 11.1).CStringisString where !it.contains("\0").Packed[T: Machine], with views (section 6.1).Machineis implemented by the machine numbers andBool.ForeignError = { code: s32, message: String }, the error of an extern that returnsResult[T, ForeignError].
12.12 The runtime module
core.runtimeholds theextern cdeclarations of the C runtime: allocation and counts, park and unpark, timers, descriptors, helper calls, stacks (section 9). It is one module, so its parts refer to each other freely (section 5.7).- Only core and std may import it. A program never does: it waits through channels and capabilities, never by parking a task itself.
- Its contracts are part of the trusted base (section 8.6), and
verifyfuzzes those of itspuredeclarations. - Three things write without a capability, through the runtime directly: a panic's message and trace,
dbg, and the deadlock report.
12.13 Laws
The laws of core's traits are those above (Eq's, Ord's, Hash's), obligations of every impl. Further laws, sketched, proven on core:
// sorting keeps every element, and only those
law sorted_permutes[T: Ord](xs: List[T])
holds len(xs.sorted()) == len(xs) && xs.all(x -> xs.sorted().count(x) == xs.count(x))
// concatenation keeps lengths
law append_len[T](a, b: List[T])
holds len(a + b) == len(a) + len(b)
// mapping distributes over concatenation
law map_append[T, U](a, b: List[T], f: (T) -> U)
holds (a + b).map(f) == a.map(f) + b.map(f)
// a dict holds what was inserted, and nothing else changed
law insert_then_get[K: Hash, V](d: Dict[K, V], k, other: K, v: V)
holds d.inserted(k, v).get(other) == (if other == k { Some(v) } else { d.get(other) })
// a range has as many elements as its bounds say
law range_len(a, b: Int)
requires a <= b
holds len(range(a, b)) == b - a
13. The standard library
std is the package above core that programs import by use std.…. It is written in Strata, and reaches the outside world only through capabilities. This section gives its outline; each module's own documentation gives the rest.
13.1 Capabilities
| capability | gives | in tests |
|---|---|---|
Console | standard input, output and error; print (section 6.9) | a do-nothing mock, or mock Console with Ghost, which keeps what was written |
Files | files and folders | a temporary folder |
Net | TCP connections and listeners | a mock |
Clock | the time, sleeps, after | VirtualClock (section 9.7) |
Random (built late) | random bytes and numbers | SeededRandom, seeded per test like the scheduler, a concrete test capability (section 6.10) |
Process | arguments, environment, exit code, programs run | a mock |
Terminal | raw mode, size, keys | a mock |
- The runtime gives them to
main's parameters by their full paths, through the entry point the compiler generates for the program. A test asks for them as parameters (section 6.10). - A capability's own code is the only place
assumedis written in std (section 8.1).
13.2 Modules
- Data:
json,toml,regex,unicode,utf8,typing,code. - Programs:
cli(derive CommandLine),term,process,fs,io,time. - Networks:
net,http(a client, and a server with aRouter; handlers run in a task of their own, each request's work in anarena, section 10.3),web(pages as values, live pages throughserve_app). - Concurrency:
actor(initial, update), withaskover aReply(section 9.6); subscriptions send back a receiver (section 9.3). - Numbers:
array, N-dimensional arrays overPacked, with BLAS for products. - Storage:
sqlite,orm(the mapping between records and tables; every operation on theDatabasecapability). - Agents:
agent, an LLM loop with tools. - Calls into Python, Rust and TypeScript are bindings (section 11.2), not std modules:
std.python,std.rustandstd.tsgive way to them.
13.3 Built late
RandomandSeededRandom(std has no random source: session ids are the clock and a counter today).- Streaming HTTP responses: a response's body is
Bytes | Stream(Receiver[Bytes]). - std's
lemmasmoves to core, next to the functions (section 12.6).
14. Commands
The strata command reads, changes, checks, proves, builds and runs code. This section says what each command does, and how it looks to a person at a terminal and to a program or an agent reading its output.
14.1 At a terminal, and elsewhere
Every command behaves in one of two ways, decided when it starts:
- At a terminal: standard output is a terminal (and, for pickers and the editor, standard input too). Output is coloured and highlighted, long output goes through the pager, and a command missing its target opens a picker.
- Elsewhere: a pipe, a redirect, an agent's shell. Output is plain text, never paged, and a missing target is an error saying what to give. Everything a command does at a terminal it also does elsewhere, with the same result: only the presentation differs.
--jsonon every command writes its result as JSON instead, for editors and agents: one object per result, one per line for the commands that stream (check,verify,test,build,run), with the same fields the text shows (place, verdict, message, code as text). The fields are part of the command's interface: one is never renamed or removed without a new version.
Colour and highlighting.
- Code is syntax-highlighted wherever it is shown:
view,find,doc, a counterexample's input, a hole's goal and context, a failed assertion, a diff. Capabilities, and the traits they implement, have a colour of their own. - Verdicts are coloured: proven green, refuted and failed red, fuzzed or unknown orange, a counterexample's input amber. Hashes are dim, holes yellow, removals in a diff red and additions green.
- Colour is on at a terminal when
NO_COLORis unset andTERMisn'tdumb.FORCE_COLORturns it on anywhere.
The pager.
- Output meant for reading (
view,find,refs,doc,history,diff,holes, the help) goes through the pager when it is taller than the terminal: taller than the terminal's whole height, not the space left below the prompt. Shorter output is printed as it is. - The pager is
$STRATA_PAGER, else$PAGER, elseless -FRX, which keeps colours.--no-pager, orSTRATA_PAGER=cat, turns it off. check,verify,test,buildandrunstream their results as they come and never page.editnever pages.
Pickers.
view,edit,find,refs,doc,historyandtour, given no target at a terminal, open a fuzzy picker over what they could act on. Typing narrows the list; Enter runs the command on the choice; Escape gives up (exit 130).- The picker is
fzfwith a preview pane when it is on thePATH, else a numbered list narrowed by typing.STRATA_PICKER=offturns pickers off,=listforces the list. - Each line holds what is matched: a name, its kind, its signature with its contracts, and its doc's first line, so typing any of them finds it.
- The preview is the command's own output for that line, made by
strata pick-preview, so any front end (fzf, an editor, the viewer) shows the same thing. Keys switch the preview where a command has several (below). - The pager starts after the pick, never before.
Exit codes. 0 when there is nothing to report; 1 for findings (an error, a refuted or unproven obligation under --require proven, a failing test, a certificate that doesn't replay); 2 for a mistake in the command itself; 130 when a picker or the editor is given up.
Reader settings live in ~/.config/strata/settings.toml, never in a package: the notations of section 2.4, the indentation and the line width, types and core (section 2.10), how conflicts are shown (conflicts: markers or block, section 4.9), colours, the pager. A command's flags override them for that command.
14.2 Reading code
view [SELECTOR] prints code as section 2.10 says.
- The selector is a package (nothing), a module (
shop), a definition (shop.total), a member or method (Shape.Circle,Money.add), or a binding (sqlite, section 11.2). -l,--level: 0 a map of names and kinds, 1 interfaces (signatures, contracts, docs, laws' statements), 2 everything (the default for one definition).-k,--kind:fn,type,trait,impl,law,test,extern, comma-separated (view shop -k law -l 1lists a module's laws).--types,--core,--proofs(loop clauses,assert … byand proofs, hidden otherwise), and each notation, as one-off settings.- With no selector at a terminal, the picker lists every definition. Its preview is the definition, then what it calls and what calls it;
ctrl-rshows its uses, each inside the definition that makes it;ctrl-tthe tests and laws that name it;ctrl-vthe definition again. Enter prints the choice, through the pager.
find [TEXT] finds names: definitions, members, fields and methods, in the package and its dependencies, bindings included. Each result is one line: name, kind, signature, doc's first line, and its place. With no text at a terminal it opens the picker over every name; the preview is the place shown as code with six lines around it.
refs [NAME] lists every use of what NAME refers to, each shown inside the definition that makes it. --used-by lists the definitions instead. With no name at a terminal, a picker over every name, whose preview is its uses. At a terminal its results open in a picker too, one line per use, whose preview is the definition around that use, highlighted, with the use marked; Enter shows it through the pager.
doc [SELECTOR] shows docs as a reader of the API wants them: a module's doc and its pub definitions' signatures and docs, then one definition's with its laws and examples. With no selector at a terminal, the picker lists every documented name; the preview is its doc.
history [NAME] lists a definition's changes from git, newest first: an uncommitted change first, then each commit that changed it, with its hash, date, author, subject and structural diff. A commit that only re-encoded the file is skipped. -n N shows the last N; --no-patch one line per change, saying what changed in words (body changed, doc changed, added). With no name at a terminal, a picker over the definitions, then a second over that definition's changes, whose preview is the change's diff.
diff [FROM] [TO] shows structural changes, definition by definition: what was added, removed, renamed, and each body's change as code. Renames are shown as renames, since ids say what they are.
tour [FILE] walks through a change (the branch's, by default) page by page, in reading order, each page a definition's change with its context and verdicts. With no file at a terminal, a picker over the pages.
14.3 Changing code
edit [SELECTOR] is the one way code is written.
- Text piped in (
strata edit shop < defs.st): the definitions given replace those of the same names in the module, or are added, names matched in their own scopes (section 3.1). An import line given replaces that import. - At a terminal, with nothing piped in: the selected definitions open in
$VISUAL, else$EDITOR, as text printed under the reader's settings. What is saved is the edit.- With no selector, a picker lists the package, each module and each definition (preview: its text); Enter opens the editor on the choice.
- If the saved text doesn't check, the editor opens again on that text with the errors at the top as comments, each with its line. Saving the text unchanged, or quitting the editor without saving, gives up: nothing is written (exit 130).
- The editor's text is the whole of what was opened: a definition removed from it is removed, and
editlists each and asks before writing. Piped text only adds or replaces;--rmremoves.
- Elsewhere with nothing piped in,
editis an error saying to pipe the definitions in, or to pass--editor. - Writing.
editparses, desugars and elaborates the whole change in memory, checks it with the module and everything that depends on it, and writes only if it checks. A change to several files is written through a journal (.strata/edit.journal): each new file is written beside its old one, then all are renamed into place, and a command started after a crash finishes or undoes the journal first. Oneeditruns at a time per package; a second waits on the package's lock. Every command that changes code goes through this path. - What it says. Each warning shows the text as stored where
editstored something other than what was written: arequiresmade a refinement (section 2.3), a constructor left out, a reordered field refused with the order to write. Each definition, field or member removed is listed. --rm NAMEremoves a definition, and--rm 'use m'an import; piped text never removes one otherwise.
rename OLD NEW, given a definition, changes one entry of a module's names (section 3.2). No code changes, and no other definition's hash. rename refuses a name taken in the scope, and a name that breaks section 5.6's conventions.
Modules. new NAME inside a package makes a module (an empty file), rename given a module renames its file and rewrites every use of it in the package (keys hold the module's path, so a module's rename changes the hashes of the definitions that refer into it, unlike a definition's rename), and edit --rm MODULE deletes an empty one; a module with definitions is emptied by move or --rm first.
move NAME MODULE gives a definition a new key in another module and rewrites every reference to it in the package.
fix writes what the tools can find (and edit writes the loop invariants it finds, listing each among its warnings): loop invariants (section 8.3), contracts made refinements, unused capabilities removed (--dead), each shown as a diff and written through edit's path.
new NAME outside a package makes a package: its strata.toml, a main module, and a .gitignore holding strata.proofs.
revert NAME [COMMIT] puts one definition back as it was before a commit changed it, through edit's path, and shows the diff.
14.4 Checking and proving
check checks the package, or a selector: names, types, mutability, capabilities, the duty to close. It reports each error with its place, the code around it highlighted, and what to write instead where there is one.
verify [SELECTOR] proves obligations (section 8) and streams one line per obligation as it is decided: its place, the condition, the verdict in its colour with the rung that gave it, and for a refuted one its counterexample as code. A law's line shows its /// doc. It ends with the count per verdict.
--rung static|z3|kernel,--require proven,--assumed(lists every trusted contract),--no-cache,--jobs N.
test [NAME] runs tests, each with its capabilities mocked (section 6.10) and its tasks on a seeded scheduler. It streams one line per test with its /// doc. A failure shows the assertion, the values in it, the trace, and the seed; --seed N replays a failing order.
holes lists the holes left in the package, each with its goal, the types in scope, and its place.
14.5 Building and running
build compiles the program to an executable, through LLVM. It verifies what changed first and leaves proven checks out (section 8). --release optimizes; --certify writes the certificate beside it (section 8.8).
run [NAME] [ARGUMENTS] builds what is needed and runs main, or a function given its arguments as code, checked against its parameters' types. --trace shows each call and result. --debug turns dbg on (section 2.8). --copies, --stalls and --memory report copies made between tasks (section 9.6), calls that held a carrier (section 9.13), and memory per place.
main is fn main(…), taking the capabilities it needs (section 13.1) as cap parameters, and returning () or Result[(), E] with E an Error. The program exits with 0 when main returns, 1 when it returns an Err (its message and trace on standard error), and 3 on a panic or a deadlock (the report on standard error), so a program's exit codes never meet strata's own usage error, 2. strata run exits with its program's code; when the program can't be built, it exits 4 and says why.
14.6 Packages and git
setup-gitmakes git merge module files throughmerge-file(section 4.9), and sets a text conversion sogit diff,git log -pandgit showprint module files as code under the reader's settings.- How a pull request is reviewed on a forge that shows only the stored files (GitHub) is open.
updatemoves git dependencies to their newest allowed commits and writesstrata.lock; nothing else changes it (section 5.1).check-certificate FILErebuilds the program from its source, compares the executable's hash, and replays each proof (section 8.8), reporting each that doesn't.
14.7 Laws
Sketched, proven on the command's code.
// a command gives the same result at a terminal and elsewhere: only colour, paging and pickers differ
law presentation_only(command: Command, input: Input)
holds strip_presentation(run_at_terminal(command, input)) == run_elsewhere(command, input)
// edit writes only code that checks, and writes all of a change or none of it
law edit_all_or_nothing(before: Package, text: String)
holds edit(before, text) is Err ==> files_after(before, text) == files(before)
// a rename changes one name and no hash but the renamed definition's text hash
law rename_one_entry(p: Package, from_name, to_name: Name, d: Definition)
holds code_hash(rename(p, from_name, to_name), d) == code_hash(p, d)
// a picker, given up, changes nothing
law picker_given_up(command: Command, p: Package)
requires picker_cancelled(command)
holds files_after_command(command, p) == files(p)