Strata
The next Strata

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.

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

1.2 Tokens

token     = identifier | keyword | wildcard | hole
          | integer | decimal | string | raw_string | f_string
          | module_doc | doc_comment | comment
          | punctuation | newline ;
space     = " " | "\t" ;

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.

The keywords are reserved: none of them can be an identifier anywhere, including as a field name after ..

groupkeywords
definitionsfn type distinct trait impl test law lemma extern pub use as mock derive with blocking pure ghost
bindingslet mut cap comptime move
controlif else match while for in loop return break continue assert dbg except or
valuestrue false is self Self it old
tasksspawn scope await select race supervised
memoryarena frozen
contractsrequires ensures holds invariant decreases where assumed by
proof stepsassume 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.

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.

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+".

1.7 f-strings

f_string      = "f\"" { string_char - "{" - "}" | escape | interpolation } "\"" ;
interpolation = "{" tokens "}" ;

Example: f"{name} has {len(xs)} items", f"\{literal braces\}".

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.
  …
}

1.9 Punctuation

punctuation = "<=>" | "==>" | "..." | "..=" | ".." | "|>" | "**" | "<<" | ">>"
            | ":=" | "->" | "=>" | "==" | "!=" | "<=" | ">=" | "&&" | "||"
            | "+=" | "-=" | "*=" | "/=" | "%="
            | "(" | ")" | "[" | "]" | "{" | "}" | "," | ":" | "." | "="
            | "<" | ">" | "+" | "-" | "*" | "/" | "%" | "!" | "?" | "|" | "&" | "^" ;

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:

  1. The innermost bracket open at that point is ( or [.
  2. The token before the newline is {, ,, or a continuing operator.
  3. 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.

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)

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:

errorexample
invalid UTF-8a 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 number007, 1_, 0x, 12abc, 5u8
an unknown escape"\d"
an escape \u{…} out of range or a surrogate"\u{d800}"
a control character in a stringan LF inside "…"
a string not closed on its line"abc
} alone in an f-string's textf"a}b"
an empty or unclosed interpolationf"{}", f"{x"
{{ in an f-stringf"{{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.

  1. Parsing only ever turns sugar into core. A hand-written match is stored as a match, even when it is written like a handler.
  2. 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.
  3. A type or a constructor left out is inference, not sugar.
  4. 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 fields r gives), 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

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 ] ;
writtencore
T?Option[T]
[]TList[T]
A ! EResult[A, E]
A | BSumType { members: [A, B] }
T where pRefinement { base: T, predicate: p }
{ x: f64, .. }RecordType { open: true, … }

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 } "]" } ;

From tightest to loosest (17 levels):

levelformsassociativity
1literals, names, (e), (e: T), tuples, lists, records, blocks, if, match, lambdas, spawn, scope, await, select, race, comptime e, old e, mock T, holes
2calls f(…), […], .f, .0, .m(…), postfix ! and ?, except and orleft
3**right
4prefix -, !, mut, move
5* / %left
6+ -left
7<< >>left
8&left
9^left
10|left
11.. ..=none
12|>left
13== != < <= > >= isnone
14&&left
15||left
16==>right
17<=>none

Operators are calls of core's traits (section 12):

writtencore
a + b, a - b, a * b, a / b, a % b, a ** bAdd.add(a, b), Sub.sub, Mul.mul, Div.div, Rem.rem, Pow.pow
-aNeg.neg(a)
a == b, a != bEq.eq(a, b), Not { Eq.eq(a, b) }
a < b, a <= b, a > b, a >= bOrd.lt(a, b), Ord.le, Ord.gt, Ord.ge
a & b, a | b, a ^ b, a << b, a >> bBitAnd.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, !athe 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).

2.7 Values made of parts

writtencore
(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, trueGlobal 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"])

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 } ;
writtencore
x := e, (a, b) := eBind
mut total: s64 = 0Bind of a mutable Binding of type s64
x += eAssign { place: x, value: Add.add(x, e) }
mut xs[i] = vEvaluate { Index.set(mut xs, i, v) }
loop { … }While { condition: true, … }
comptime forFor { unrolled: true, … }
dbg eDebug { value: e }
mut grid[r][c] = va 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 = vIndex.set(mut xs, i, RecordLiteral { base: Index.at(xs, i), f: v })

2.9 Handlers

writtencore
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 das x except { d }, x or { d }, for a tight d

2.10 Printing

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)
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 }] }.

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:

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:

Names:

Calls:

Values made of parts:

Control and logic:

Types:

The _type field:

Unfinished 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:

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,
}

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.

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

notationencoding
uintunsigned 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.
inta 64-bit signed integer, zigzag-encoded (0, -1, 1, -2 become 0, 1, 2, 3), then written as a uint.
boolone byte, 0 or 1.
id4 bytes, least significant first: a u32, never 0.
hash16 bytes: the first 16 bytes of a SHA-256 digest.
offset8 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.
bytesa uint length, then that many bytes.
textbytes 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 recordits fields, in the order section 3 lists them.
a suma 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

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

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)
Node = tag:uint  flags:uint  fields

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)

4.6 Tags

tagsnodes
0–6, 8Definition: Function, Extern, TypeDefinition, Trait, Impl, Test, Conflict; Constant is 8
16–51Expression: 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–56Expression, tasks: Scope, Spawn, Await, Select, Race
57–61Expression: Mock, Iff, Arena, Frozen, It
64–70Statement: Bind, Assign, While, For, Assert, Evaluate, Debug
80–88Pattern: Wildcard, Binding, LiteralPattern, NamedPattern, RecordPattern, TuplePattern, TypeTest, Alternatives, ListPattern
96–104Parameter, 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.

hashofchanges when
interface_hashpublic, the variant's tag, and the hashed interface partwhat other code relies on changes: types, signatures, contracts, visibility
code_hashinterface_hash and the hashed body partanything the definition does changes
text_hash, computed when needed, not storedcode_hash, the names of the ids the definition declares (in declared order), and its local names, docs and comments, each written out in fullanything a reader of this definition sees changes, names, docs and comments included
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

4.9 Merging

<<<<<<< ours
  total + tax
=======
  total + tax(rate)
>>>>>>> theirs

edit reads either back as the same conflict, and text with one side chosen resolves it.

4.10 Reading safely

A decoder never crashes on a file. It reports the first of these as an error:

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" }

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.

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:

  1. the locals whose binder is in scope there (section 5.4);
  2. the module's own definitions, including the types and atoms declared in its sums;
  3. the imports: the names use m.{…} brings in, and the module names use brings in;
  4. core's names: every module of core but core.runtime (section 12.1) is imported in every module, as if by use core.task, use core.channel, …, and every pub name of these modules is in scope bare (Task, Sender, Option). core.runtime is never bare, and only core and std may import it (section 12.12). std has no such import: its modules are always imported by use.

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:

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:

bindercovers
a TypeParameterthe whole definition
a function's Parameterits contracts, its body, and the defaults of the parameters after it
a Lambda's Parameterthe lambda's body
a Binding in a Bindthe statements after the Bind in its block, and the block's result
a Binding in an Arm's patternthe arm's where condition and body
a Binding in a For's patternthe loop's invariants and body
a Binding in an Is patternwhat 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 namethe match's arms, their conditions and bodies

5.5 Visibility

5.6 Naming conventions

edit refuses a name that doesn't follow these, and its message gives the name that would:

whatformexamples
types, types declared in sums, atoms, traits, type parametersUpperCamel: [A-Z][A-Za-z0-9]*Order, NotFound, T, R
functions, methods, parameters, fields, locals, tests, modules, packagessnake_case: [a-z_][a-z0-9_]*total, _x, unit_price

5.7 No cycles

5.8 Names when reading

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

typewrittenvalues
core's built-in typesBool, 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 recordtype 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 sumCircle { r: f64 } | Square(f64) | Empty, NotFound | Denieda value of any member
a function type(item: T) -> Ufunctions and lambdas
a refinements64 where it > 0the base's values for which the predicate holds
a distinct typedistinct type Meters = f64Meters(3.0)
a generic type appliedList[s64], Patch[User], Matrix[3, 4]
a packed arrayPacked[f32], for an element type implementing core's Machineelements 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 typeDrawable where Drawable is a traitany value whose type implements it (section 6.6)
TypeTypethe types
NeverNevernone

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:

  1. T <: T, and S <: U with U <: T gives S <: T.
  2. 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.
  3. T where p <: T. T where p <: T where q when p implies q (section 8); until that is proven, the place where it is needed holds an obligation.
  4. Never <: T for every T.
  5. 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.
  6. G[S1, …] <: G[T1, …] when each argument pair agrees with that parameter's variance (section 6.3): Si <: Ti for covariant, Ti <: Si for contravariant, Si == Ti for invariant.
  7. (a: A1) -> R1 <: (b: A2) -> R2 when A2 <: A1 and R1 <: R2. Parameter names don't count. A mut parameter's type must be equal on both sides.
  8. A type implementing a trait used as a type is a subtype of it: Circle <: Drawable when impl Drawable for Circle. A value of a trait type is the value with its impl's method table: passing a Circle where a Drawable is expected pairs it with that table, and a List[Circle] passed as a List[Drawable] is converted element by element, a copy --copies reports.

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:

6.4 Checking

6.5 Narrowing and exhaustiveness

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
  }
}

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] }

6.8 Errors

6.9 Capabilities

6.10 Mocks

6.11 Mutability

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:

7.2 Values and bindings

7.3 Numbers

formatlargestoverflow thresholdrelative error of one roundinghalf the least subnormal
f642^1024 − 2^9712^1024 − 2^9702^-532^-1075
f322^128 − 2^1042^128 − 2^1032^-242^-150
f1665504655202^-112^-25
bf162^128 − 2^1202^128 − 2^1192^-82^-134

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

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:

assumed contracts are never checked: they are trusted, and verify tests them (section 8).

7.7 Compile time and debugging

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):

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.

rungwhatdecides
1. staticone pass over the typed tree: integer ranges, values known nonzero, difference bounds x - y <= c, lengths, Booleans, the variants a value may be made bydeterministic, no search; proves or refutes, else passes up
2. solverZ3 under a budget of 2M resource units per query, on hash-consed termsproves, refutes with a counterexample, or passes up when the budget is spent
3. kernela written proof (section 8.4), checked by the kernel (section 8.5)proves, or fails with the step and goal
fuzzingrandom inputs meeting the requires, for what no rung decidedreported as fuzzed, never as proven

8.3 What the logic means

The solver and the kernel read a program through one translation of its stored tree. Its meanings:

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
}

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   = "==" | "<" | "<=" | ">" | ">=" ;
stepdoes
simplify by l1, l2rewrites 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 freplaces calls of f by its body
witness egives the value for an exists
assume ptakes p as a hypothesis; the goal becomes p ==> goal
assumecloses 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
arithmeticlinear integer arithmetic, after simplifying the facts
nonlinear, bitsnonlinear arithmetic, bit vectors (Z3 as a named oracle)
computeevaluates the goal
autothe ladder

8.5 The kernel

8.6 What is trusted

A verdict "proven" rests on:

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

8.8 Certificates

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

8.10 To measure in the lab

The rules of sections 8.7 and 8.8 bind; the lab measures how they perform:

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
}

9.2 Panics and supervised tasks

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) }
}
// 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(),
}

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(),
}

9.6 Values across tasks

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

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).

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
}
type Placement =
  | Anywhere
  | Here
  | Carrier(Natural)
  | OwnThread

9.10 Stacks

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.

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.

9.12 Locks and the order at a task's end

9.13 Helper threads and blocking calls

9.14 Platforms

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

10.2 Layout

10.3 Arenas

for req in requests {
  arena {
    if req.bad { continue }
    served += 1
    respond(req)
  }
}

10.4 Frozen values

frozen routes as shared {
  scope {
    for connection in connections { spawn serve(connection, shared) }
  }
}

10.5 Values between tasks

10.6 Shared[T] and Weak[T] (built late)

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

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
StrataC
s8 … s64, u8 … u64int8_t … uint64_t
f16, bf16, f32, f64_Float16, __bf16, float, double
Boolbool
() (as a result)void
a handle type, distinct type Statement = Ptra pointer C made
Option[H] of a handlea 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: Ta 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

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)
}
read fromrunsvalues
Cthe headers, by clangin the programas section 11.1; struct → record, enum → sum, simple #define → constant, a pointer to an opaque struct → handle
Rustthe crate's public APIin the program, through glue the compiler generates and cargo buildsstruct → 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
Pythonsignatures, type hints, .pyi stubsembedded, the interpreter served by an actor on: OwnThreadint, 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
TypeScriptthe .d.ts filesin a Node worker processdata as JSON; class instances → handles
//! 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

Foreign values and foreign objects

What crosses from a foreign library is one of two kinds.

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_()
}

11.3 To try in the lab

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

moduleholds
typesBool, Option, Result, Type, Never, the refinements of section 12.2
numbersthe integer and float types, Int, Real, conversions, OutOfRange, the named arithmetic of section 12.4
opsthe operator traits, Eq, Ord, Hash (section 12.3)
textString, Display, Debug, concat, the string functions (section 12.5)
collectionsList, Dict, Set, the ranges, dict, set (section 12.6)
iterIterator, FiniteIterator, Iterable (section 12.7)
errorsError, panic
taskTask, Panic, Placement, carriers (section 12.8)
channelchannel, Sender, Receiver, NoReceiver, Reply
resourceResource, Capability
memoryShared, Weak, Owned, same (section 12.9)
keysKey, key_of, the hashes, KeyPath (section 12.10)
foreignPtr, CString, Packed, Machine, ForeignError (section 12.11)
runtimethe C runtime's declarations (section 12.12); never bare

12.2 Types

typeisso
NaturalInt where it >= 00, 1, 2, … (ℕ with 0)
PositiveInt where it > 01, 2, 3, … (strictly)
NegativeInt where it < 0−1, −2, … (strictly)
NonZeroInt 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.

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()
}

12.4 Numbers

12.5 Text

12.6 Collections

12.7 Iteration

12.8 Tasks and channels

12.9 Resources and memory

12.10 Keys and compile time

12.11 Foreign values

12.12 The runtime module

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

capabilitygivesin tests
Consolestandard input, output and error; print (section 6.9)a do-nothing mock, or mock Console with Ghost, which keeps what was written
Filesfiles and foldersa temporary folder
NetTCP connections and listenersa mock
Clockthe time, sleeps, afterVirtualClock (section 9.7)
Random (built late)random bytes and numbersSeededRandom, seeded per test like the scheduler, a concrete test capability (section 6.10)
Processarguments, environment, exit code, programs runa mock
Terminalraw mode, size, keysa mock

13.2 Modules

13.3 Built late

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:

Colour and highlighting.

The pager.

Pickers.

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.

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.

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.

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

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)