Roadmap

The stages that build the Avin compiler, runtime and Avin-written standard library to the specification.

Approach

The compiler is built to the architecture from the first stage: every program, from main() = 42 on, goes through the real pipeline — resolve, check, lower to MIR, emit — and is linked against the real runtime. Early stages make that pipeline thin and end-to-end; later stages widen it. No stage builds a temporary path that a later stage has to tear out.

Stages

Each stage is one or more bounded items. Each ends green on the full gate and is merged to dev with --ff-only.

#StageDelivers
0SpecificationThis specification, the architecture, this roadmap, the project reset
1Skeleton and test harnessThe compiler/, runtime/ and library/ packages; the lexer and parser carried over; avin parse, check and build; a thin end-to-end pipeline (main() = 42 and println of a literal) through resolve, check, MIR and the LLVM emitter, linked with a minimal runtime; the Sysl-written execution-test driver in sysl test (.avin cases with expected output, run at -O0 and -O2)
2Type core and scalar programsThe Type enum over symbols; scopes and symbol tables; local bidirectional inference with subtype constraints and Nothing; integers with trapping overflow, byte, real, char, bool, unit; functions, local functions, if/match/loops, guards, scalar patterns and coverage; unbounded generic functions; by-name parameters. The old execution corpus, revised to the specification, joins the suite here
3Modules and packagesavin.hocon loading, multi-file modules, imports and visibility, the prelude as an Avin file, @intrinsic declarations
4Runtime and heap valuesThe collector over sh.sysl.gc with shadow-stack roots; type descriptors; traps with messages and locations; string as a runtime value, with s"…" rendering the built-in types; data layouts, tuples, lambdas and closures with environments; by-name parameters
5Object modelclass, trait, object, impl, methods, override, open/abstract, constructors with checked initialization, companions, member access, type patterns; overloading, default and named arguments; infix method calls
6Monomorphization and dispatchBounded generics, closed-world instantiation, dispatch for generic trait methods, reified headers, variance checking, devirtualization
7Sysl bindings@sysl declarations, shim generation, the cached shim build, boundary conversions, opaque handles, diagnostics mapped back to bindings
8Core library in AvinEq, Hash, Ord, Display, Debug, Writer, Option, Result, Either, ?, string methods, println, debug, StringContext and interpolators, interpolation and formatting
9Collections in AvinIterable/Iterator (Iterator is Iterable), Seq, List, Vector, Array, Buffer, Deque, Set, Map, Range, builders, views, literals built through them, ::, list and sequence patterns, for comprehensions
10Test runner and toolingavin test, avin run, project and package commands, avin lsp
11System libraryavin.io, avin.fs, avin.process, avin.time and the rest over Sysl bindings
12Actors and state machinesactor declarations, messages and their scheduling in the runtime; machine and state declarations, transitions and their checks
13C bindings@c bindings called directly from Avin’s code, checked against the library’s headers by a clang-compiled C unit; C libraries in the manifest; handles, strings, out parameters, buffers and callbacks from C threads; avin-lang/mlt (MLT 7) and avin-lang/cairo (Cairo 1.18) as the stressors, with avin-lang/freetype (FreeType 2), which Cairo’s FreeType font faces depend on
14Lightweight threadsEvery thread a lightweight thread with a stack of its own, run by a scheduler over a few operating system threads, waits that park, time-slicing at safepoints, sockets on a poller, actors’ turns and the server library on top, as settled
15Linuxx86_64-linux and aarch64-linux as targets, and machines in packages, by the twelve items of the Linux plan: close-on-exec in the lookup, machine conditions in the manifest, files for one machine and avin.target, the Linux image, the compiler, runtime, corpus and platform tests on Linux, the target in cache keys, Linux CI, Linux releases, and cross builds

Until stage 8, println in stage 1 was an @intrinsic over a runtime entry point, declared in Avin source like every other intrinsic; stage 8 replaced it with the library’s println over Display.

Status

StageState
0Done
1Done
2Done: local bindings and assignment; integer arithmetic with trapping, wrapping and saturating operators; bitwise operators and shifts; integer literals of any width, one among the branches of an if, the arms of a match or the elements of a collection literal taking the type the others decide; byte, real and char with their operators, comparisons and conversions; comparison chains; &&, `
3Done: a directory as a program’s root, each directory under it a module named by its path, its files sharing one namespace and headed by module a.b (the root directory’s files the root module, without a header); a single file a program by itself; import a.b.X and import a.b.{X, y as z} per file, import a.b and import a.b as c binding a whole module, reached as b.X for any public declaration in expressions, types and patterns, unknown, private, self-module and clashing imports rejected; export a.b.X, export a.b.{X, y as z} presenting another module’s public declarations (types, aliases, classes, objects, traits, machines, every overload of a function, values, variants) as names of the exporting module, the very declarations, in every file of that module and to its importers by name or through the module, chains of exports followed to the declaration, two paths to one declaration no clash, a module exporting a declaration presenting its module’s extensions, and private, unknown, whole-module, self-module, root-module, private, clashing and cyclic exports rejected; member exports in a class, an object or a data type’s plain impl (export f.m, export f.{m, n as k}, export f.*, private export), a use the type’s own members do not answer checked as x.f.m (calls with overloads, defaults and named arguments, reads, assignments, method values, operators), through a field or a method of no parameter list read at every use, chained by name and by wildcard, an export by name implementing a trait’s method, completion and go-to-definition following the export, and unknown, untyped, private, clashing, shadowed, misplaced and cyclic exports rejected; private top-level declarations, seen in every file of their module only; a file’s names resolved through its module, then its imports, then the public declarations of avin, loaded from library/ as an ordinary module tree with the prelude one of its files; program modules named avin or under it rejected; conformances checked against the module of their type or trait; an impl that only adds methods written in any module, an extension in another module than its type’s or trait’s, its methods seen by its module and by files importing the module or a declaration of it, called directly with no reach into the type’s private members, one a type’s own method always hides rejected where declared, two seen modules’ extensions of one signature rejected at the call naming both, and its private methods its module’s; companions kept to their class’s or data type’s module across files; modules importing one another in cycles, with module values initialized in dependency order across the program; object-file symbols carrying the module path; packages: avin.hocon manifests read and checked with each error at its line, git dependencies fetched at their tags into the machine’s cache with the highest version asked for chosen, or pinned to a commit by rev (abbreviated or full, one commit one package, two commits or a commit and a release refused), path and workspace dependencies, a dependency’s modules under their own names without its root files and tests, one module in two packages and nested manifests kept apart, avin.sum checked and added to, workspaces with one selection and one sum file, and every command finding the package by walking up from its path (format details Proposed); the standard library’s modules read as a compilation needs them: the prelude, then only the library modules the program, its dependencies and the modules read import, to the end, in the library’s own order, an import of a module under avin the library does not have reported at the import with the modules where it would be, and the language server reading the whole library for a library file or a completion; members of a repository (member naming a directory, each member a package of its own, <coordinate>//<dir>, selected and summed separately, every member at one version read from one clone whose hash its line carries, a fetched member’s workspace = true and in-repository path siblings read as their own coordinates at its version, its sysl-dependencies reaching the program as any package’s do, and avin add <coordinate>//<dir>); and avin vendor copying the resolution into vendor/ at the project’s or workspace’s root, each copy checked against avin.sum first and what is no longer read removed, a vendor/ present being read in place of the cache with a package it lacks refused rather than fetched, and the root’s vendor/ never a module.; and features: a manifest’s features (doc, default, modules, enables, requires, and name = [x]), optional dependencies, "dep:x" and "dep/feature", each error at its line, a dependency entry’s features, default_features = false and -x, every request for a package added together across the graph, workspace members included, a module a feature that is off lists not read, an import of a gated module or an optional dependency’s module allowed only where the importer’s gate implies it whatever is selected, the package’s tests importing any of its modules with a test module read only while every module it imports is, an import refused for its module reported once however many names it imports, --features, --no-default-features and --all-features on build, run, check, test and vendor, and avin test, avin check, the language server, avin tidy and avin vendor with every feature on; a program of one file’s dependencies header (// avin.hocon and the comment lines under it, a manifest’s dependencies block), resolved, fetched and summed into <file>.sum as a manifest’s are, read by run, build, check, test, tidy and the language server, refused at its line when malformed, not at the top or in a file of a package or a program of many files, and avin vendor refusing a program of one file; a first line beginning #! passed over, and avin <file> ... (the form a #!/usr/bin/env avin line runs) for a file with one giving every argument after the file to the program, avin run keeping its options
4Done: the collector over sh.sysl.gc, with exact roots on a shadow stack per thread, reached through each thread’s context, which every compiled function takes as a hidden first argument, collection when allocation since the last collection reaches what survived it, a heap limit, and the whole pages of large free runs given back to the system after a collection (gc 0.4.0, AVIN_GC_RELEASE); type descriptors for data variants; data types, generic and recursive, with constructors, field access on one-variant types, variant patterns nested to any depth and exhaustiveness over variants; variants reached through their type, Shape.Circle(1.0), Option[int].None and m.Color.Red, in expressions and patterns beside the bare name, a name that is none of the type’s variants reported with the ones it has, and a variant with fields written without parentheses in a pattern reported as its bare name is; variant names shared by several data types of one module (and by machines’ states), a bare use decided by the expected type (parameter, binding, result, field, element, the other operand of a comparison, the matched value in a pattern) and refused with the types and qualified forms where nothing decides it, shared names imported or reached through their module; a nested call’s unknown settled by the call around it; functions defined by clauses, with inline guards and guard blocks; comparison patterns and n + k; exhaustiveness over integers, bytes and chars by the values their literals, ranges, comparisons and n + k patterns leave out; extractor patterns, Name(p…) on a value whose type implements a core extractor trait, BoolExtractor or Extractor (an unapply answering a bool or an Option, its value matched whole or as a tuple’s parts) or SeqExtractor (an unapplySeq answering an Option of a sequence), the conformance and not the method’s name making the extractor, a trait’s value, a bounded type parameter, a data type’s impl and a subclass included, and a value implementing none reported with the trait to implement, the matched value held in a local and the method called once per test, nested, guarded, in is, clauses and match functions and never counting toward exhaustiveness; rest* and _* ending a sequence pattern or an unapplySeq extractor’s patterns, a list’s tail or what drop answers, with exhaustiveness over every sequence type by the lengths its sequence patterns cover; tuples, made on the heap like a one-variant data value, with parts read by position, tuple patterns, tuples without parentheses where they fill a line, destructuring bindings and multiple assignment; strings as references to constant objects or heap objects, joined with +, compared by their bytes, and matched by literal patterns; s"…" interpolation of the built-in types, lowered directly to rendering and joining; function types, and functions as values: lambdas, with parameter types written or taken from the expected function type, a lambda of n parameters taking apart the n-tuple a function of one parameter expects (an overload that needs it chosen only where none takes the lambda as written), and named, local, generic and intrinsic functions; closures that hold copies of the values they capture and share the vars, which a closure’s capture moves into a box on the heap; calls of function values through each closure’s entry; closure identity with ===; by-name parameters, each argument a closure with no parameters evaluated at every read, forwarded unevaluated to another by-name parameter, with the mode part of a function’s type; traps that flush the output and print avin: trap: <reason> at <file>:<line>:<col>, each trap site constant data with its own cold block, shared by every instance of a generic. A delayed argument that cannot escape still keeps its environment on the heap rather than the caller’s stack. The thread runtime: contexts attached and detached by each thread, a gc chunk held by each thread’s carrier, which its context points at, so that small objects are allocated with no lock (gc 0.3.1), one lock around claiming chunks, collection and the lists of contexts and carriers, stop-the-world collection with each other thread parked at a safepoint or in a safe region, and safepoint polls on every back edge and before every call that may recur, found from the call graph’s strongly connected components; programs start threads through avin.threads (stage 11)
5Done: def, a keyword optional before every function and method declaration (after the modifiers, on the signature of one defined by clauses), and the one way to declare a top-level or local function with no parameter list, def now -> int = … or def now = …, read by its bare name and run again at each read, with no function value, no type parameters and no assignment, the parentheses after it calling what it yields, the only function of its name in its scope, read through its module as clock.now, and the declaration written without def refused naming it; default and named arguments, each default a function of the parameters before it, declared beside its function and checked in the function’s declaration scope, called at each call that omits the argument; named arguments after positional ones, in any order, with the written arguments evaluated in the order written and then the defaults in parameter order; named fields for variants; defaults of by-name parameters delayed. Repeated parameters (values: T*), a Vector[T] inside the function, made at the call through the core library’s vector builder from the positional arguments from its position on, or one Iterable[T] spliced with xs* (a vector of that type passed as it is), on functions, local functions, clauses, methods, impl methods and class constructors, generic element types inferred from the arguments, an overload without one preferred, and the core library’s max and min over them. Final classes with constructor parameters as fields (plain private and immutable, val public, var public and mutable, private var); the class body as the constructor, running statements and field initializers top to bottom; body fields with declared or inferred types; methods in every function form, clauses and type parameters of their own included, with the implicit receiver and self; member access, assignment, compound assignment and ++/-- on fields; privacy per class; generic classes, their type arguments inferred or written; the constructor as a function value, and a data variant with fields as one too (bare, qualified or with type arguments, typed from the expected function type, a companion’s apply and the variant chosen between as at a call); === on objects, and ==/!= on class instances, objects and closures comparing identities (rejected between types with no common class); a field read in the body before its declaration rejected. Overloading of top-level and local functions, resolved statically to the most specific overload that accepts a call, with literals and lambdas tried against each candidate, generic overloads compared by the same rule, an overloaded function value chosen by its expected type, and each overload a symbol of its own named by its parameter types. object singletons, made before main, with fields, methods and privacy as a class’s, passed as values of their own types; companions, the class’s name in call position its constructor and otherwise the companion, each using the other’s private members; companions of data types, of one variant or several, a variant of the type’s name its constructor in call position and the type’s impls and the companion each using the other’s private members, an object named after another type’s variant or a fieldless variant of its own type’s name rejected; an object’s apply methods called by its name, a companion’s overloading the class’s constructor or the data type’s variant of its name by the ordinary rules (by-name, defaults, repeated parameters, generics, trailing blocks, written type arguments the chosen candidate’s), one with the constructor’s parameter types rejected where declared, and the name where a function type is expected the constructor or apply that type chooses; module-level vals and vars; every global initialized before main after what its initializer reads through the functions it calls and the lambdas it makes, with a cycle reported by its chain; globals that hold references kept as roots of every collection. Class inheritance: open and abstract classes, one superclass after : with its constructor arguments (generic ones with written type arguments), construction from the top down through each class’s initializer, inherited fields leading the subclass’s, override checked against parameter types with covariant results, abstract methods, super.m(), subclass instances conforming to their superclasses (arguments, tuples, if and match joins, ===), and virtual dispatch through a method table placed before each class instance’s descriptor. Traits: abstract methods and default bodies, required traits, generic traits with written type arguments, classes and objects conforming after the superclass in the : list and subclasses inheriting the conformance, override on every implementation, two inherited implementations of one name rejected unless overridden, trait-typed values as plain references (arguments, tuples, vars, ===, if and match branches agreeing on an expected trait), and dispatch through a position each trait has in every conforming class’s method table, chosen once for the whole program; a trait’s variance is checked and used in stage 6. Any: every value converts to it where it is written (arguments, bindings, assignments, fields, results, tuple parts written out, branches), boxed where it is not already an object, with == and === rejected on it; type patterns x: T and _: T in match, clauses and is, matching built-ins, strings, tuples, data types, classes (subclasses before superclasses) and traits, generic instances told apart by their type arguments, downcasts from a trait’s or an open class’s type, never-matching patterns rejected, and coverage counting only a pattern whose type the value already has; each type a record of its ancestors, tested by one comparison or a scan of the ancestors (== on Any came with stage 8). impl: methods added to data types, classes, objects and built-in types (impl string, in the core library’s module), with the implicit receiver, self and a one-variant type’s fields by bare name, and private impl methods; impl Trait for Type for data types, classes and objects, its methods implementing without override, a conformance stated once whether in a header or an impl; generic impls naming the type’s parameters (impl[T] Source[T] for Box[T]); data types dispatching through a method table every variant’s descriptor carries, fieldless variants included, and matched by t: Trait patterns on Any. Methods as values: a method named without a call, on a value or by bare name inside its class or impl, a closure holding the receiver, evaluated once where the value is made, of the method’s type without the receiver; for class, object, trait, open-class (calling the override through the method table) and impl methods, built-in types’ included, generic classes’ with type arguments from the receiver, and a method’s own type parameters written or taken from the expected type; private methods only where they could be called. The initialization check, run once every body is checked: through a class’s or object’s last field initializer, self only reads set fields and assigns fields, with method calls (bare, self.m(), super.m()), method values, self passed, stored or returned, and lambdas, by-name arguments and local functions that use it rejected; an open or abstract class’s whole body held to the same limits, calling after its last field only methods that cannot be overridden and are safe, found by a fixed point over every method’s body. Overloaded methods in classes, objects, traits and impls, built-in types’ included: a call chooses among the methods of its name the receiver’s static type has, inherited and trait methods included, by the rules for functions, with the class’s type arguments known from the receiver; each overload a symbol of its own and a method table position of its own, overriding, trait implementation and dispatch matched by name and parameter types; an overloaded method used as a value chosen by its expected type; two abstract overloads in a row parsed as two declarations rather than clauses. Infix method calls: a m b is the call a.m(b), resolved as the dotted call (overloads, dispatch, impl methods, generic methods), binding between ranges and comparisons and grouping left, continued onto an indented block only after a line ending with the method’s name; a postfix use, a method of another arity, a name that is not a method of the receiver’s type and a name starting a later line rejected with the dotted form to write. Trailing blocks: an indented block after a call’s line given to the callee’s last parameter, as a by-name parameter’s delayed expression or as the body of a lambda whose parameters end the line, past defaulted parameters, with named arguments and in overload resolution, on functions, methods and function values, a callee with no other arguments written without parentheses; never in the header of a form whose body follows, nor where a local function’s header or an infix continuation already reads the block; a last parameter that is neither by-name nor a function, already given or absent rejected. Methods named by symbols: an operator the longest run of operator characters, any run that is not the language’s own a method’s name, declared in classes, traits, objects and impls and called infix or dotted, binding at the level of the operator its first character belongs to, or tightest with a ~ anywhere in it, a name ending in : grouping right with its receiver on the right and its left operand evaluated first, left- and right-grouping operators of one level mixed without parentheses rejected (comparisons and is among them); a declared precedence, `@precedence(“
6Done: declared variance on the type parameters of data types, classes and traits. An instance of a generic type is one of another instance where each type argument follows its parameter’s variance and both arguments are references (List[Dog] is a List[Animal], List[int] is not a List[Any]), through superclasses and traits with their arguments substituted; tuple parts are covariant and function types take contravariant parameters and covariant results on the same terms; two branches agree on the instance whose covariant arguments agree. Declarations are checked: a +T only in method results, immutable fields and parents’ covariant arguments, a -T only in method parameters, neither in a mutable field, with positions flipping through function parameters and following other types’ variance; private members included, and the methods an impl adds to an open or abstract class, which are in its method table (Vector‘s :+, +:, ++, updated and toArray taking a lower-bounded W >: T). Type patterns match through variance: each record lists, besides its ancestors, the tested types it conforms to by variance. Bounded type parameters, [T: A & B], on functions, methods, classes, data types and traits, each bound a trait or a class, at most one a class, none written twice, & the one spelling (+ between bounds and A & B written as a type each rejected with the form to write): a bounded value has its bounds’ methods (required traits’ included), trait vals and a class bound’s fields, with overloads, defaults, infix calls, own type arguments and method values, and passes as its bounds’ types; type arguments held to their bounds where written in declarations and at calls, with a bound’s own type arguments inferred from the argument; each instance calling its type argument’s implementation directly, through the method table only for a trait type or an open class; a method’s own bounds checked as contravariant positions. A function’s or a method’s own type parameter bounded by a type parameter declared before it, [J: I], at most one: a J is an I with no conversion and has I‘s bounds, each type argument is held to be the bounding one’s or seen as it as a covariant part is, one decided where a value is passed in takes the bounding argument where that is the narrower (`err
7Done: top-level functions bound with @sysl("module.name"), their parameters and results integers of 8, 16, 32 and 64 bits, byte, real, char, bool, unit, string, Array[byte] (copied each way), Array and Vector of the other boundary types (copied element by element, into Sysl as a slice and out of a slice or a Buf into a new array or vector, nested to any depth), an Array of bytes, integers, reals, booleans or characters as a binding’s own parameter filled by the Sysl function (copied into a writable slice and back after the call, the shim keeping the array as a root meanwhile), every other array going in as a []const slice so that a Sysl type that would write into it is refused at the binding, Option and Result of boundary types, tuples of boundary types (a Sysl tuple of the same arity, converted part by part, nested in the other shapes and in mirrors’ fields), and data declared with @sysl("module.Name") mirroring a Sysl enum or struct; integer results, mirrors’ integer fields and the integers a result’s options, results, collections and tuples hold converted from any Sysl integer, with a check that stops the program at the binding’s call where a value does not fit; a real rounded into any Sysl floating-point type (f32, f16, bf16) as a parameter, a mirror’s field or a callback’s answer, and widened out of any as a result, a field, a callback’s parameter or a value a result holds; a generated Sysl shim per binding that converts each value and calls the Sysl function at the binding’s types, passing the arguments by position or, for a binding marked named, by each parameter’s name, so the parameters it leaves out take the Sysl function’s own defaults, with one conversion per data type and direction, built with the runtime by sysl build-c into one archive the program links in place of the runtime’s; Sysl’s diagnostics of a shim reported at the binding, or at the mirror for its import and conversions; the archive cached by a hash of the shims, the Sysl version and the runtime’s source; bindings to Sysl packages other than the standard library, which a manifest names in sysl-dependencies (by release, commit or directory, gathered over the whole package graph, the cache keyed by each one’s release, commit or directory sources, and the C libraries they name with @link or require through pkg_config linked into the program); Array[byte] results out of a Sysl []u8 or []const u8; opaque handles, classes declared with @sysl("module.Type"), on a Sysl struct, a trait or an instance of a generic one (@sysl("module.Signal[string]"), its type arguments boundary types that are one Sysl type each), whose objects hold one counted Sysl reference in an untraced word (a trait object’s two words in a cell that word points at), made by the bindings that return one directly, in an Array, a Vector, an Option or a Result, or as a part of a tuple that is one of these (a collection out of a Sysl slice or Buf, each element a handle of its own), passed back to Sysl as a parameter of a binding or of a handle’s method (shared as the counted reference where the Sysl type has a destructor, otherwise as the Sysl parameter takes it) or as the elements of an Array or a Vector that is one (each checked as a handle passed by itself is, and shared for the call as a slice of what the Sysl parameter takes) or as a mirror’s field by itself (passed and checked as a parameter is, and out of Sysl made a handle of its own), with methods without a body bound to the Sysl type’s methods (a view they answer converted before any local holds it), methods with a body written over them, close() giving the reference back, a bound method on a closed handle or a closed handle passed as a parameter or a mirror’s field trapping at the call, and a finalizer per handle class, named in its descriptor, giving back the reference of an object the collector frees unclosed; each handle owned by the code that made it, a second word of its object compared with the context’s owner word at every use (a bound method, a handle passed as a parameter, close()), trapping “Name belongs to another thread” where it differs and the handle is not in transit, ownership handed by the runtime’s walk of what a thread’s body or a pool task reaches, its own owner whichever worker runs it, and put in transit when the body returns, by a future’s completion and by a callback’s registration; bindings and handle methods declared blocking, whose shim converts the arguments and takes each handle’s own counted reference, makes the Sysl call with the thread safe for the collector, and converts the result once it is running again, a view of bytes copied before it leaves; Avin functions passed to a binding’s parameter of function type (a lambda, a closure, a method value, a top-level or local function), handed to Sysl as a closure the shim makes, which keeps the function a root while Sysl holds it and gives it back when Sysl drops it, converts each argument out of Sysl and the answer into it, and runs the function through an entry the program defines with the C convention, on the calling thread: the giver’s code only, or any thread for a parameter marked @threaded (whose function is held to capturing only sendable vals and parameters, a value of a @sendable function type and a parameter marked @sendable taken as they are, and whose binding is blocking whether or not it says so), a thread Sysl started attached for the call, a thread in a blocking call made running for it, a call from elsewhere trapping. A callback’s integer answer is converted, with a check that stops the program at the binding’s call, into whatever integer the closure Sysl takes answers, an unsigned one included (a Sysl &Fn() -> u32 takes an Avin () -> long); a closure answering a generic Sysl function’s type parameter answers the Avin type, the shims built once more where Sysl could not infer one. A binding’s integer parameter, and a handle method’s, is converted the same way into whatever integer the Sysl parameter is, an unsigned one included (syslui’s colours, u32), a blocking call converting it while the thread is safe; a parameter of a generic Sysl function’s type parameter, and every integer parameter of a call that left a type argument uninferred, passed as the Avin type; values narrower than 32 bits passed and answered sign- or zero-extended as the C convention says. Generic bindings: a binding’s type parameters bounded by Boundary, the core library’s structural bound for the types that cross as one Sysl type each (integers of 8 to 64 bits, byte, real, char, bool, unit, string, mirrors, and options, results and tuples of these), held at each call and passed on through a generic function’s own bounded type parameter, every type parameter that is not so bounded refused where it would cross, with one shim per instantiation that Sysl checks at its types (a Sysl bound’s refusal reported at the binding); generic handle classes, @sysl("m.Signal") class Signal[T: Boundary], a handle with its own finalizer on each instance the program uses, mirrors among its type arguments, with bound methods at every instance and methods with type parameters of their own; and a callback whose closure takes a type parameter of the Sysl function given its parameters’ types by the shim, which is built again for as long as each build finds more to say.
8In progress: Option, Result and the right-biased Either (with Either.cond, and Option.toRight/toLeft/okOr/okOrElse, and Result.toOption beside ok) in the core library, written in Avin, with their methods, lower-bounded where the reference library’s are (getOrElse[B >: T], orElse, contains, zip, Either’s flatMap and filterOrElse, Result’s flatMap and orElse); ? on either, returning None or the Err from the enclosing function or lambda, where the error passed on must conform to the function’s error type. String methods in impl string, in library/avin/string.avin: byteLength, charCount, isEmpty, nonEmpty, startsWith, endsWith, contains, slice, toUpper, toLower (the names char has for its own), trim, strip, stripLeading, stripTrailing, repeat, replace, padTo, stripPrefix, stripSuffix, capitalize, stripMargin, head, last, headOption, lastOption, indexOf, lastIndexOf (of a string or a char), indexWhere and lastIndexWhere (an offset, -1 when there is none), toInt, toLong and toReal (trapping on a string that writes no number) and toIntOption, toLongOption and toRealOption (answering with Option), the character-wise methods (map, flatMap, filter, filterNot, foreach, exists, forall, find, takeWhile, dropWhile, span, partition, splitAt, tail, init and the lazy charIterator), split by a char and with a limit, stripLineEnd, compareIgnoreCase, toInt and toLong (and their Option forms) in a radix from 2 to 36, and toBool and toBoolOption, written in Avin over intrinsic methods (the length word, a checked byte load, and the runtime’s slicing, repeating and searching, each lowered at its call so a trap reports the caller’s line) and Sysl bindings for casing, replacing and Unicode white space; string.fromUtf8, answering with a Result whose Utf8Error(offset, truncated) mirrors Sysl’s, and string.fromUtf8Lossy, both bound to Sysl’s UTF-8 decoders; chars() and bytes() as vectors, utf8 as a new byte array, split and lines; a length or size asked of a string answered with an error naming charCount and byteLength, and * between a string and an integer with one naming repeat; a string capped at the largest int bytes; the core library’s functions compiled only as a program reaches them. Writer, FormatSpec, Display and Debug as library traits in format.avin; print of any value and debug over Debug, both library functions; toString() as Display‘s default body; StandardOutput, writing integers without a string, and StringWriter, growing its text in place; the built-in types (every integer width, byte, real, char, bool, unit, string) implementing both, a value too wide for long rendered in chunks of eighteen digits, honouring a field’s width and side, strings and chars quoted and escaped by Debug; built-in types conforming to any trait through an impl, as bounds, each instance calling the impl’s method directly, every method of the trait implemented since a built-in takes no default bodies; s"…" holes of any Display type, type parameters bounded by it included, rendered through toString(), and a hole of any other type rejected; defaults of variant fields; abstract methods yielding unit written as bare signatures in traits and classes. Eq, Hash, Ord: Eq and Add, Sub, Mul, Div, Rem, Neg as library traits, the built-in types implementing those their operators have; the closed core trait Integer, whose members are every iN and which nothing implements or names as a parent, requiring the arithmetic traits, Ord, Display and Debug, implemented for every width at once by the core library’s impls over the integer family (impl[T: Integer] Ord for T, allowed only there), each width’s instance calling the family’s method directly and its operators the machine’s; a parameter bounded by Integer converted to and from the other integer types (long(x), T(n)), each instance converting at its width; operators on data types, classes and type parameters through them, < and the rest defaulting from compare; every type comparing and hashing, by value (tuples and data types field by field, through a function made per instance), by identity, or through its own equals and hash, a type implementing one of them implementing both; == and the hash on Any, trait-typed values and open classes decided at run time through equality entries in each type record. Values of Any and of every trait are Display and Debug (as bounds, as receivers of display, debug and toString() and in interpolation, as every type is Eq, without being values of either trait), shown by the type they have at run time through rendering entries in each type record: the type’s own implementation, or its name for a type with none. derives Eq, Hash, Ord, Display, Debug on classes (over the constructor parameters, Eq and Hash together, Ord beside an Eq) and data types (Ord by variant and then by field), a generic type’s Ord, Display and Debug conditional on its type arguments, written out as methods and impls before anything is declared, Display and Debug as Name(a, b) through each field’s own form and padded whole to a width; each field held to the derived trait and named when it falls short; a trait derived and also implemented, unknown or repeated rejected; equals and hash called on values of any type parameter. Derivation through shapes: derive Trait for T templates in a trait’s module, checked once as an impl over T bounded by the trait and Shaped (a bound nothing else may write), and copied for each derives entry naming the trait, its T the deriving type, its names resolving in the trait’s module and its errors reported once, at the template, or at the entry; every data type and class deriving through a template or carrying annotations given its type, variant and field shapes as private module values made before main; T.shape(), T.variantOf(x), T.walk(x, v), T.walkPair(a, b, v) and T.build(b) written for the deriving type’s variants and fields, checked in its file, calling the visitor’s or builder’s field (and missing) hook once per field at its own type, directly, each field held to the hook’s bound and named at the derives entry when it falls short; build reading fields in any order, defaults seeing the fields before them, duplicate and missing from the builder, an index out of range a trap, refused for open and abstract classes; generic types bounded by the trait, recursive types, classes over their constructor parameters; annotations on types, classes, variants, fields and class parameters as values of types implementing Annotation, an unknown name an error. Every data type’s Display and Debug without derives, conditional on its type arguments, replaced by an impl of its own (so Option and Result show as their variants and the collections keep their own forms), a type whose field lacks the trait left without it and a use needing it naming the field; a data type’s trait implementations compiled only when called and a method table position filled only once a call goes through it, so a program that never shows a value carries no rendering code. derives Enumerable through the core library’s template, for a data type whose variants have no fields: T.values() as a Vector in declaration order, ordinal(), name() (the declared name, whatever Display writes) and T.valueOf(name) answering an Option, reachable through an E: Enumerable bound; a variant with fields, a type parameter or a class refused at the derives entry. Tuples are Display, Debug and Ord where their parts are, through core impls over each tuple family, impl[A0: Ord, A1: Ord] Ord for (A0, A1), written by the compiler for every arity from two up to the widest tuple the program writes, a tuple meeting one where its parts meet the impl’s bounds: (a, b) through each part’s own form and padded whole, ordered part by part, with < and the rest. Built-in values, strings and tuples as values of the traits they implement, converted where a trait is expected as to Any (a number, char, bool and unit boxed, its box’s descriptor holding the type’s method table through entries that read the value out; a string and a tuple as they are), so a call through the trait, == and a type pattern reach the value’s own type, and an Any matches a trait its value implements; every string, literal or made at run time, has the program’s descriptor for strings, with the type record of string and its table; overloads taking a trait accept such values, one taking the value’s own type the more specific; print, println, eprint and eprintln of any value, Any, trait-typed and types with no Display of their own included, one or several separated by , , each shown as interpolation shows it; an integer literal fitting an Any parameter of an overloaded function. An interpolated string p"…" is the call StringContext(parts).p(holes), with the parts as written (library/avin/string_context.avin); s, f and raw are its methods, and a program adds an interpolator with a trait and its impl for StringContext. Text blocks, """ … """, plain and after every interpolator’s name: the incidental indentation and each line’s trailing blanks dropped in the lexer, \ at a line’s end joining lines where escapes are read, and the formatter writing each block back byte for byte. s"…" and f"…" are written out directly to Writer calls into one StringWriter, each hole rendered by its Display, or its Debug under %?, with no value boxed; f"…" specifiers (flags - + space 0 #, and , grouping a decimal integer’s digits in threes, a width and a precision in digits or as holes counted when the program runs, conversions d i x X o b f e g E G c s ?) are parsed and checked against the hole’s type as the literal is compiled, and StringContext.f reads them as it runs; FormatSpec carries the flags and the conversion, integers of every width format in every base in Avin and reals through the runtime’s exact formatter. ? converting an error through From, a core trait with one static member, from: the enclosing function’s error type’s conformance at the error’s type, or the one most specific at a type the error is a value of, a type parameter’s through its bounds, and its absence or several equally specific named in the error. A generic trait whose members are all static implemented by one type at several type arguments, by impls and in a class’s header, for data types, classes and built-in types, each conformance held to every member at its own type arguments; a call on the type picking the member by its parameter types, and through a type parameter bounded by several instances, the instance whose member the arguments fit, each instance of the code calling its type argument’s member for it. Option, Either and Result are Ord where their parts are (None before every Some, every Left and Err before every Right and Ok, two on one side by their values), so they sort, have max and min, key a TreeMap and sit in a derived Ord. Options of classes and strings kept as bare pointers when an Option[Nothing] reaches one nested inside another value (a Vector[Option[Nothing]] used as a Vector[Option[Dog]], a Result[Option[Nothing], E], a function yielding one, and through options, tuples, data fields and map values): Option[Nothing] takes the form of the options it is seen as there, null beside pointers and an object beside objects; a program seeing it inside other values both ways, or as an option of a type parameter, stores every option as a full object (correct, slower). Done, the core of union types (settled 2026-11-09), tested to its matrix: the union type in annotations and aliases with its precedence beside ->, the parenthesized type-pattern form, and `
9Done: the collections’ pure accessors are parameterless methods (xs.head, xs.size, m.keys, xs.toVector), with iterator(), toArray() and toBuffer() keeping their parentheses, and so are the rest of the library’s pure accessors (the rule: opt.get, r.isOk, s.trim, c.isDigit, n.abs, date.year, T.values through a type parameter); Iterable[+A] and Iterator[+A] (hasNext, next, an iterator its own iterator(); head, last and their Option forms on every Iterable, a sequence and a sorted collection reaching the end at once) in the core library; Array[T], invariant, its elements stored unboxed at their own widths after the length, traced element by element when they are references, made by Array.fill, Array.tabulate and Array.empty with every element set, with length, apply and update (bounds-checked, trapping at the caller), slice, copy, lift, isEmpty and an iterator, == and the hash by contents (=== identity) and Display and Debug as [1, 2, 3] where the elements have them; xs(i) through apply on any type that has one, and xs(i) = v, its compound and := forms and ++/-- through update; Range of int from a..b and a..<b values, with by, isEmpty and an iterator, a zero step trapping; for over a range written in place (any integer type, counted with no allocation), a Range value, an array (indexed) and any Iterable (through its iterator), with patterns, break and continue, and several generators, if guards and value definitions written out as the loops they nest into; Nothing written as a type. List[+T] in the core library, Cons(first, rest) or Nil: x :: xs, right-associative between the bitwise operators and ranges, always the core library’s Cons with its element type inferred as the variant’s call infers it; [] and [a, b] built as a list where a List is expected; head :: tail, [] and [a, b] patterns, mixing (a :: [b, c]), nested, in match, clauses and every pattern position, covered as the variants they stand for; isEmpty, nonEmpty, head, headOption, tail, last, length, apply, lift, reverse, ++, map, flatMap, filter, foldLeft, foldRight, take, drop, exists, forall, find, contains, foreach, toArray and an iterator, every one a loop, so a million-element list needs no deeper stack; == and the hash by contents and lexicographic Ord, each a loop; Display and Debug as arrays have them. The Builder trait, with clear, sizeHint and knownSize. Immutable Map[K, +V] and Set[A], data types over a persistent binary trie of spread hashes, lookups a loop and updates copying one path: get, apply (trapping), getOrElse, contains, updated and incl, removed, ++, keys, values, filter, map, mapValues, foreach, union, intersect, diff, subsetOf, iteration as Iterables, Map.empty, Map.newBuilder, Set.empty and Set.newBuilder in their companions, each builder typed as a Builder of its collection so a literal’s expected type settles its bounded type arguments. Mutable Map[K, V] and Set[A] in avin.collections.mutable, open-addressed tables probed linearly with backward-shift removal: m(k) = v and its compound forms, remove, getOrElseUpdate, clear, addAll, copy, filter, toMap and toSet. All four compare and hash by contents and display as {a: 1} and {1, 2}, their Debug as {"a": 1}, where the parts have them. A newBuilder[T]() in the companions of Vector, Buffer, Array and List (with List.empty), the list’s adding in constant time. List(1, 2, 3), Set(…) and Map((k, v), …) through their companions’ apply. Buffer[T], growable and mutable over an array whose spare capacity is zero bytes never read, doubling when full: addOne, append and +=, addAll, appendAll and ++=, prepend, prependAll, insert, insertAll, sizeHint, remove (clearing the vacated element), clear, apply, update, lift, length, toArray, toVector, an iterator, == and the hash by contents, Display and Debug as arrays have them. Vector[+T], immutable, covariant and persistent: a radix-balanced tree of read-only FrozenArrays of 32, with a prefix and a suffix at every level of six depth classes, each array exactly sized and never written once in the tree; apply and updated (one path copied) in time in the depth, :+ and +: in amortized constant time, slice, take, drop, takeRight, dropRight, splitAt, tail and init in time in the depth through one slicer that shares every array it does not cut, ++ in time in the shorter operand, a builder making each array once, leaf-walking iterators forwards and backwards, and map, filter, collect, flatMap, foldLeft, foreach, exists, forall, count, contains, indexOf, toArray, toBuffer, == and the hash by contents, Display and Debug; crossing to Sysl, a vector is read a leaf at a time and made from an array through the core library’s functions, their addresses passed to the shim with the layouts. ArraySeq[+T], the immutable sequence over one FrozenArray, each change a copy, with toArraySeq on every collection. mkString(sep) and mkString(start, sep, end) on every sequence, set and map (a map’s entries as pairs, through Iterable‘s) of Display elements, and max and min (trapping when empty) and maxOption and minOption on every sequence of Ord elements, each through an impl bounding the element type. The methods an impl adds to a class whose fields are all immutable are not variance positions. Every trap inside the core library, fail and failed checks alike, reports the program’s call that last entered the library, through the context’s caller site: set by the program’s calls that may enter the library (direct, through a method table or of a function value), kept by the library across its calls that may run the program’s code, at no cost to calls between the program’s own functions. Sequence literals: a List where one is expected, the expected collection’s newBuilder() where it implements the core trait Buildable itself (every library collection, the program’s own through an impl, a type parameter bounded by it), an expected collection without it reported by the trait’s name, and otherwise the core library’s Vector; elements take the expected element type, or agree on one as if branches do; an empty literal settled by a later use or reported; a literal compared with == or an ordering takes the other operand’s type. Seq[+T], the core trait of List, Vector, Array, Buffer and Deque: length and apply abstract, and lift, isEmpty, nonEmpty, head, headOption, last, lastOption, foldLeft, foldRight, foreach, exists, forall, find, indexWhere, count, toVector, toList, an iterator and reverseIterator written once over them, a list overriding each with a walk; contains, indexOf, mkString, max and min written once on Seq through impls on the trait. Sorting, every sort one stable bottom-up merge sort over insertion-sorted runs of 16 with one scratch array: sorted(), sortBy(key) (the key computed once per element) and sortWith(compare) on every Seq answering a Vector, a list’s own answering a List, and sortInPlace(), sortInPlaceBy and sortInPlaceWith in place on arrays, buffers and deques, with sortedDescending and sortInPlaceDescending() for Ord elements; the other in-place operations: remove(i, n), trimStart, trimEnd, filterInPlace, mapInPlace, patchInPlace, reverseInPlace and, for Eq elements, subtractOne on buffers and deques (the wrap-around of a deque’s ring checked against a buffer for every start and length), reverseInPlace, mapInPlace, fillInPlace and an overlap-safe copyTo on arrays, and length(), isEmpty() and clear() on StringWriter. Function types as parents: a class or trait lists one after :, a data type or class names one in an impl, checked for an apply of that signature, for one function type per type and for variance; every Seq[T] is an (int) -> T, every Set[A] an (A) -> bool, every Map[K, V] a (K) -> V, immutable and mutable, and every PartialFunction[A, B] an A -> B, with no conversion, a call of a function value running its descriptor’s call entry, a closure’s code or the type’s apply. Sequence patterns ([], [a, b], nested, with literals and ranges) on every Seq, reading the length once and each tested element by index, in match, clauses and is. Deque[T], a ring over an array doubling when full: prepend, append (and addOne), removeHead and removeLast (trapping when empty), prependAll, appendAll, insert and insertAll, apply, update, clear, toArray, toVector, contains, indexOf, == and the hash by contents, Display, Debug and mkString, Deque.empty, Deque.newBuilder and literals. for with yield: generators separated by commas or one to a line in a block, each with if guards, yield on the for line, on a line indented under it or after the block, checked as withFilter, flatMap and map calls on the sources, so the first source decides the result and any type with those methods works; withFilter a lazy view on lists, vectors, arrays, buffers, deques, sets, maps (entries as pairs) and ranges, Option‘s its filter; flatMap on the library’s collections taking any Iterable; map and flatMap added to arrays, buffers and deques, to ranges (yielding vectors), flatMap to vectors and sets, and maps’ map and flatMap over pairs; generator patterns matching every element; return, break, continue and ? rejected inside one; value definitions, pattern = value with their own guards, after any generator, evaluated once per element, a val beside the element where no guard follows and otherwise paired with the element through map for the guard to see, a rebound name or a leading definition reported; the mutable Set and Map given withFilter views and the map a map over pairs, so a comprehension over any mutable collection makes a new one of its kind. match functions: a match with nothing before it, one arm on its line or an indented block, a lambda over its arms where a function of one parameter is expected, its arms covering every value, and where a PartialFunction is expected the core library’s MatchPartialFunction, its arms partial, one lambda testing them for isDefinedAt and one yielding Some of the matching arm’s value for calls, lift and applyOrElse; PartialFunction[-A, +B] with isDefinedAt, a call trapping at the program’s call outside its domain, lift, applyOrElse and orElse; collect on lists, vectors, arrays, buffers, deques, ranges (yielding vectors), sets, maps (entries as pairs) and options, and collectFirst on every Iterable; a match that misses values naming one of them as a pattern. A companion from(xs) on every immutable and mutable collection (List, Vector, ArraySeq, Queue, HashSet, TreeSet, OrderedSet, BitSet, HashMap, TreeMap, OrderedMap, Buffer, PriorityQueue and the mutable maps and sets), Vector.iterate, Vector.unfold and List.unfold, and toSortedSet and toSortedMap on every Iterable of ordered elements or pairs. OrderedMap[K, +V] and OrderedSet[A] (traits SeqMap and SeqSet), the immutable maps and sets that iterate in insertion order, over a hash trie from key to slot and a vector of slots compacted when gaps outnumber the entries. TreeMap[K: Ord, +V] and TreeSet[A: Ord] in the core library, over a persistent tree balanced by weight, each side at most three times the other, lookups a loop and updates copying one path with its rotations: every method Map and Set have with the same traits, iteration in ascending key order, headOption, lastOption, head, last, firstKey, lastKey, minAfter, maxBefore, rangeFrom, rangeTo, rangeUntil, range, iteratorFrom and reverseIterator, the slices made by splitting and rejoining the tree, filter by rejoining its kept parts, map, collect and flatMap into tree collections of Ord keys, a hash equal to the hash-based collection’s of the same contents, empty, newBuilder, apply and literals. BitSet, an immutable SortedSet[int] over words of 64 bits (library/avin/bit_set.avin), with the set algebra a word at a time, toBitMask, BitSet.fromBitMask, and a negative element trapping on incl; and the mutable avin.collections.mutable.BitSet with add, remove, addAll, the compound assignments and the in-place algebra unionInPlace, intersectInPlace, diffInPlace and symmetricDiffInPlace. The mutable avin.collections.mutable.TreeMap and TreeSet, holding an immutable tree and replacing it at each update, with the mutable Map and Set API, the ordered queries, removeFirst, removeLast and their Option forms, and iteration that goes on over the collection as it was when the loop began. Map[K, +V] and Set[A] traits, with the hash-based HashMap and HashSet and the tree collections conforming through SortedMap and SortedSet, which re-declare the updating methods with sorted results: the methods putting a value in take [W >: V], an update through a trait answers the same kind, map, collect and flatMap through a trait answer hash-based collections, literals, Map(…), Set(…), empty and newBuilder make the hash-based ones and the sorted traits’ companions and literals tree ones, and maps and sets of different kinds with equal contents are equal (through the traits and Any, by the library’s anyCollectionEquals) and hash alike. == and the hash written once on Seq: two sequences of one element type, of any kinds (Vector, List, ArraySeq, Array, Buffer, Deque, Range, a program’s own), are equal when their elements are equal in order and hash alike, a comparison between two kinds checked and lowered as the library’s seqEquals at the element type, a Seq-typed value and an abstract Vector included, and the per-type comparisons and hashes removed. Range of int a Seq[int]: length, apply, contains, lift, head, last and their Option forms answered from its bounds in constant time, a length beyond int trapping while its ends and indices are still answered, and every method written once on Seq, sequence patterns, == and the hash working on it. Views: view() on every Iterable, a lazy iterator over the collection, and flatMap, collect and withFilter added to Iterator beside its lazy map, filter, take, drop, takeWhile and dropWhile, with zip taking any collection, so a view composes element by element, computes nothing until read, stops reading at what it was asked for and is forced by the conversions; a comprehension over an iterator is an iterator; size and length on an Iterator count the elements remaining and use it up. size, knownSize (-1 when the count needs a traversal) and sizeCompare(n) on every Iterable, overridable so the answer through Iterable[T] is the collection’s own, counting by iteration by default, and size beside length on every sequence. Set and map literals: {a, b} a Set and {k: v} a Map unless the expected type names another collection, built through that collection’s Buildable conformance (TreeSet, TreeMap, the mutable ones, a program’s own), {} the empty one expected. NumericRange[T: Integer], the range of any integer type other than int, made by a..b and a..<b where the bounds are integers of that type (a literal bound taking the other’s type, bounds of two types rejected) with a step of type T: a Seq[T] whose lift, apply, head, contains and isEmpty are answered from its bounds in constant time at any width without wrapping, whose iteration never passes either end of the type, and whose length traps beyond int and last and length for a span beyond long. Nothing is still to come for ranges. object Iterator (empty, single, iterate, unfold, continually, from over any integer type, fill, tabulate), each computing an element when it is read; an iterator’s lazy ++/concat, scanLeft, grouped, sliding, distinct, distinctBy, zipAll, padTo, tapEach, flatten of an iterator of collections, and buffered() answering a BufferedIterator with peek()/peekOption(); on every Iterable, the eager scanLeft, tapEach, partitionMap, span, grouped/sliding (through the iterator’s), concat and flatten of a collection of collections, answering vectors. avin.collections.mutable.LinkedMap[K, V] and LinkedSet[A], the mutable map and set that iterate in insertion order, with the whole mutable Map and Set API, putLast, moveToEnd, headOption, lastOption, removeFirst and removeLast (the last two trapping when empty), safe removal during iteration, and the same display, equality and hash. Queue[+T], the immutable first-in first-out sequence of two lists, in library/avin/queue.avin: enqueue, enqueueAll, dequeue, dequeueOption, front, frontOption, own-kind map, filter, filterNot and flatMap, Queue(...), Queue.empty and Queue.newBuilder, and Eq, Hash, Display and Debug as any sequence. LazyList[+T], a memoized lazy list (each cell evaluated at most once and its expression dropped once it has been; a cell is one object of three words, made with the one function that evaluates it and filled in place by it through the core library’s field_unset fields, read with no lock): LazyList.empty, cons with a by-name tail, the companion’s from, iterate, continually, unfold, fill and tabulate with Iterator‘s names and argument orders, toLazyList() on every Iterable; lazy map, filter, filterNot, take, drop, takeWhile, dropWhile, zip, zipWithIndex, ++ with a by-name right operand and flatMap; +:; head #:: tail, right-grouping at the cons level, through the language’s operators a companion declares with a by-name right operand (# an operator character, passed over when a name’s level is decided), and a cell read while it is being evaluated trapping with a message about the lazy list; forcing length, apply/lift, force and every Iterable method, all in loops, so a million cells are walked without deepening the stack; Display/Debug showing the evaluated prefix and … without evaluating. A map’s map and flatMap to non-pairs answering a collection, on every map, its filtered views and in comprehensions, chosen by a lambda’s body when the overloads agree on its parameters; every collection’s and iterator’s flatMap taking an option-making function into its own kind (a map’s into a map where the options hold pairs), flatten on collections and iterators of options, and an option’s flatMap of a collection-making function answering a Vector, so comprehensions mix collections and options. BigInt, a whole number of any size written in Avin (library/avin/big_int.avin): limbs of nine decimal digits, schoolbook multiplication and long division, the five operators, floorDiv/floorMod/divRem, pow, gcd, lcm, abs, sign, isZero, toRadix, toLong/toInt and their Option forms, toReal, Numeric, Ord, Eq and Hash, made from any integer width, from text in any radix (BigInt(text, radix), BigInt.parse), and written by the integer conversions %d, %x, %o, %b with every flag; a type’s static member called on its name beside its companion object (BigInt.zero()). Integers meet a type that takes them (FromInteger, which BigInt implements): a literal of any size and base where one is expected (val f: BigInt = 1), and an integer of any width beside one under the arithmetic operators, compound assignment, the comparisons and ==, on either side (f *= i, i * f, f == 0). BigDecimal, a decimal of any size and scale written in Avin (library/avin/big_decimal.avin) over an unscaled BigInt and a scale that is never negative: exact + - *, / to 34 significant digits half to even (exact where the quotient ends within them), div at a scale, divSignificant, exactDiv answering None for a quotient that never ends, %, divRem and pow; the seven-mode Rounding data type (HalfEven the default) for round(places), roundSignificant(n) and the divisions, by name; equality, ordering and hash by value across scales, with scale, unscaled, precision and stripTrailingZeros; plain-digit toString, %f with precision and flags, BigDecimal(text)/BigDecimal.parse with exponents, fromRealExact and fromRealShortest, toReal, and toBigInt/toLong/toInt toward zero with their Option forms. Decimals meet a type that takes them (FromDecimal): a real literal where one is expected read exactly from its spelling (val price: BigDecimal = 19.99), and a BigInt beside one under the operators and comparisons on either side; a real meets one only by an explicit conversion.
10In progress: avin run builds into a directory of the program’s own in the user’s cache directory (.avin/build/ beside it only on a machine with none), which avin clean removes (--all every program’s), kept by every build within AVIN_CACHE_LIMIT (5G by default) by a sweep at most every ten minutes that evicts least recently used entries (none used within the hour), removes interrupted builds’ debris, killed builds’ temporary directories and other versions’ caches three days after their last use, rebuilds an entry gone from under a build rather than linking a path to nothing, with avin cache info, trim and clean [--older-than <age>] [--packages], reuses an executable whose sources, library, runtime and compiler are unchanged, and forwards output, arguments and exit status (128 and the signal for a trap); avin test checks and collects top-level @test functions, builds one executable whose main runs the test its argument numbers, runs each test in its own process, and reports ok/FAIL by file with the trap’s reason and the test’s output, a filter by name or file, and the exit status; tests answering with a Result[unit, E], failing on an Err at the test’s name; main answering with a Result whose Ok is unit, an integer type or Nothing and whose error has Display (a union’s members each), an Err written to standard error as error: and its Display and exiting with 1; @test‘s should_trap (with or without the text the run must print), timeout (killing the test’s process) and ignore (reported as skip, counted in the summary); @setup/@teardown around each test, the teardown in a process of its own after a test that trapped, and @setup_all/@teardown_all once around a module’s tests, each failure reported against the hook; @tests files, checked by every command and built only for tests, whose declarations only tests, hooks and other @tests files may name, with impls only for their own types and traits; assert and assertEq in the core library, with a trap reason made at run time; -O0/-O2 on build, run and test; avin new <dir> [--lib] scaffolding a program or library package with a module, a test and a .gitignore; avin add <coordinate>[@<version>] recording a git dependency in the manifest, fetching it and adding its hash to avin.sum; avin tidy [--check] rewriting avin.sum to what the package resolves to; a manifest’s avin, the least Avin the package builds with, held for every package of the graph and reported on the manifest by the language server; avin lsp, a language server over standard input and output that answers diagnostics, hover, go-to-definition, the document outline (local functions nested, tests marked), the workspace’s symbols by subsequence, folding ranges, references, highlights, rename, semantic tokens and completion from the checker’s own analysis (a rename edits every file of the program, follows a method to what it overrides and implements, and refuses the library, a keyword and a clash found by checking the program as the edit leaves it), re-checking the whole program with the library on each change; completion checks a copy of the text with a stand-in name at the cursor and answers the scope the checker had there, in about 130 ms in the largest library file. Literate .lavin sources are read wherever .avin files are, by every command, the corpus and the language server, at the document’s own positions; avin tangle prints the program, and avin weave renders the document as HTML with the program coloured by the lexer. avin doc writes a program’s (or with --std the standard library’s) API documentation as static pages from the checker’s own record of its declarations: a page per module, every public declaration with the header hover shows and its doc comment as Markdown, the impls each type has, exports, a type in a signature linked to the declaration the checker resolved it to (across modules, into dependencies and the standard library, or --std-url), links to declarations written in doc comments, a search box, and --check failing on a link that leads nowhere or an Avin block that does not parse. The core library’s own tests, a program of @test functions in library/tests that is no part of the library programs are compiled with, run by the gate at -O0 and -O2: Option and Result, the string methods, format specifiers, List, Vector across the lengths where its tree deepens, Map and Set with colliding hashes, TreeMap and TreeSet, Buffer, Deque and the mutable Set added to or removed from themselves, and stable sorting at every run and merge width. avin fmt [--check] [<path>...] and the language server’s textDocument/formatting write one style over the lexer’s tokens: two spaces a level (a literate file’s program inside its four-column margin, its prose untouched), the spaces between tokens, at most one blank line and one between multi-line top-level declarations, comments kept, and lines past 120 characters broken one list item per line (a sequence or set literal of short literals and names filled, as many to a line as fit) or before a binding’s loosest operators; the result is parsed and its syntax tree and tokens compared with the source’s before it is given back, and every source file of the tests and the library formats so, stably. textDocument/rangeFormatting formats the whole lines of the top-level declarations a range touches, and edits nothing else. Not yet: textDocument/onTypeFormatting A build compiles a program’s LLVM text as parallel codegen units, each unit’s object cached by its text, so an edit recompiles only the units it changed (tui’s top example at -O2: 12.7 s to 6.4 s from an empty cache and 5.9 s after a one-line edit, with clang’s part about a second). Incremental builds, designed in the pipeline: every build, run and test keeps each instance’s code and text in the program’s build cache and takes an unchanged instance’s from there (AVIN_INCREMENTAL=off or verify), items 1 to 7 of its build plan. Debug information, designed in the pipeline: avin build -g and avin emit-llvm -g describe every function the source declares (literate documents and generic instances included) with its lines and its parameters and locals, and on macOS dsymutil writes the .dSYM, so lldb stops at an Avin line, shows the Avin call stack and reads the variables. Still to come for it: a location in the stack overflow report, and each unit carrying only the metadata it names (both proposed). Still to come: the whole-program passes run only where an instance’s facts changed, and, if measured to matter, the front end (item 8). Done: avin repl, an interactive session: a growing program whose imports, modules (one per declaration of types, and per function or val that uses no local of main, which later declarations call and read, each keeping the version it was declared after) and main (each input a block nested in the last, so a name may be entered again) are checked, built at -O0 through the instance cache and run after each input, the earlier inputs’ output passed over, an expression’s value shown with its type as res0: int = 42 and a val‘s by its name, a trap or an ended program leaving the input out, diagnostics and trap places shown in the input as typed, :type, :imports, :load, :reset, :help, :quit, a multi-line editor with history and Tab completion from the language server’s at a terminal, and a package’s modules importable. Still to come for it: one live process loading each input as a shared object, so earlier inputs are not run again (their side effects repeat, unseen, and a value they compute afresh, a random one or the time, may differ from the one shown); a var that declarations can reach; code of main keeping a type declared again apart from the earlier one.
11In progress: avin.process, with args() as a Vector[string] of the arguments after the program’s name, programName(), env(name) as an Option[string] over one Option-returning Sysl binding, environment() as a Map[string, string] over sysl.env.vars, a Vector[(string, string)] across the boundary, and exit(code) of type Nothing, flushing standard output first; the runtime keeps the arguments main is handed, checked as UTF-8 at startup, and a test sees none. The execution corpus passes arguments to a program from an // args: line. avin.io‘s IoError(kind, operation, subject), its ErrorKind the failures a program tells apart and Other(text), showing as cannot read nope.txt: no such file or directory, every error of avin.fs, avin.process, avin.signal and avin.net naming its path, program, process or address, and CommandError.Failed its command; the core Error trait (message, cause, a display chaining the causes), implemented by every library error type, and Result.context(text) with ContextError, over unions and E: Error bounds and ? into Result[T, Error]; avin.fs over Sysl bindings, with a private mirror of Sysl’s error converted into it: whole files read and written as text or bytes, appended to, removed, exists, isDir and isFile, createDir, createDirAll, createTempDir, removeDir and removeDirAll, rename (replacing the destination in one step), and listDir, the names of a directory’s entries as a Vector[string] sorted by code point, each failure a Result‘s Err. Open files in avin.fs: File, made by open, create, append, openUpdate and createUpdate over sysl.fs.File, with size, position, seek, seekToEnd, read(max), readAll, readText, readLine and readCompleteLine through a buffer of its own, write, writeText, flush and close; a file closed by the collector when forgotten, every call on a closed one, a read of a write-only one and a write to a read-only one an Err, a file that grew since a read reached its end read on from there; readBytesFrom(file, offset), readTail(file, maxBytes) starting at a whole character, and readTailLines(file, count). Standard input in avin.io, read through readLine(), lines() and readAll() from one buffer the runtime holds, lines ending at \n or \r\n, ill-formed UTF-8 replaced with U+FFFD; readSecret, readSecretBytes and readSecretOrLine in avin.io, a line typed at the controlling terminal with echo off, the terminal put back on every way out (a signal included) and the read serialized with standard input’s; io.stdin(), io.stdout() and io.stderr(), the standard streams as a byte Reader sharing the text readers’ buffer and lock and as unbuffered ByteWriters that keep printed lines whole and answer ConnectionReset for a reader that has gone, standard input a Readiness any thread may wait on in a select or Selector (buffered bytes, the end and descriptor 0 making it ready) with readAvailable(max) reading only what is there, and closed standard descriptors opened on /dev/null at start; eprint and StandardError in the prelude, every write to standard error flushing standard output first; the execution corpus feeds a program its NAME.in sidecar and otherwise empty input, and a test run by avin test reads empty input. Source in avin.io, a trait read by lines(), chars() and readAll(), each taking up where the last stopped: Source.fromFile reading the file whole through fs.readText, every failure the Err, Source.fromString, and Source.stdin() over standard input’s shared buffer, its characters decoded one at a time by the runtime as its lines are, U+FFFD for each ill-formed run. avin.threads: spawn(body, stack) starts a closure on an operating system thread with its own context, attached before the thread starts so the closure is always a root, and gives back a Thread[T] whose join() waits safe for the collector and gives the same result every time, from any thread; scope(body) joins every thread started through s.spawn, which traps from any thread but the scope’s own or after the scope has closed; a trap in any thread stops the program once, with one flush and one report; the program ends when main returns. The corpus runs threads under GC stress and in parallel with budget collections. Synchronization in avin.threads: Mutex[T] owning its value, reached through with, get, set and update, over a runtime futex lock taken with one compare-and-swap when free, a second take by its holder trapping; Condition from a mutex’s condition(), with wait, notify and notifyAll, a wait without the mutex trapping; sequentially consistent Atomic[T] of any type, load, store, swap and compareAndSet each one LLVM atomic at the value’s storage width (a value wider than 64 bits under one runtime lock), update and the integers’ add and sub a compare-and-set loop trapping on overflow; Channel[T], bounded or unbounded, with send, trySend, receive, tryReceive, close and isClosed, iterable until closed and drained; the rendezvous, Channel[T](0), handing each value from a waiting sender to a waiting receiver (a plain send or receive on a condition of its own, or a select’s arm that a partner claims through select_claim once its round is tried, a select met mid-round woken to try again), with the try and timed forms, select pairing both ways, close, cancellation and the deadlock report’s “waiting to hand a value to a receiver” (channel_rendezvous*, deadlock_rendezvous_*); Once with run and isDone; the rest of the synchronization kit, each over the runtime’s parking lock and conditions: WaitGroup (add, done, wait, timed waitFor, pending, trapping below zero), Semaphore(permits, capacity) (acquire, tryAcquire, timed acquireFor, release trapping beyond the capacity, withPermit giving its permit back when a cancellation stops its body), RwLock[T] (read, write, and get, set and update for a sendable value; writers first, with the readers a write kept waiting let in before the next writer; a write body uncancellable as a mutex’s, a read body stopped and its share given back), Pool[T, E] (resources made by create up to maxSize and lent by use and lease, always taken back, also on a cancellation; waiters served first come, first served; timeouts, validate, broken leases, idleTimeout with minIdle, warm, evictIdle, close waiting for lent resources, stats; isolated resources whose handles move to each borrower) and Barrier(parties, action) (reusable, its action run by the last arrival under the lock, wait answering whether the caller was last); the waits that keep state of their own (a read-write lock’s, a barrier’s) wait through the runtime’s settling condition wait, which answers a cancellation with the lock held again so the waiter takes itself back before it stops; a condition’s waitFor(timeoutMillis), through a timed runtime wait over the lock, which is a Sysl Mutex. Every wait is safe for the collector, keeping what it sleeps on as a root. Future[T] and Promise[T] in avin.threads, on a pool of workers, a module’s lazy val, started as work comes, one per processor, with a worker started in place of each one waiting in await while work is queued: Future(body), the companion’s apply, with a by-name body written in place or as a trailing block, Future.successful, await() and await(timeoutMillis) as an Option, isCompleted, value, onComplete on a pool thread, map, flatMap (so for … yield over futures), zip, Future.all in the order given, Future.first, and mapOk and flatMapOk on a future of a Result; a promise’s future, complete trapping a second time, tryComplete and isCompleted. The runtime publishes the strings, arrays, locks and conditions it makes with a release fence, and the core library ends the fill of an array it makes with the array_publish intrinsic (Array.fill, Array.tabulate, Deque.toArray, the growth of a buffer or deque). lazy val at module level and in class and object bodies: a state word per value (a module-level global, or a hidden field beside the value with the initializer’s closure), read with one sequentially consistent load and a branch once ready; the first reads call the runtime, which claims the word with a compare-and-swap, makes other threads wait safe for the collector, traps a thread that reads a value its own initialization is computing, and marks it ready with a release store; module-level lazy values outside the eager initialization order, their readers depending on what the initializer reads. Local lazy vals in blocks: each declaration makes a cell, the core library’s LazyCell, whose initializer slot takes the lambda computing the value, so a read is the cell’s lazy field and a closure that captures the name shares the cell; the name is in scope in its own initializer, a self-read trapping, and a @sendable closure capturing one holds the initializer’s captures and reach to its own rules. avin.time‘s clocks and durations, step (1) of its build plan: Duration(micros) with Duration.Zero, Min and Max, the makers micros, millis, seconds, minutes, hours, days and weeks and the same methods on int and long (2.hours), toDays() … toMillis() and toHoursPart(), toMinutesPart(), toSecondsPart() and toMicrosPart() dropped toward zero, toSecondsReal, isNegative, isZero and abs, arithmetic through Add, Sub and Neg, d * n, d / n and d / e (a long), and the text in the largest of s, ms and us (0s for none); Instant(epochMicros) as the wall clock, read by now(), with Instant.Epoch, Min and Max, epochSeconds, epochMillis and epochMicros as makers and counts back rounded toward negative infinity, t ± d and later - earlier, and the ISO 8601 text with Z, the fraction only where there is one and years outside 0 to 9999 signed; monotonic() a Duration, two runtime clock readings beneath; every maker and step leaving a long of microseconds trapping; both types ordered, equal and hashed by value. Every delay is a Duration: Future.await and Condition.waitFor take one beside their milliseconds, a part of a millisecond waited for whole; a command’s deadline and the actors’ timers and restart windows are monotonic() readings. avin.regex, written in Avin: a reader for the whole pattern language (literals and every escape, \Q…\E, classes with ranges, nesting and intersection, the predefined, POSIX and Unicode general-category classes over a mirror of Sysl’s Category, every quantifier greedy, reluctant and possessive, capturing, named, non-capturing and atomic groups, the four lookarounds with bounded lookbehind, back references by number and name, the anchors and boundaries, inline and scoped flags imsxdu and comments mode) into a syntax tree, with the established dialect’s error descriptions and indices; a compiler from the tree to an array of operations (single-character loops, counted repetition of one-length groups, loops for the rest), and a backtracking matcher over the text’s code points with a backtrack stack of its own, an array of frames, so a repeated group over a million characters takes no deeper a call stack, and a step budget for each attempt at a start that traps, naming the pattern and the budget, on catastrophic backtracking, and the checked searches (tryMatches, tryFindFirstIn and the rest of the try family, trySplit on Pattern too) answering a Result with a MatchError instead, the budget ending the whole search through lookarounds and atomic groups; Regex with matches, findFirstIn, findFirstMatchIn, findPrefixOf, findPrefixMatchOf, findAllIn (a MatchIterator), findAllMatchIn, unanchored, anchored, withStepLimit, regex, pattern and toString, Regex.compile answering a Result, the string method r, and Match with byte offsets and Option groups; replacing and splitting: replaceAllIn with a replacement or a function of the match, replaceFirstIn, replaceSomeIn, the replacement syntax ($n, ${name}, backslash escapes) with the dialect’s trap messages, split and Pattern.split with a limit, Regex.quote and Regex.quoteReplacement; a regex as an extractor, unapplySeq answering the groups’ texts where the whole text matches (any part, unanchored), and Groups taking apart any Match; Unicode scripts, blocks, the binary properties beyond the general category (Alphabetic, Uppercase, Lowercase, Ideographic, Word, Alnum, the emoji properties), the U flag’s Unicode classes and word boundaries, and grapheme clusters (\X, \b{g}), over run tables generated from the Unicode Character Database 17.0.0 by scripts/unicode_tables.avin and decoded on first use; the library’s tests hold a conformance table over every construct. avin.math: Pi, E and the elementary functions on real (roots, exponentials and logarithms, pow and hypot, the circular and hyperbolic functions and their inverses, atan2, floor, ceil, rint, abs, max, min, signum, and the angle conversions, then round to a long, trunc, log2, the explicit fused fma, copySign, ulp, nextUp and nextDown), each a binding to one runtime function over Sysl’s Float methods, NaN and the infinities following IEEE 754 and nothing trapping. The integer methods, written in Avin in one impl for every width: abs, sign, pow, gcd, lcm, floorDiv, floorMod, bitCount, leadingZeros, trailingZeros, isPowerOfTwo and toRadix; and the bitwise and shift operators on a type parameter bounded by Integer. avin.random, written in Avin: Random, PCG32 on the reference stream over a long state with the wrapping operators, Random(seed) reproducing the published sequence and Random() seeded by one runtime function over the host’s entropy; nextInt and nextLong, their bounded forms and between on int, long and real unbiased by rejection (64-bit draws through i128), each bad bound trapping at the program’s call; nextReal from 53 bits, nextBoolean, nextGaussian by the polar method over avin.math, nextBytes, alphanumeric, shuffle by Fisher-Yates, choose, chooseWeighted (an index or an item of a pair, by running totals of the weights) and Weighted for repeated draws, and setSeed; the companion’s methods on one shared generator in a module’s lazy val Mutex, seeded by the platform on first use. avin.crypto over Sysl’s sysl.crypto: sha256, sha512, sha1 and md5 of bytes or of text as UTF-8, hmacSha256 and hmacSha512, toHex, and the incremental hashers Sha256, Sha512, Sha1 and Md5 (update, a repeatable finish, update afterwards trapping), tested against the NIST vectors (empty, abc, the 448-bit and 896-bit messages, a million a), RFC 4231, Unicode, every byte value and every split point. pbkdf2HmacSha256 and pbkdf2HmacSha512 (RFC 8018, bytes or text, over sysl.crypto‘s PBKDF2 through a runtime shim, trapping on fewer than one iteration or a length outside 1 to 255 digests), saslPrep (RFC 4013 over RFC 3454’s tables, generated from the RFC by scripts/stringprep_tables.avin; NFKC, prohibited and Unicode 3.2-unassigned code points, the bidirectional rule; tested on the RFC’s examples and every table’s edges), string.normalize(form) and isNormalized(form) for Nfc, Nfd, Nfkc and Nfkd (NormalizationForm, a mirror of sysl.unicode.Form, Unicode 17.0.0; every line of NormalizationTest.txt in all four forms, and every code point it does not list), real‘s IEEE 754 encodings toBits and real.fromBits (binary64, NaN payloads kept) and toBits32 and real.fromBits32 (binary32, widened exactly, narrowed to nearest, ties to even), and avin.uuid‘s Uuid (a 128-bit value: parse of the canonical form, random version 4, fromBytes, bytes, version, variant, lower-case display, ordering by unsigned bytes, a Map key, sendable, and a FromParam for HTTP parameters), tested against the RFC 7914 and well-known PBKDF2 vectors and the RFC 9562 examples. The security primitives an API server needs: constantTimeEquals in avin.crypto for bytes and text, over sysl.crypto.verify; avin.encoding, written in Avin, with toHex (moved from avin.crypto, which exports it) and the strict decoders fromHex, fromBase64 and fromBase64Url beside toBase64 and toBase64Url, refusing with a DecodeError at a byte offset, tested against RFC 4648’s vectors, every padding case, every ASCII character, every unused-bit pattern and round trips over random bytes; and SecureRandom in avin.random, every draw from getentropy, with Random‘s drawing methods and hexToken/urlToken. Url in avin.net, written in Avin: Url.parse answering a Result with a UrlError and the trapping Url(text), every component (user information, IPv4, IPv6 with a zone and later-form hosts in brackets, empty kept apart from absent), escapes checked to decode to UTF-8 through string.fromUtf8, the scheme and host held in lower case and a default port left out, portOrDefault, queryParams, encode and decode, resolve by RFC 3986 §5.2 with dot-segment removal, and the with methods; the library’s tests hold RFC 3986’s normal and abnormal resolution examples. The futures’ additions in avin.threads: Future.traverse, calling its function in order on the calling thread, over Future.all; mapErr and orElse (by-name, widening as Result.orElse does) on a future of a Result; Executor, fixed(n) keeping at most n tasks working and shared(), with future(body), shutdown() (a new body afterwards trapping, the functions of futures made before still running) and isShutdown(), every future running its map, flatMap and onComplete on the executor it was made on, each worker enrolled by its thread’s identity so a wait on it finds its pool; blocking(body), counting a worker as waiting once however nested, as await does; and sleep(d: Duration), a runtime function over Sysl’s sleep bound blocking. A delayed argument may yield a subtype of what its by-name parameter yields, also through a companion’s apply called by its type’s name, and what it yields decides the call’s type arguments, those held to a lower bound included. TCP in avin.net, written in Avin over a runtime Connection holding sysl.net‘s socket, with a destructor that closes it: TcpStream.connect trying each resolved address, read, readLine and readAll sharing the bytes read ahead, write, writeText, setTimeout, shutdownOutput and close; TcpListener.bind (port 0 choosing one), port, accept and close; every wait a blocking binding, a connection’s failures ConnectionRefused, ConnectionReset and TimedOut in IoError, and a connection handed to the thread or future that serves it. Unix domain sockets in avin.net, UnixStream and UnixListener (bind, bindReplacing, path, accept, close) over sysl.net‘s Unix socket calls, with a TcpStream‘s reading and writing operations through the read-ahead code the two share, a path too long for the platform, a path in use and a missing path each an Err. The HTTP/1.1 client in avin.net.http, written in Avin over it: get, head, delete, post, put and patch, each taking headers to send, and send with a Request (its headers checked as it is made, withHeaders, withQueryParam), Response.json for a handler’s JSON text, bodies by Content-Length, chunked or to the connection’s end, interim responses skipped, up to five redirects of a GET or HEAD resolved by Url.resolve, HttpError; the corpus serves it from a server written in the test. TLS in avin.net.tls over the Sysl package openssl 0.2.2, which the library names in library/library.hocon, joining a program’s shims only where a binding the program compiles reaches it: TlsStream at both ends over a TcpStream, OpenSSL working on memory buffers while the bytes go through the TCP connection’s waits, so its limit and cancellation hold; TlsClient with trust(pem) over the machine’s store, host-name checking, SNI and TLS 1.2 at the least always on; TlsServer from PEM; TlsError (Transport, Certificate, Handshake, Credentials); a ByteStream trait over TCP, Unix and TLS connections; https URLs in the client (withTls, redirects across schemes, HttpError.Tls) and http.serve(…, tls); tested with a test authority’s fixtures in tests/fixtures/tls (untrusted, self-signed, expired and wrong-host certificates refused, a two-mebibyte body each way, keep-alive over TLS, 64 connections at once, a handshake timed out, a parked TLS read cancelled by its scope) and an opt-in tests/network/https_live.avin against real sites. A blocking binding takes a handle without a destructor as a parameter through a share taken before the call; a variant’s name is checked to be unique across a module’s files. Commands in avin.process, written in Avin over sysl.process.spawn and pipe: a Command of a program and its arguments (Command(program, args*), Command.parse), with inDir, withEnv, clearEnv, withoutEnv, withEnvironment (an ordered list of environment changes, a cleared or trimmed environment built whole and handed over without inheritance, a bare program name looked up on the command’s own PATH or the system’s default), withTimeout, toFile, appendTo, fromFile and withInput, joined by `
12Done. Designed and settled in actors and state machines. Done: Sendable in the core library, decided by the checker for every type from its structure (scalars, unit and string; tuples and data types of sendable fields, recursive ones included; final classes and objects with no var and sendable fields; type parameters bounded by it; Sysl handles; not Any, function values, open or abstract classes, or traits that make no promise), held as a bound where a type is named and at each generic call, a field typed by its initializer held once it is known; the promise of : Sendable in a trait’s or a class’s header or an impl, checked against the structure outside the standard library, an open or abstract class’s at each subclass, a generic trait’s at sendable arguments; the standard library’s promises for Future, Promise, Channel and Atomic of sendable values, Mutex of any, Once and Vector, and the immutable Map and Set traits; and diagnostics naming the field, variant, part or type argument that is not sendable and what to do; and Sendable held where values cross threads today: the @sendable and @isolated parameter marks, checked by what a closure, a by-name argument or a method value captures (a var never, for @sendable) and by what any other argument reads, on the bodies of spawn, s.spawn, Future and ex.future and the functions of map, flatMap, onComplete and orElse, with their results, a promise’s value and Future.successful‘s sendable; a mutex’s value and its with body @isolated (now @isolating, below), with‘s result and get, set and update sendable; a mark an override adds rejected; and the library’s promises for Thread, Executor, Condition, TcpStream, TcpListener and a started Child, every operation of each of the last three checking a handle’s owner first (a child through a runtime token holding nothing but its owner), so a read served from the bytes a connection read ahead, a closed one, and a child whose command has ended trap in the code that handed them over; and the whole-program check that what is passed for a @sendable parameter, directly or through every function, implementation, closure and extractor it reaches, touches no module-level var and reads no module-level value, lazy val or object whose type is not sendable, the error naming the item and the path to it, with the library’s worker registry and Annotation promising Sendable; and @sendable function types, @sendable (A) -> B, which are Sendable and subtypes of the plain types: a lambda, a function reference or a method value made where one is expected checked there by its captures and the module-level state it reaches, a parameter marked @sendable holding one, data and classes of @sendable fields (generic ones and module-level lazy val grammars among them) sendable, overloads differing only in the mark refused as one, and diagnostics printing the mark; a parameter marked @sendable sendable inside its function whatever its type (captured by @sendable lambdas, passed on unchecked), what is passed for one of another type being a match function written in place, a value of a sendable type or a marked parameter or class val field, or orElse of such partial functions (the standard library’s @sendable_result promise), chains of it included; and a lambda or a match function passed for a type argument bounded by Sendable made as a @sendable function, a match function where a PartialFunction is expected meeting the bound where every value the call gives of the type argument is one; and machine and state declarations, needing no runtime: a machine read into its Door.State data type, a variant per state holding its parameters and taking the machine’s type parameters, and a final class of the machine’s parameters, fields and methods, generic ones included; arms yielding the next state or stay, in any branch of an arm’s value; enter and leave, leave first, on every transition, a self-transition included, and the first state’s enter after the body; the per-state coverage check of a state’s own arms and the shared receive ones, naming the state, the machine and every case left out; handle and state(); the trap on handling from inside an arm, enter or leave; Door.State named in its module, by an import of Door and through the module, private with a private machine; and a machine reported as not sendable; and the actor runtime, in avin.actors: Behaviour[M](name, start), its start a @sendable function run on the first turn that makes the state and gives back the handler, spawn on the shared pool or a given executor handing the behaviour’s handles to the actor, ActorRef[-M] contravariant, sendable, equal and hashed by the actor and shown Name#n, and tell, which never waits; an actor record per actor with a lock-free mailbox (senders swap in the newest node, the actor alone takes the oldest), so one sender’s messages arrive in order; an actor queued on its executor by the send that finds it idle and never run on two threads at once, a turn handling at most 16 messages before the actor goes to the back of the queue, the worker’s owner word set to the actor’s for each turn so its handles work on any worker; actors on a shut-down executor still running; and Executor.execute, a task with no future and nothing handed over; and actor declarations, read into a function making the Behaviour and a hidden class of the actor’s state, needing no runtime of their own: parameters with defaults, named arguments, var and repeated ones, each held to Sendable where the actor is declared (a @sendable one exempt), and the message type where it is written after receives, reported once and naming the actor; generic actors; the body as the start, its fields and statements run once on the actor’s first turn and its vars kept across messages; receive arms as a match’s, each value discarded, checked for exhaustiveness and naming the actor and every case left out; self the actor’s reference, in the body, arms, methods and lambdas, never the state; the actor’s own private methods with the implicit receiver; the module-level state its body, arms and methods reach refused, the error naming the actor and the methods on the path; actors spawning actors; an actor declared in a module that does not import avin.actors, private to it when private; completion offering none of the names the compiler makes for an actor or a machine; and actor, receives and receive keywords only where a declaration, its header and its body place them; and the lifecycle: ActorContext[M], which an actor’s state extends and a library-form start makes from its reference, trapping where other code makes or calls it, with stop() after the message in hand (the mailbox dropped, a message to an ended actor dropped), stop(child) (trapping for a live actor that is no child), children stopped and waited for before the parent’s stopping block runs, so a tree ends from its leaves, children() and parent() from the runtime’s table of running actors, which gives spawn the parent; a stopping block, one per actor, given to the context after the body, and onStopping; watch with a message or a @sendable function of the Ending (Stopped, Failed(reason)), at once for an ended actor, replaced by a second watch, and unwatch; ref.ended(), a Future[Ending]; after and every on one timer thread, in the order they fall due, cancel() from any thread dropping a queued message too, every timer cancelled at the end; an actor’s own method names refused for its fields and methods, and its state never captured by a @sendable function; and the expected type bounding a contravariant type argument of a call’s result only from below; and ask, adapter and pipeToSelf: ref.ask(r -> Get(r), timeout) answering a Future[Result[R, AskError]], Ok of the first reply through a one-shot reference shown Reply#n, TimedOut from the actors’ timer thread and Ended where the question could not be delivered; adapter(f) translating another protocol into the actor’s mailbox at the send, the adapter equal to the actor’s self; pipeToSelf(future, f) delivering a future’s value as a message, at once for a future complete already; and a lambda’s parameter of a known shape with an open type argument (Promise[T], ActorRef[R]) taking that argument from its body, so a request-style call infers its reply type; and failure: an actor’s start, messages and stopping blocks run under a runtime return point, so a trap there is reported naming the actor (avin: trap in Counter#3: …), its frames dropped back to the worker and the message in hand with them; the program stopped instead, still naming the actor, where a lock (a Mutex, a Once), a lazy val‘s initializer or a Sysl call or callback is in progress, and on a stack overflow; spawn‘s onFailure: Supervision, Escalate by default (the escalating actor halted until its parent’s failure stops it, the program stopped from a top-level one), Stop (ending Failed(reason), watchers told) and Restart(limit, within) (children stopped and waited for, timers and watches cancelled, the stopping blocks run and the start run again with the mailbox kept, reported as avin: restarting Counter#3, escalating past the limit, a negative limit or an empty window trapping in spawn); a trap in a stopping block ending the actor Failed; and the functions of pipeToSelf and watch run in the receiving actor’s turn. Step 8, state blocks in actors, is done: the machine’s desugar shared, a private Counter.State data type and the current state in the actor’s class, each message matched in the current state against its own arms then the shared receive arms (optional with states), the next state from each arm’s value, leave then enter on a transition, the first state’s enter after the body (so again on a restart), per-state coverage naming the state and the actor, state() the actor’s own, and an ending running stopping but no leave. Step 9, ownership crossing between actors, is done: a message’s Sysl handles that the sender owns handed to the receiving actor as it enters the mailbox (the sender’s later use trapping, a handle sent twice going with the first message, a dropped message leaving them the sender’s, a receiver passing them on), walked only for message types that can hold a handle (holds_handles, decided per type), the walk of every hand-over stopping at the standard library’s types shared between owners (@keeps_owners, carried in the type record); Isolated[T] in avin.actors, made by isolate (a by-name body, in place or as a trailing block), take once by one atomic compare-and-set, with holding the objects while its function runs, each misuse trapping; and the @isolating mark on isolate‘s body and with‘s function: only sendable values from around it and, through the whole program, no module-level mutable state reached, across modules, trait implementations, methods, generic instances and closures made in the body; and the same mark on a mutex’s value and its with body, so neither can leave the guarded value in module-level state; and the standard patterns in avin.actors: Router.pool with RoundRobin, AtRandom, SmallestMailbox (a counted mailbox for routees) and ByKey (highest-weight hashing, so a routee leaving moves only its own keys), its routees supervised as a group and re-routing a message a routee no longer accepts; Stash, whose unstashAll puts its messages in front of the mailbox, a full stash trapping; and Topic, publish and subscribe from any thread, a subscriber’s end dropping it; and bounded mailboxes: mailbox = Bounded(capacity, overflow) on spawn and Router.pool (a locked queue for a bounded actor, the lock-free one kept for the rest), a full one’s tell dropping the newest or the oldest and counting it in dropped(), offer answering Full at once, send waiting for room (timed, a cancellation point leaving nothing behind, Ended where the actor ends first), an ask of a full mailbox answering Full, the notices, timers’ and piped messages an actor arranged for itself outside the bound, and a pool’s router waiting for room in its routees. All of stage 12’s steps are done.
13In progress. Designed in C bindings, its choices proposed in decisions. The stressors are two new repositories, avin-lang/mlt, binding MLT 7 (mlt-framework-7), and avin-lang/cairo, binding Cairo 1.18 (cairo, cairo-pdf, cairo-svg) to the surface of the reference binding, each step unlocking a piece of both. A third, avin-lang/freetype, binds FreeType 2 (freetype2) to the reference binding’s surface, and avin-lang/cairo depends on it for its FreeType font faces (cairo-ft); its lacks are proposed from the FreeType survey. Cairo is single-threaded and never waits, so it needs neither blocking nor @threaded, and it writes files whose pixels a test reads back: it is the earlier stressor, drawing its first PNG and PDF at step 3, where MLT renders first at step 6; MLT carries as:, blocking and C threads. Built in this order. Done: (1) c-libraries in the manifest (pkg-config, link, headers, install), gathered over the dependency graph and linked into every program, statically from their archives under the root package’s static-c-libraries = true (pkg-config --static, archive paths, the system’s libraries kept dynamic, a missing archive an error), and chosen library by library in c-linking (default, static, dynamic, static-system, search; --static-c-libraries/--dynamic-c-libraries; a library’s files, search, include, frameworks, link-flags and dynamic-only), a library’s own C sources compiled with its cflags and linked into the program (cached by text, flags and headers, once per build), and the C unit compiled by clang with the header check for top-level @c bindings of scalars (every C integer type and typedef measured and checked, bool, double, float) and unit, called directly and declared with signext/zeroext — unlocks the avin-lang/mlt manifest and its pkg-config probe, and mlt_version_get_int, get_major, get_minor and get_revision; for Cairo, the manifest’s three modules, cairo_version and cairo_format_stride_for_width; tested against the C library, libm, zlib through pkg-config, a library package binding zlib that a program uses without naming it, and a C fixture in tests/c the corpus builds and names to pkg-config, covering every scalar width, sign and typedef, every checked conversion’s trap at its boundaries and every diagnostic of the header check, at -O0 and -O2 under GC stress; (2) an integer bound as bool (Cairo’s cairo_bool_t: zero false, any other value true at the C type’s full width, a bool passed as 0/1; a typedef crossing as bool checked to be a C bool or an integer); strings, const char * in from a string or an Option[string] (null for None) copied into NUL-terminated memory off the heap, held until the result is converted, a held NUL trapping at its byte; char * and const char * out copied into a string and UTF-8-checked (an ill-formed sequence trapping at its byte), or into an Array[byte] unchecked, each perhaps in an Option for null and trapping on null otherwise; borrowed results left to C, and free: naming the function that frees one, checked by the C unit to take a pointer and answer nothing; string typedefs checked to be char */const char * — unlocks mlt_version_get_string, mlt_environment and mlt_factory_directory; for Cairo, cairo_version_string, cairo_status_to_string and cairo_pdf_version_to_string; tested against the C fixture (every UTF-8 width, empty and long strings, held NULs, every kind of ill-formed UTF-8, nulls both ways, counted frees over many calls under GC stress, truth values from 0, 1, -1, 2 and high bits), the C library’s strlen, getenv, strerror, strchr, strstr and strdup, and zlib’s zlibVersion, and every new diagnostic of the checker and the C unit. (3) handles: @c(type:, release:, retain:, kept:, shared), owned and borrowed results, the closed and owner checks, close() and finalizers, handle parameters, Result[unit, int] status results, keeps:/consumes:, and headers entries named by a macro (<ft2build.h> then FT_FREETYPE_H) — unlocks mlt_factory_init and the repository, profiles, producers, playlists, consumers and the properties bag, enough to build the two-clip playlist; for Cairo, Surface, Context, Pattern, FontOptions, FontFace and ScaledFont over cairo_*_reference/destroy, the borrowed get_target, get_source, get_group_target and get_scaled_font, every drawing, path, clip, group, transform-by-scalars and toy-text call, write_to_png to a file, the PDF surface with its metadata, outline, page labels and tags (flags and enums as integers) — enough to draw the reference program’s setsourcergba.png and tagged.pdf; for FreeType, the manifest’s macro-named headers, FT_Error_String as Option[string] (null where FreeType is built without error strings, as Homebrew’s is), Library (FT_Done_Library/FT_Reference_Library) and Face (FT_Done_Face/FT_Reference_Face) declared, kept handles held by a C reference given back after the holder’s release, keeps: lists, kept: names in release:, handle classes of another package in a binding (with that package’s headers and flags), and the scalar and status calls FT_Set_Char_Size (26.6), FT_Set_Pixel_Sizes, FT_Load_Char, FT_Load_Glyph, FT_Get_Char_Index and FT_Set_Named_Instance — callable once a face is made, at (5); built as handle classes whose objects hold their C pointer, owner, the C references they keep and the Avin objects they keep, given back by close() or the collector’s finalizer through the C unit’s glue, methods bound with the receiver as self, handles of another package checked after that package’s headers, a kept handle’s own C references taken by its holder too; tested against counted C objects in tests/c that stop the process on a double free or a use after free (tests/c/handles, tests/c/shapes over the first’s handles with its declarations named by a macro, and tests/c/handle_tests), covering close then use, double close, borrowed references, null as None, statuses at every width, sign and an enumeration, keeps of a list and of self, kept: names, consumed handles, owner checks across threads and shared, handles in data values and vectors, 10,000 handles finalized exactly once, both orders of a holder and what it keeps dying in one collection, at -O0 and -O2 under GC stress, and every new diagnostic of the checker and the C unit. (4) as: conversions between handle types, expression glue and field accessors — unlocks the Object property bag on every MLT type, Profile‘s fields, Playlist.clip and Tractor.track; field accessors over expressions with bound: indices — unlocks Cairo’s cairo_copy_path/copy_path_flat walked into PathElement data and cairo_copy_clip_rectangle_list; for FreeType, as: ["FT_GlyphSlot = self->glyph"] for FT_Render_Glyph, the face’s fields (num_faces, num_glyphs, family_name and style_name as Option[string], units_per_EM, ascender, descender, height, face_flags, size->metrics in 26.6) and the glyph slot’s through field expressions (glyph->bitmap.rows, width, pitch — negative for a bottom-up bitmap — pixel_mode, bitmap_left, bitmap_top, advance, metrics), and the variation descriptor’s axes and named styles with bound: indices; built as conversions made at the call, after the closed and owner checks, through the C unit’s glue, each checked by clang to make the type its entry names, and field accessors reading self-> the field through glue whose field type the C unit names, checks and measures, every index passed as a long long and checked against its bound before the read, scalars written at the field’s own width; tested against a counted chain of structs in tests/c (avin_fields.h, tests/c/fields and tests/c/field_tests) passed up two steps through a function and an expression, lending and staying the owner, closed and other-thread handles stopping at the call, None passed as null, keeps: and consumes: of a converted handle and another package’s bindings through the declaring package’s glue, and a record whose fields of every integer width and sign at their least and greatest, truth values, a byte, float and double, strings (every UTF-8 width, null as None or a stop, ill-formed UTF-8), nested structs, a struct through a pointer, a bounded array by an int and a long, a two-dimensional array, an array of a union and one of strings, and lent handles of its own and another package are read, and scalars written (each conversion’s trap at its boundary), indices at the first, the last, -1 and the bound, handles from conversions and fields finalized exactly once at -O0 and -O2 under GC stress, and every new diagnostic of the checker and the C unit. (5) enum mirrors (upper-case prefixes too), @c(const:) values (integer, real and string), enum statuses as Result[unit, E], and out/inout parameters joined into the result — unlocks ImageFormat, AudioFormat, TimeFormat, mlt_service_get_frame and timecodes; for Cairo, Status and the latched-error checks, every enum of the reference (Format, Operator, FillRule, LineCap, Extend, PdfVersion, …), the tag names, get_current_point, user_to_device and device_to_user (inout), the extents calls and the device offset and scale; for FreeType, FT_Init_FreeType and FT_New_Face answering Result[Library, int] and Result[Face, int] (the first library and face made, the face keeping its library), FT_Library_Version as a tuple, FT_Get_MM_Var answering an MMVar freed through kept:, RenderMode and PixelMode mirrors, the FT_LOAD_*, FT_KERNING_*, FT_FACE_FLAG_* and FT_Err_* constants (load flags combined with `
14Done. Lightweight threads, designed in threads and decisions. Done: (1) the allocation chunk belongs to the carrier, the operating system thread a context runs on, so a parked thread holds none; (2) the scheduler core: spawn and a scope’s s.spawn start lightweight threads on stacks reserved through sysl.fiber (8 MiB unless asked, committed as touched, the default size reused; the pages below where a thread stayed parked for a monitor tick, and those of a stack kept for reuse, given back to the system), run by workers about one per processor started as threads become ready, from one ready queue in the order threads became ready; locks, conditions, Mutex, Condition, Once, channels, joins, futures, promises and the pools’ workers park instead of blocking, timed waits on a timer the monitor thread fires; a thread that overruns its 10 ms slice while another is ready yields at its next poll, the Yield bit of the poll’s flag beside the collector’s Stop; a worker held by a blocking call for a tick while threads are ready is replaced by another; main stays on its own operating system thread; (3) sleep parks a lightweight thread on a timer, freeing its worker, and the timers that sleeps and timed waits park on are a heap of their waiters, soonest first, each cancelled in one step when its event ends the wait first; (4) an accept, connect, read or write on an avin.net socket, TCP or Unix, that would wait parks its lightweight thread on the runtime’s poller, one sysl.io.poll set whose own thread makes each waiter ready once its descriptor is, every socket being non-blocking; a connection’s timeout parks on the timers beside it, and main waits on the descriptor alone; (5) an actor’s turn is a lightweight thread of its own (one given an executor of its own keeps running its turns on that executor’s workers), so a turn that sleeps, awaits, asks or receives parks without holding a worker, a long turn is time-sliced, and the actor still runs one turn at a time; (6) cancellation by scope: s.cancel() cancels a scope’s threads, which stop at their next wait (a socket’s among them) or safepoint poll with their frames dropped, running their deferred statements first, and end with no result (Thread.result() answers None), never while holding a lock, initializing a lazy val or resolving a future they completed; a thread running a scope of its own stops first at that scope, which cancels and waits for its threads; the scope hands back the Sysl handles a cancelled thread reached; (7) main-thread scheduling for the ui package: isMainThread(), inboxes made on the main thread whose handlers it runs, post for sendable work, one queue in the order sent that the frame loop runs at the start of every frame and run once more as it ends, an ask that parks its lightweight thread, and run only on the main thread; threads pinned to the main thread (spawnOnMain, a scope’s spawnOnMain, runMainThreads, isPinnedToMain), on a main scheduler of their own that the frame loop runs after the posted work and the main thread’s own waits run as its threads become ready, so a pinned thread parks on a future, a channel or an ask without holding a frame and carries on on the main thread, and is named as pinned in the deadlock report; (8) the server library: TcpServer, a listener serving each connection in an actor of its own (supervised with Stop, so a trap ends that connection alone after a failed hook answers on it) on a pool with a worker per connection it may hold, at most maxConnections held and the next left unaccepted, a per-connection timeout, and a graceful stop/join/shutdown that closes the listener at once (its parked accept cancelled) and waits for the connections, and idle, a connection’s wait for its next piece of work that stopping cancels, so a shutdown closes idle connections at once; and on it http.serve, HTTP/1.1 with keep-alive and pipelining, bodies by length and chunked, Expect: 100-continue, read, write and idle timeouts, a bound on the whole of each request from its first byte (requestTimeout, http_serve_request_timeout.avin), header and body limits, its waits for a request made through idle, the refusals 400, 408, 413, 414, 417, 431, 500, 501, 503 and 505, and Router with Route patterns binding :name segments, 404 and 405 with Allow; examples/http_server.avin; (9) diagnostics: a deadlock of the whole program, main waiting without a limit with no lightweight thread running or ready, no timer, no socket wait, no foreign thread attached and no @threaded callback held, stops the program with avin: trap: deadlock: all threads are waiting and a line per thread naming what it waits on (a lock, a condition, a join, a channel’s receive or send, a future), idle workers left out; the quit signal writes a thread dump (each thread running, ready, ending or waiting on what and for how long) and the program goes on, unless the program watches the signal. Partial deadlocks are not found, and a dump names no functions; (10) select, the wait on several channels at once: receive arms binding by Some(p), None, a name or nothing, send arms, after and else, operands evaluated once in order, a uniformly random choice among ready arms, the runtime’s one-park wait enlisting a link on each channel’s condition with one wake-once token, a notification a select cannot use passed on, every link withdrawn, cancellable and safe for the collector, inside parentheses, nested, and in actors’ turns (syntax and semantics Proposed); stream.readable() arms beside the channel arms, ready on any threads.Readiness (every ByteStream: TCP, Unix and TLS, whose readable() counts read-ahead bytes, decrypted plaintext and whole records only, the end, a reset and a closed connection) and otherwise waiting on the runtime’s poller under the select’s one wait, its registration withdrawn on every ending, cancellation included, counted as sockets in the thread dump, only the owning thread able to name a connection; sink.writable() arms on any threads.Writability (every ByteStream and StreamWriter), with writeSome, TLS’s sending one record and keeping what does not fit for writable() to send (select_writable.avin); if guards on select arms, a false guard leaving its arm absent, and threads.Selector for a set of channels and streams known at run time, waited on through the select’s own wait (select_guard*.avin, selector_*.avin); split() of a TCP, Unix or TLS connection into a sendable StreamReader and StreamWriter used by two threads at once, both parked on one descriptor through the poller’s per-direction waiters, the writer’s close a half-close, a TLS session shared under locks taken from transit and handed back (net_split_tcp_both_ways.avin, net_split_tls_both_ways.avin, net_split_half_close.avin, net_split_reset.avin, net_split_cancel.avin). Built on it for API servers: streamed responses (Response.stream, chunked or of a length given beforehand, close-delimited to an HTTP/1.0 client, each write of a BodyWriter sent at once and answering Err once the client has gone or the server stops), server-sent events (Response.events, an EventWriter with send, comment, retry and keep-alive comments while it waits), a handler’s waits through untilStopped on the request and the writers, which a shutdown ends at once, an error page (errors) for the router’s and the server’s own answers, Result[Response, ToResponse] handlers so ? ends a handler, typed query and route parameters (queryAs, queryOption, paramAs over FromParam, a ParamError answered 400), and Route.group, under and wrap with middleware as functions of Handler, a middleware handing values on to the handlers inside it through withValue, read by value[T]() and keyed by their exact type (http_request_values.avin); a handler that traps while streaming has its connection closed unanswered (tests/run/http_stream.avin, http_server_hooks.avin, http_api.avin); connection upgrades (Response.upgrade, a 101 handing the connection and the bytes read ahead to the code that carries it on) and WebSockets on them, RFC 6455: webSocket(request, session) checking the handshake (405, 426, 400 refusals, subprotocols by the server’s order) and WebSocket.connect for ws and wss, text and binary messages, fragments put back together, pings answered with pongs, the close handshake with codes and reasons, a message size limit, client frames masked and server frames not, UTF-8 checked, violations closed 1002, 1007 and 1009, a stopping server closing its sockets 1001 (tests/run/websocket.avin, websocket_frames.avin, websocket_tls.avin); a sendable ws.sender() whose whole messages queue in a bounded outbox the owning thread writes while it receives, in one select on its stream’s readable(), the outbox and the server’s stopped() channel, never interleaved, large ones fragmented, a full outbox answering Err at the write timeout, a sender’s close carried out by the owner, and ws.serve(onMessage) (websocket_chat.avin, a broadcast chat over ws and wss; websocket_sender*.avin, websocket_slow_client.avin, websocket_outbox_trap.avin). (11) Timers and deadlines: after(d), a channel delivering one instant once d has passed, and Ticker(period), ticks a slow receiver misses dropped, stop(), both holding their due time in the channel rather than a timer or thread, so nothing is left when nobody receives, delivered by the receive or select that looks and woken for by a select’s park; a channel’s receive(timeout) and send(x, timeout); and withTimeout(d, s -> …) -> Option[T], the body on a lightweight thread of its own cancelled with its scope’s threads when the time runs out; each a timed wait, never taken for a deadlock (Proposed). The request context: Context.current() with its deadline, remaining() and value(key) over typed Key[T]s, withValue(key, v, body), and withDeadline(t, s -> …) -> Result[T, DeadlineExceeded] beside withTimeout, both setting the deadline, the sooner one kept; the context lives in a slot of the thread’s runtime context that every collection marks, a scope’s threads taking all of it, a plain thread, a future’s code and an executor’s task its values, and an actor’s turn none.
15In progress (Linux, 2026-11-19): machine conditions in the manifest (item 2: package.targets, if on dependencies, Sysl dependencies, C libraries and features, install by condition, link-flags, avin check --target, avin tidy and avin vendor over every target); files for one machine (item 3: name.<symbol>.avin and .lavin read where the symbol holds, a module existing where any of its files is read, the import rule against every target, avin check once per differing set of targets with each diagnostic told with its machines, and avin.target‘s os and arch decided as the program is compiled, the untaken branch left out at every level). Still to come: the other ten items; items 4 to 8, 10 and 11 wait for a Linux Sysl (Sysl’s items 1 and 2), and item 12 for Sysl sysroots

Dates and times: build plan

avin.time is rebuilt to its chapter over @sysl bindings to Sysl 0.10.0’s sysl.time and sysl.posix.time, with no new C. Each step is one item, gated on its own, and ships the tests below for what it builds; a binding that cannot hold Sysl’s Zone as a handle is a gap to report, not to route around.

  1. Clocks and durations. Instant(epochMicros) as the wall clock, WallTime and the monotonic Instant removed; now(), monotonic() -> Duration, epochSeconds/epochMillis/epochMicros; the makers micros millis seconds minutes hours days weeks (from microseconds and milliseconds) and their methods on int and long; toX()/toXPart(); d / e; the duration’s and instant’s text; Duration.Zero in place of zero(). Every caller moves with it: avin.process‘s command deadline (a monotonic() reading), avin.actors, avin.net‘s setTimeout, the tests and examples that name milliseconds, zero(), wallClock, elapsed or WallTime (git grep them), and the Duration overloads of await and waitFor.
  2. The calendar (done). Date, Time, DateTime, Weekday: makers and their traps, fields, with…, startOf…, endOfMonth, onOrAfter/onOrBefore, isoWeek, daysUntil, DateTime ± Duration, the ISO 8601 display. Zoned‘s with… and startOf… come with step 3.
  3. Zones. Zone over the host’s database, utc, localZone(), fixedZone, ZoneError, Resolution, Zoned with atZone/atZoneEarlier/atZoneLater, ZoneTimeError, its equality and order, Zoned ± Duration, abbreviation and daylight saving.
  4. Periods (done). Period, months/years, plus…, Date/DateTime ± Period with the month-end clamp, until/monthsUntil. Zoned ± Period and Zoned‘s plus…, which need the gap and overlap rules, come with step 3.
  5. Text in (done). parseDate, parseTime, parseDateTime, parseTimestamp, parseZoned, parsePeriod, TimeParseError; format(pattern).

The test matrix. Each claim of the chapter is a test; these are the cases each step owes.

  • Clocks: monotonic() never decreases across 10,000 reads and across threads; now() is after 2020; monotonic() has no atZone, and monotonic() - now(), a Duration from now() - monotonic() (an Instant, the wall reading moved back) and now() < monotonic() do not compile (reject tests).
  • Durations: 2.hours == hours(2) on an int and a long receiver; (hours(1) + minutes(30)) .toMinutes == 90; seconds(-90).toMinutes == -1; the parts of a negative duration; Duration.Min.abs, hours(long.MaxValue), Duration.Max + micros(1), d / 0 trap; 3 * d rejected; the displays 5400s, -45s, 0s, 90.5s, 250ms, 1.5ms, 7us, and the Debug forms; Ord and Hash as TreeMap and Map keys.
  • Instants: epochSeconds(0) displays 1970-01-01T00:00:00Z; epochMillis(1000).epochSeconds == 1; epochMillis(-1).epochSeconds == -1; epochMicros(1_000_000_001) keeps its last digit; Instant.Min and Instant.Max display as the chapter says and round-trip through parseTimestamp; Instant.Max + micros(1) and epochSeconds(long.MaxValue) trap; now() + months(1) rejected; now().year rejected.
  • Calendar: date(2026, 2, 30), date(2026, 13, 1), date(2026, 0, 1), time(24, 0), time(9, 60), time(9, 0, 60), time(9, 0, 0, 1_000_000) trap with the chapter’s messages; 2024-02-29 valid and 2023-02-29 a trap; 1900 not leap, 2000 leap, year 0 leap; weekday of 1970-01-01 is Thursday and of 2026-08-28 Friday; dayOfYear 240; daysInMonth of every month of a leap and a common year; isoWeek across 2026/2027 (2027-01-01 in week 53 of 2026) and 2020-12-31 (week 53); startOfWeek of a Monday and a Sunday; onOrAfter its own weekday; withDay(31) in February traps, withMonth clamps; displays of year 0, -1, 9999, 10000; Date.Min and Date.Max display and reach no instant (atStartOfDay(utc) traps); date(…) == dateTime(…) rejected; Time arithmetic rejected; Time ordered.
  • Zones (Toronto, Tokyo, Kolkata, Kathmandu at +05:45, Lord Howe’s half-hour change, UTC): zone("Nowhere/Atall") is UnknownZone; "../../etc/passwd", "", "/etc/localtime" and a name with a non-ASCII letter are NotAZoneName; zone("UTC")? == utc; zone("+05:30") displays +05:30 and its readings carry no bracket; fixedZone(seconds(30)) and fixedZone(hours(24)) trap; localZone() answers with TZ unset, set to a zone and set to nonsense; the spring gap (2026-03-08T02:30 in Toronto: atZone is Skipped, both atZoneEarlier and atZoneLater give 03:30-04:00) and the autumn overlap (2026-11-01T01:30: Repeated, -04:00 then -05:00, an hour apart); a zone whose skipped hour is midnight for atStartOfDay; Zoned ==, < and TreeMap for Toronto 09:00 and Tokyo 22:00 of one instant; abbreviationAt EDT/EST; an offset with seconds in the table (Toronto in 1850) held to whole minutes; a reading past the table’s last transition.
  • Periods: Jan 31 + 1 month in 2026 and 2024; Feb 29 + 1 year and + 4 years; Jan 31 + Period(1, 1) is Mar 1; months(1) - months(1) after a clamp; months(1) != Period(0, 30); years(1) == months(12); Period * n overflow traps; Date - Date across a leap day; until and monthsUntil from month ends; a + a.until(b) == b over a year of pairs; zoned + days(1) against zoned.plusDays(1) across the spring change (an hour apart) and the autumn change; a period landing in a gap and in an overlap; Period has no < (reject).
  • Text: every display of every type reads back equal through its parser, over a sweep of dates from year -1 to 10000 and times with 0 to 6 fraction digits; 2026-02-30, 2026-13-01, 2026/03/08 (byte 4), 2026-03-08T (trailing at 10), 24:00, 23:59:60, seven fraction digits, an offset of -25:00, a timestamp with no offset, Arabic-Indic and full-width digits, a trailing space, an empty string, a zone name in parseZoned that does not exist; patterns: the chapter’s two examples, h12 at 00:30 and 12:30, DDD, z zz zzz zzzz, a literal Z, ||, a Unicode literal between bars, YYY and an unclosed bar trapping, hh on a Date, YYYY on a Time and z on a DateTime trapping with the chapter’s messages; format on an Instant rejected.
  • Neighbours: every type as a field of a data type and a class, in a generic [T: Ord] sort and a Map key, captured by a closure, sent to an actor and through a Channel, in s"…" with a width; threads.sleep(millis(1)), await(millis(10)), an actor’s after(millis(5), m); the corpus runs every time program at -O0 and -O2 and under GC stress, with a zone held across collections.

Union types: the test matrix

Each claim of union types is a test; these are the cases the item owes. Run tests (tests/run/union_*) run at -O0 and -O2 and under GC stress; reject tests (tests/reject/union_*) carry the chapter’s exact messages, at most five per file.

  • Syntax: int | string as a parameter, result, val, var, data field, class parameter, type argument (f[int | string](x), List.empty[int | string]()), tuple part, function parameter and result, alias body; (A) -> B | C returns the union and A | B -> C takes it; ((int) -> int) | string holds a function and is called after a match; Option[A | B] and Option[A] | B are different types (a reject assigning one to the other); []int | string vs [](int | string); @sendable (int) -> int | string; (int | string) parenthesized; a union broken after | inside brackets; x: int | string -> in an arm rejected with the parenthesized suggestion; _: int | _: string -> is two alternatives; a | b on ints still bitwise and a symbol method | still called in the same file; a clause guard f(n) | n > 0 = … beside a union parameter.
  • Normal form: A | (B | C) == A | B | C (one overload, a duplicate-overload reject); int | string == string | int (same overload, same Map key type, a value made as one passed as the other); written int | int, Dog | Animal, string | Any, int | Display, int | Nothing each rejected with its message; the same reached through T (T | int at T = int, T | Animal at T = Dog, T | string at T = int | bool) and through aliases (Key | string) compile and behave as the collapsed type; Named | Pet kept two members; Option[int] | Option[string] two members; type Json = Vector[Json] | string rejected; data Node(kids: Vector[Node | string]) builds a tree, compares and prints it; messages print aliases expanded and flattened.
  • Inference: if c then 1 else "a" rejected naming int | string; the same for match arms, a loop’s else/break, [1, "a"], pair(1, "one"); val y: int | string = if … accepted; val u2 = u, Some(u), id(u) carry the union; if c then u else 3 is the union; orText(3) gives T = int, orText(u) with three members gives the remaining two, orText("a") rejected naming T.
  • Injection: each single site — argument, binding, assignment to a var, data field, class field, result (= 3 and return 3), tuple part written out, each if/match branch, collection literal element, map literal key and value, with { v = 3 }, a default argument, a named argument; a subtype (Puppy into Animal | int); Parrot into Named | Pet rejected; literals: 3 into int | long is the int, 5_000_000_000 the long, 3 into long | string the long, 3 into byte | long rejected, 1.5 into real | string, int.MaxValue/long.MinValue boundaries; None, [] and Ok(1) into a union with one fitting member, and rejected with two; int | string into int | string | bool; int | bool into int | string rejected.
  • Subtyping and variance: Dog | Cat passed as Animal; int | long as Any and matched back; int | string as Display; List[Dog] <: List[Dog | Cat], Option[Dog | Cat] <: Option[Animal], Result[T, IoError] <: Result[T, IoError | ParseError] with no conversion (identity preserved: the same Array inside); List[int] as List[int | string] rejected, List[int | string] as List[int | string | bool] rejected; Array[Dog] as Array[Dog | Cat] rejected (invariant); (Dog | Cat) -> int as (Dog) -> int; () -> Dog as () -> Dog | Cat; (int | string) -> int value as (int) -> int rejected, the named function accepted; @sendable union functions.
  • Overloads: show(1)/show("a")/show(true) pick int / union / Any; f(int | string) vs f(int | bool) with 1 ambiguous and with a union argument resolved; member overloads with a union argument rejected suggesting match; generic overload g[T](x: T) vs g(x: int | string); overloads differing by member order rejected as duplicates.
  • match and exhaustiveness: every member by type pattern; a member left out names _: bool; _ covers the rest; a supertype pattern covers a member; a subtype pattern needs the rest; a sub-union pattern binds the smaller union and leaves the others; literal, range, comparison, n + k, constructor, list, sequence, tuple and extractor patterns each reach their one member and count only for it; 0 on int | long rejected; Some(x) on Option[int] | Option[string] rejected; a type pattern naming no member rejected; unreachable arm after its member is covered rejected; guards do not cover; a Parrot in Named | Pet taken by the first arm; clauses by member with a missing member rejected; match functions (match n -> …) over a union; an Any matched by x: (int | string) binds the union and fails on a bool; a generic match on T | int checked once and, at T = int, taking every value by the T arm.
  • is: if v is s: string, is not with early return, while v is n: int, && and || scopes; v.charCount after the test rejected (no narrowing).
  • Equality and hashing: same member equal and unequal; different members unequal (int 1 vs long 1 in int | long); u == 3 injects; u == true rejected; a class member with its own Eq used; the sequence exception (Vector[int] | List[int]); Set[int | string] holding 1 and "1"; Map[int | string, V] lookups; hash equals the member’s hash; === on Dog | Cat accepted and on Dog | int rejected.
  • Traits and member calls: println, interpolation, toString(), debug (strings quoted) and a field width on unions; [T: Display] at a union; a union without Display member not displayable (reject naming the member); a library trait with receiver-only Self reached; Ord refused (sorted() on Vector[int | string] rejected, TreeMap key rejected); Sendable through spawn/an actor message when every member is, and rejected when one is not; a.name through the join; v.charCount rejected; a name on two conforming traits rejected.
  • Derivations: a data type and a class with a union field derive Eq, Hash, Display, Debug; derives Ord rejected naming the field; a derive template’s bound met and not met by a union field.
  • ?: rule 1 with two error kinds; a subclass error into its superclass member; a union ?‘d inside a wider union; rule 2 (From on one member) and two members with From[E] rejected; rule 3 (union into a wrapper with two Froms) and a member with no conversion rejected naming it; rule 4 unchanged; NetError into IoError | ParseError rejected with the message; ? in a lambda with a declared union result; a returned Result[T, IoError] widened with no conversion; a scalar error union rebuilt with mapErr(e -> e) and rejected without it; Option ? unaffected.
  • Representation and GC: a reference union and a scalar union in locals, fields, tuples, Vector, List, Array, Buffer, Map values, closures’ captures and actor messages, held across forced collections (strings and class instances in the reference slot stay alive and intact); a scalar union of long | real | char | bool | unit round-tripping every member and boundary value (long.MinValue, real NaN and -0.0, '\u{10FFFF}'); a union nested in a union field of a data type nested in a vector; generic Vector[T | int] at T = string and at T = int; the same output at -O0 and -O2.
  • with and aliases: p with { v = 3 } injects; p with { v.x = 1 } through a union rejected; type Num = int | long in every position; generic alias type OrErr[T] = T | string; impl on an alias of a union rejected.
  • Closures: lambdas taking and returning unions; a closure capturing a union var and changing it to another member seen outside; placeholder lambdas over a union (xs.map(_.toString())).
  • Refusals: impl Display for int | string, an extension on a union, class C: A | B, [T: A | B] (and [T >: A | B] accepted), a union in an @sysl and an @c parameter, result and mirror field, calling or constructing a union, each with its message.

Refined variants: build plan

Refined variants are designed, their choices proposed in decisions; steps 1 to 6 are built, step 7 is still to come. Each step is one item, gated on its own targeted files, and ships the tests listed for it: run tests tests/run/refined_* (at -O0 and -O2, under GC stress) and reject tests tests/reject/refined_* carrying the chapter’s exact messages, at most five per file. A step that meets a missing piece of the checker it builds on reports it rather than routing around it.

  1. Declaration. Done (branch gadt-1): parsed, shown and formatted; VariantSymbol holds params (the type’s, then the variant’s own) and result; the six checks run, rule 6 through expansion.sysl‘s flow graph with each refined variant’s parameters as nodes of their own; tests tests/reject/refined_{result,parameters,variance,nested,bounds,defaults}, tests/run/refined_declaration, tests/programs/reject/refined_across_modules, and cases in parse_tests, formatter_tests and lsp_tests. Where it meets higher-kinded types: a result refuses any form but data types, classes, tuples, functions and parameters, so a constructor or an applied constructor parameter is refused; step 2 adds the rest (below). Variant[params](fields) -> Type[args] and Name -> Type[args] in a data body: syntax.sysl (Variant gains type_params and result: Option[&TypeExpr]), parse_decl.sysl, formatter.sysl (round trip, avin fmt-clean), syntax_show.sysl, lsp_symbols.sysl; in check.sysl‘s declare_variants, VariantSymbol gains its parameters and its result in them, and the six declaration checks run. Tests: each check’s reject (a result of another type, a fixed +T and -T, a union naming a parameter beside a closed union accepted, an unused parameter, a reused name, Lift[A](x: Expr[Vector[A]]) refused beside First[A, B](pair: Expr[(A, B)]) accepted); parse and formatter cases for a fieldless variant with a result, a multi-line field list, annotations and defaults on a refined variant’s fields.
  2. Making values and layouts. Done (branch gadt-2): step 1’s refusal is gone; a variant’s signature is generic over its parameters, a parameter of the type it names nowhere fixed rather than inferred or written (Signature.fixed); T[A].V holds the value to the instance written; the chapter’s two messages for a value at the wrong instance, the field’s named where it is given to one; variant_args/variant_fields_at read a variant’s arguments back from a concrete instance, and lower.sysl lays out only the possible variants (AbsentVariant for the rest), compiles an arm on a variant its copy’s instance cannot hold not at all, and an arm on a refined one at the arguments read back (Lowering.refined), which the derived templates’ code needs; a derivation holds a refined variant’s own parameter to the trait where the result implies it (implied_own). Higher-kinded types: a variant’s own constructor parameter is refused, a result fixing a constructor parameter is refused, and one keeping it in its place is accepted. Still refused, with “not yet” messages, for the steps that own them: a variant pattern of a type with refined variants, plain variants included, outside derived code (step 3); a field read by name on a refined type’s one variant (step 3); a value of a variant with a hidden parameter (step 5); a value of a variant bounding its own parameter (step 6). Tests: run refined_values, refined_layouts, refined_derived, tests/programs/run/refined_across_modules; reject refined_making, refined_shared_names, refined_type_args, refined_later_steps, refined_later_steps_reads, refined_constructor_params, and the cross-module program. The plan as written: removes step 1’s refined_use_refused and its two reject tests refined_not_yet_built*. variant_signature generic over the variant’s parameters; inference from fields and the expected type; explicit arguments on the variant and on the type; the bare and qualified names; in lower.sysl, DataLayout holding only the variants possible at the instance, tags kept as declared; derived Eq, Hash, Display, Debug per instance; a type pattern on an Any holding one. No hidden parameters yet (refused with a “not yet built” message, removed by step 5). Tests: run: values of every Expr variant printed and compared, Expr[int] and Expr[bool] in one Vector[Any] taken apart by type pattern, a refined value in a class field, a closure capturing one, a Map keyed by one; reject: a variant at the wrong expected instance, a field of the wrong instance, a shared variant name decided by a refined result.
  3. Refinement. Done (branch gadt-3): step 2’s two step-3 refusals are gone. Each refining pattern is a site (Checker.sites, TProgram.refine_sites) whose fresh types have the owner pattern_owner(site); refine_variant solves the equalities (solve_pair: fresh types first, an occurs check, unions and constructors naming parameters taken apart not at all, a contradiction giving none) and declares a marker local beside the pattern’s names, so BodyState.equalities hold exactly where those names are in scope. refined_type applies them in fits, unify, joined, bounds, the expected type of check_value, patterns on a type parameter, and operands of operators and members (refined_operand); a refining arm, clause, is branch and block yield the expected type (held_to_expected), and a fresh type leaving its scope is refused (escape_checked, settle_var). val V = x takes the value apart where V is a variant of a refined type; a field of a refined one-variant type is read at what the instance says. In lower.sysl, refine_pattern reads each site’s arguments back; is, &&, ||, !, if and while fold a test impossible at the copy and leave out what holds its equalities, a block’s rest included (Lowering.dead); a lambda or local function written in a site’s scope is compiled at what its sites read (TProgram.refined_functions); a field read of an instance with no values traps. Still refused, for the steps that own them: a pattern on, and a value of, a variant with a hidden parameter (step 5); a value of a variant bounding its own parameter (step 6). Tests: run refined_eval, refined_scopes, refined_closures, refined_impossible, the cross-module program; reject refined_arm_results, refined_escapes, refined_contradictions, refined_attacks, refined_later_steps, refined_later_steps_reads. The plan as written: in check.sysl, a scoped substitution of the type parameters in scope, pushed by each arm, clause, is scope and destructuring binding whose pattern holds a refined variant (solved by decomposition with an occurs check), consulted wherever two types are compared or a member is found; arm results checked against the expected type under it; inference variables settled as written; in lower.sysl, an arm whose equalities fail at the copy is not lowered. Tests: run: eval over IntLit, BoolLit, Add, Eq, If, Pair (as clauses, as a match, as a match function, through is with an early return, in a class’s generic method, in a local generic function); nested refinement (If(BoolLit(b), x, y)); a lambda made in an arm and called after it; a var declared outside stored in an arm; Same/cast; reject: an arm result of the wrong type, arms joining with no expected type, an inference variable settled in an arm and used outside, a refined name used outside its is scope, an unknown matched type.
  4. Coverage. Done (branch gadt-4): cases_of in coverage.sysl keeps the variants whose result’s equalities with the column’s instance have a solution (possible_case, its own variant parameters given coverage_owner types), and each case carries what its equalities say of the enclosing type parameters to the other columns (case_columns), so a row’s equalities travel along it; an instance with no possible variant is a column with no values. The checker hands coverage each matched type under the equalities in scope (refined_type), so a nested match in a refining arm counts the enclosing arm’s. A pattern whose equalities contradict is an error at the pattern (report_contradiction): the variant makes another instance, a cyclic equality, or a contradiction with an earlier pattern of its row (Checker.pattern_row: an arm, a clause’s arguments, an is test, a binding); a match on an empty instance is an error at the value matched. Alternatives no longer hold each other’s equalities nor the arm’s (a step-3 leak: IntLit(_) | BoolLit(_) -> 5 checked 5 as a T that is int). Two fresh types that read the same are named apart by their patterns’ lines (names_apart) in the expected/found, operand and result messages; lowering tests each alternative at what its own patterns read back (refine_pattern), where it compiled one without them. Tests: run refined_coverage, refined_alternatives; reject refined_coverage, refined_coverage_rows, refined_coverage_more, refined_names_apart, refined_contradictions (now an error for the cyclic arm), refined_alternatives. The plan as written: in coverage.sysl, cases_of keeps the variants possible at the instance and the witness search carries each row’s equalities; impossible arms and empty instances are errors with the chapter’s messages. Tests: run: total on Expr[int] with no BoolLit arm, a pair of Expr[T]s whose contradictory row is left out, a nested match inside a refined arm; reject: an Eq arm on Expr[int], a contradiction in one row, a cyclic equality, a Same[int, string] matched, a missing case naming a possible variant, an arm unreachable after the possible variants are covered.
  5. Hidden parameters. Done (branch gadt-5): steps 2 and 3’s step-5 refusals are gone. A value records the types it hides (Construct‘s hidden, at hidden_positions); in lower.sysl each list of them at an instance is a pack (pack_layout, PackLayout), a descriptor of the variant’s tag laying the fields out at the pack’s types. An arm, a clause and the derived code are compiled once per combination of packs their hidden variant patterns can stand for (arm_packs), each tested by its descriptor (test_packs); an alternative, an is test and a field read by name (pack_field) try each pack in turn. Packs are found as lowering reaches the code making them, so an instance compiled for fewer than the program makes is lowered again (relower_stale), and neither kind is kept in the instance cache. A lambda or local function in such an arm carries its pack’s arguments after its copy’s (pack_args), and a local whose type a pattern decides gets a slot of the copy’s machine type where it is bound. Equality compares descriptors first and hashes a pack’s number. In check.sysl, a fresh type has the bounds its variant declares (fresh_bound_key), so a hidden parameter’s bounds, T: A & B included, are checked at the call and held in the arm, while a bound on a variant’s own parameter that its result names stays refused (step 6); a derived trait, Sendable included, holds of a hidden parameter only by its bounds (hidden_has, hidden_sendable); a hidden type leaving its arm has the chapter’s message; an is test binds no field naming a hidden type. In expansion.sysl the fresh types of patterns are their variant’s parameter nodes, a value’s hidden types reach them, and a type argument holding a hidden type does not grow a parameter the matched value holds (fresh_edges), so eval(First(p)) is ordinary and a cycle making ever larger packs is refused. Tests: run refined_hidden, refined_hidden_plan, refined_hidden_protocol, the program refined_hidden_across_modules; reject refined_hidden_escapes, refined_hidden_tests, refined_hidden_growing, refined_hidden_bounds, refined_later_steps (now step 6’s alone) and refined_later_steps_reads. The plan as written: fresh rigid types in an arm; the escape check; packs: one descriptor per variant and list of hidden types the program makes, fields laid out at the pack’s types; an arm on such a variant lowered once per pack as a function of the hidden types and called through the descriptor, reusing the dispatch lower.sysl and devirt.sysl build for generic trait methods; equality comparing descriptors first; the polymorphic-recursion check extended to cycles that make packs. Tests: run: First in eval; a hidden value-type field (int, real, a tuple) beside a reference one; two packs of one variant compared unequal and hashed apart; the Plan example driving a Door machine; reject: a hidden type leaving its arm as a result, through a local settled in the arm, one value’s hidden type used with another’s; a growing pack cycle.
  6. Bounds on variant parameters. Done (branch gadt-6): step 5’s step-6 refusal is gone, with its test refined_later_steps. A variant’s own parameter that its result names has its bounds checked where a value is made, as a call’s are (the variant’s signature is generic over it); in the arm the fresh type has them (step 5), and in check.sysl an enclosing type parameter that an equality in scope equates with a bounded one as a whole gains its bounds there (gained_bounds, carried in Conformances.gained and read by scope_bounds), so smallest[T](c: Coll[T]) calls items.minOption in the Sorted arm. In lower.sysl an instance whose arguments fail a variant’s own bounds holds no value of it (meets_own_bounds): its layout has no descriptor for the variant and an arm, is test or derived code on it is not compiled there (refine_one). Whether a refined type is sendable is decided at its instance (structural_sendability reads a variant’s own parameters back from the instance’s arguments, and leaves out a variant the concrete instance cannot hold); a hidden parameter’s Sendable stays decided by its bounds, every pack having been checked where it was made. The Account protocol at long, string and unit and the unsendable reply type’s refusal were built by step 5 (refined_hidden_protocol, refined_hidden_bounds). Tests: run refined_own_bounds, refined_own_bounds_actors, the program refined_bounds_across_modules; reject refined_own_bounds, refined_own_bounds_scope, refined_own_bounds_parts, the program refined_bounds_across_modules. The plan as written: checked where a value is made; held in the arm; gained by an enclosing type parameter equated with a bounded one; a copy at a type without the bound leaves the arm out. Tests: run: Sorted[A: Ord] and smallest; reject: a method of a bound the variant does not give, through the equated parameter.
  7. Tooling and pages. Done (branch gadt-7): hover and completion show a refined variant’s signature with its own type parameters and its result (definition_index.sysl, which both read through render_target; tests in lsp_tests.sysl); the TextMate grammar already scopes the -> and result type of a variant, now pinned by editors/grammar-tests/samples/refined.avin (the IntelliJ plugin copies that grammar at build time); the chapter’s two complete programs are run fences with output fences, so the corpus test compiles them. The chapter’s other examples are fragments or show errors, so stay text.

Stage 10’s incremental builds are designed in the pipeline, their choices proposed in decisions. The plan follows a measurement.

Where the time goes (2026-11-10). marshal (7,400 lines, with json, tui and the library it reads) at -O2, phases timed by a temporary instrument on a machine shared with other builds (load average 30 to 55, so each figure is a range over runs):

PhaseColdOne-line edit (a string literal)
Load and parse0.1 s0.1 s
Check (bodies 90% of it)3.9 to 5.9 s4.3 s
Lower: instances31 to 86 s31 to 54 s
Lower: devirtualize10 to 40 s10 to 40 s
Lower: scalar replacement12 to 31 s12 to 22 s
Shims7.5 s (cached after)0 s
Emit6 to 9 s6 to 9 s
Split into units1.2 to 1.7 s1.2 to 1.7 s
clang, units13.5 s (8 units at once)13 to 17 s (1 unit of 8)
Link0.1 s0.1 s
Total91 s65 s to 149 s

The edit’s columns combine the edited build (149 s at a load average of 55) with an unedited one that did the same work (65 s): avin build lowers and emits the whole program every time.

The program lowers to 71,646 functions and 237 MB of LLVM text. The edit changed one line of that text and the unit cache recompiled one unit, so clang’s part is already incremental; lowering is 75 to 80% of an edit’s rebuild. Most of it is one defect: a tuple type’s record lists as ancestors every tuple its parts may be seen as, one part’s ancestor at a time, which is the product of each part’s traits and itself, and every such record gets its own equality, hash and rendering entries, each an instance of the tuple’s impl at trait types. (Some(1), Some(2), Some(3)) shown once makes 125 instances of the triple’s display; a sextuple of options makes 28,433 functions and 162 MB of text (hello is 303 and 1 MB). In marshal, 33,858 functions and about 100 MB of text are these entries. Withholding the entries from tuple records with a trait part (a probe, not the fix) took marshal to 39,879 functions and 126 MB and clang’s cold part to 8.2 s, but the sextuple still took 2.5 s and 13 MB in the ancestor lists themselves. A sampling profile of what lowering then spends names copying and dropping a whole FunctionSymbol by value in lower_function (about a fifth of its samples), conformance_holds, same_type and collect_ancestors.

The items, each one agent, gated on its own, in this order:

  1. Tuple records. No record for a tuple type no object has, and no entries for one: a tuple’s ancestors are tested by its parts at run time rather than listed as the product. Tests: the instance count of the triple and the sextuple bounded (the emitted text compared with a limit); is, match and equality on tuples seen as tuples of traits, (Display, int) made directly and shown, a tuple in Any shown, compared and hashed, nested tuples, at -O0 and -O2. The largest win, separable, and first. Done: a tuple’s record holds its parts’ records and the runtime tests a tuple target part by part; only a record some object has gets equality and rendering entries. The sextuple of options shown once went from 47,181 functions and 273 MB to 309 and 1.1 MB (hello is 304); marshal from 71,663 functions and 237 MB to 40,478 and 126 MB, its emit-llvm from 165 s to 49 s and its -O2 build from 195 s to 55 s (load averages 107 and about 45, so the times are rough).

  2. Lowering’s constant factors, led by a fresh profile after item 1: symbols read in place rather than copied, and the conformance and type-equality hot spots memoized where the profile says. Its tests are the existing suite; the report gives marshal’s before and after. Done: the fresh profile named loops whose work grew with the square of the program rather than copying alone. Scalar replacement’s test that no two objects of a group are in use at once (overlapping) copied a vector of booleans per block per pass and repeated whole passes; it now keeps 64 bits to a word and revisits only a block whose entry changed. Finding a function’s boxed locals read, and copied, every symbol of the program for every instance; an index of each function’s local functions, built once, replaced it. Recording a slot call searched every call at its position; variant ancestors asked whether each record holds each tested class once per tested type rather than once per class; and the dispatch sites asked the same questions again for every call at one position on one receiver type. marshal’s lowering went from 24.3 s to 7.6 s, by the build log, at load averages of about 10 before and 20 after, with the emitted text byte for byte the same. What remains of lowering is spread out: conformance questions asked for the first time, devirtualization, method tables and scalar replacement, none above a tenth.

  3. Build log. AVIN_BUILD_LOG=<file>: each phase’s time and the counts of instances, units compiled and units reused, with a test of its form on a small program. Every later item asserts through it. Built: AVIN_BUILD_LOG is a file or -, one phase=<name> ms=<n> rss=<n> inuse=<n> maxrss=<n> key=<n> line per phase, documented in the pipeline.

  4. Stable names. Types in instance keys and symbols spelled by qualified names; strings named by content, descriptors and records by type, closures and trap sites by function and place; the module-level tables in a codegen unit of their own. Test: adding a function or a string early in a program changes no other function’s emitted text, and the unit counts in the log say one unit plus the tables’ recompiled. Done: every table is @"avin.<kind>:<name>", named as the pipeline lists, and the tables are the last unit. A function, a string, a class, a data type, a module-level value or blank lines added first in a program change no other function’s text, and a function or string added recompiles 2 of 4 units at -O0 and -O2. marshal’s longest symbol is 319 bytes, with no hash suffix; its text grew from 126 MB to 140 MB. Its edit of one string in a leaf function rebuilds in 19.1 s against 19.0 s before (load average about 7), 3 units of 8 compiled against 2: lowering, checking and emission are still most of it, which items 5 to 7 address, and the edited function, small enough to be copied into its callers’ units at -O2, reaches a third. The C unit’s glue is still named by the checker’s indices (avin_c_call_<symbol>, avin_c_retain_<class>, and the handles’ finalizers), so a declaration added before a C binding renames the binding’s calls.

  5. Instance keys. The canonical typed-tree fingerprint, the interfaces read and the world facts, computed and logged but not yet used. Test: an edit matrix (a body, a signature, a field, a new implementing class, a new impl, a changed default argument, an inferred type changed by a callee’s result, a moved line) changes exactly the keys it must. Done: every instance gets a key after lowering, as the pipeline defines it, logged as phase=keys with instances, bodies and distinct. Devirtualization and scalar replacement report what they decided and read for each function, and lowering the slots it gave methods with type parameters of their own (still numbered past the largest table in the order found, so a larger table anywhere changes the keys of the calls through them, as it changes their text). The matrix builds a program of three modules and edits a body, a signature, a constant and a computed default argument, adds an overload, an implementing class, an impl for a data type and a class field, renames a data field, changes a callee’s inferred result, a lambda, a lambda’s captures and a generic function, and adds comments between declarations and inside one and moves a function; each changes exactly the keys listed, the library’s included, and every function whose emitted text changed has a changed key. Keys are the same across two builds and from another directory. On marshal at -O2, 41,583 instances from 6,596 bodies, all keys different: the keys take 0.59 to 0.63 s against lowering’s 6.9 to 7.9 s (load average about 12).

  6. The instance cache. Store and reuse each instance’s text, requests and summary in .avin/build/incremental/<kind><level>/, the worklist replaying requests, the passes rerun only where facts changed; AVIN_INCREMENTAL=verify. Tests: the edit matrix’s counts; the oracle (incremental text equals a clean build’s) for every edit; two builds of one program at once both correct; a truncated entry treated as a miss; trimming sparing the other level. Done: with AVIN_INCREMENTAL=on (or verify), avin build and avin emit-llvm keep, per module, a lowered entry under each instance’s own key (the requests lowering it made, replayed through the worklist, and its code by stable names) and a text entry under its finished key and the emission facts, in CRC-checked module files named by their keys, a manifest written last and no lock, as the pipeline defines; the passes still run over every instance. The tests hold an edit matrix (a body, a default argument, a signature, a constant, a class field, a renamed data field, an overload, an implementing class, an impl for a data type, a generic function, a callee’s inferred result, a lambda’s body and captures, lines added above and inside a function, a moved function, a call removed) to lowering exactly the instances with new own keys and to a clean build’s text, and cover truncated, damaged and missing files, another compiler’s entries, trimming, two builds at once, -O0 and -O2, and a corpus sample built warm. On marshal at -O2 (load average 30 to 70), a one-line leaf edit rebuilds in 21.1 s against 27.0 s without the cache (cold 26.7 s against 26.9 s): emission 5.8 s to 1.5 s and the keys 0.8 s to 0.13 s, but lowering only 11.0 s to 9.1 s with 24,246 of 41,583 instances’ code from the cache, since the passes still run everywhere and checking (7 s) is untouched; verify passes on the edit and back. The cache is 22 module files, 185 MB.

  7. The commands. avin build, run and test and the language server’s builds through it, the corpus run with the cache warm as well as cold (each corpus program edited by a script and checked against a clean build). Done: the cache is on by default for avin build, run, test and emit-llvm, off and verify kept; check keeps none, and the language server only checks, so it builds nothing to cache. A program of one file names its directories after itself (hello-program-O2), and a manifest may name only module files of its own directory. With AVIN_INCREMENTAL=verify in the tests’ environment the corpus builds each program cold with the cache, adds a function nothing calls to its first file, and builds it again in verify mode, the warm build being the one run; avin test of the library and the packages runs in verify too. Its first run failed 10 of the 202 programs of many files, all with C bindings: the C unit’s glue is named by the checker’s indices (avin_c_call_<n>, avin_c_field_get_<n>), which the edit renumbered and no key held, and every C callback’s body had one key, so one binding’s took another’s text. Code calling the glue is now lowered every build and the glue it calls is in its text’s key, and a callback’s body is keyed by its binding and trampoline. The second run passed whole: the 1,221 programs of tests/run, the 202 of tests/programs/run, the examples, the example packages, the library’s and the packages’ tests, 25 tests. The commands’ tests build, run and test a program, edit it and hold each rebuild to a clean build’s program and text; hold off to reading and writing nothing; survive damaged files, a manifest of nonsense, another compiler’s cache and trimming; and run two avin test, and a run beside a test, of one program at once. On marshal’s 138 modules (one avin build, the whole machine reserved, load average 4 to 6 at the start and end; the object-unit cache emptied before each cold build and the edit new to it on every edit build; median of 3 runs, spread in brackets; emit from the build log):

    Build-O0-O2
    Cold, no cache6.06 s [5.99 to 6.09]8.79 s [8.75 to 8.84]
    Cold, with the cache6.54 s [6.52 to 6.66]9.33 s [9.32 to 9.39]
    Warm, no edit4.88 s [4.86 to 4.92]4.93 s [4.92 to 4.96]
    One-line edit, no cache5.81 s [5.77 to 5.85] (emit 1.21 s)7.47 s [7.41 to 7.95] (emit 1.32 s)
    One-line edit, with the cache5.02 s [5.01 to 5.09] (emit 0.30 s)6.72 s [6.69 to 6.80] (emit 0.30 s)

    An edit’s rebuild is 14% faster at -O0 and 10% at -O2 with the cache: the cache read (0.23 s) and write (0.04 s) cost less than the 0.9 s of emission it saves, and what remains is loading (0.06 s), checking (1.4 s), lowering (2.0 s, 11,902 of 15,447 instances reused, the rest lowered again), splitting and linking, which the cache does not touch; at -O2 clang’s compile of the changed units (2.1 s) is the other part. A cold build with the cache costs 0.5 s more than without it (the store). A level’s directory is 185 MB in 22 module files.

  8. Only if measured after 7: the front end. If checking becomes the larger part of an edit’s rebuild, a design for checked interfaces per module (today one checker holds the whole program by index, so this is a rewrite of how symbols are numbered, not a cache).

Contextual parameters: build plan

Designed in contextual parameters, its choices settled. Steps 1 and 2 are done (branch given-1), step 3 too (branch given-3), step 4 (branch given-4), step 5 (branch given-5) and step 6 (branch given-6). A filled argument becomes an ordinary argument in the checker’s output, so lowering, emission and the runtime change nothing; every step is in the front end and tooling. Each step is one agent, gated on its own with the files it names.

  1. Syntax. given name [: Type] = value in blocks, at a module’s top level and in object bodies, with given a keyword only there at a statement’s or declaration’s start; a trailing using section in the parameter lists of functions, methods, static members, class constructors, actors and lambdas, using a keyword only before a parameter’s name; the syntax tree, avin fmt (a long list breaks before using as before any parameter), syntax_show. Files: parser.sysl, parse_decl.sysl, parse_block.sysl, parse_actor.sysl, syntax.sysl, formatter.sysl, syntax_show.sysl; tests in parse_tests.sysl and formatter_tests.sysl. Proof that nothing existing changes meaning: git grep -n -E "^\s*given\b" over library/, tests/, examples/ and marshal’s and tui’s sources prints nothing, and the corpus is unchanged (args.given(…), iterable.avin‘s field given). Done (branch given-1): given begins a given where a name and its : or = follow it, or val, var or a capitalized name (reported); using begins the section where a name follows it, also in a parenthesized lambda’s list and as using tx ->, alone or trailing a call. The syntax tree carries Param.contextual, LambdaParam.contextual, FieldDecl.given and the block’s GivenBinding. Tests: parse_tests.sysl (given_*, using_*), formatter_tests.sysl (fmt_contextual_parameters), tests/reject/given_syntax.avin.
  2. Declarations. Given symbols as module values, object members and block locals; using parameters on function symbols; the refusals with their messages (a type parameter in a contextual type, a built-in, tuple, function or union type, a trait that is only a bound, a second given of one type in a scope, given in a class/trait/data body, a section on a variant, main, @test, a hook, @sysl/@c, an unnamed given, an implementation whose section differs from its trait method’s). Files: check.sysl, names.sysl. Tests: tests/reject/given_*.avin, one refusal per file group of at most five errors. Done (branch given-1): a block’s given is a val recorded in BodyState.givens; a module’s is a GlobalSymbol with given set; an object’s is a field its declaration marks; each is held to its type and to one of a type per scope (check_givens, given_binding_expr). A function’s clauses match the parameters before its section. Calls are untouched: a contextual parameter is still an ordinary one at a call, so explicit tx = … works and a missing one is the missing-argument error until step 3, which also owes a call to a function whose repeated parameter is followed by a section (today the repeated parameter is taken as last). Tests: tests/reject/given_{block_types,second_of_type, bodies,using_types,using_types_more,using_positions,using_implementations,using_names}.avin, tests/run/given_{declarations,using_declared}.avin, tests/programs/run/given_module_files, tests/programs/reject/given_module_second.
  3. Resolution at calls. After an overload is chosen, fill each contextual parameter: a named argument, then the levels of the chapter’s scope walk, then the default; the errors for none, two, and a positional argument; defaults seeing the section; class constructors, super arguments, companions’ apply, infix calls, clauses, static members through a bound, trait methods through a trait type and through a bound, extensions. Files: check.sysl. Tests: tests/run/given_*.avin and tests/reject/given_*.avin. Done (branch given-3): fill_contextual runs in apply after the written arguments bind, so every call shape that reaches apply fills its section; fitting_givens walks the levels (block givens and local functions’ and lambdas’ contextual parameters by their scope in visible, then the checked function’s parameters, the class’s constructor fields, the object’s given fields, the module’s givens of every file) and a filled argument is a by-name argument already checked, so lowering is untouched. Positional arguments and a trailing block reach only the parameters before the section; a repeated parameter followed by a section binds and packs at its own position; the section’s defaults are computed first, each seeing the section before it, and an ordinary default takes the whole section after its earlier parameters (default_inputs). A using lambda’s parameters are givens in its body already. Givens imported from another module fill nothing yet (step 4); a function value’s section is step 5’s. Tests: tests/run/given_calls_{levels,shapes,edges}.avin, tests/reject/given_calls_{none,scope,two, positional,values}.avin, tests/programs/run/given_module_files, tests/programs/reject/given_import_{whole,named}.
  4. Modules and imports. A named import (direct, braced, as, through an export) brings a given in; a whole import does not, with the hint naming the import to write; private; module and object givens made in initialization order; a module of several files sharing its givens. Files: check.sysl, names.sysl, incremental.sysl (a module’s givens are part of what an importing file depends on). Tests: tests/programs/run/given_* and tests/programs/reject/given_*. Done (branch given-4): given_module_level takes, beside the module’s own givens, the givens another module declares that the module exports by name and those the call’s file imports by name (each under the name its export or import binds, one given however many names reach it); the “no given” error adds, for each public fitting given of a module the file imports whole, the import to write (given_import_hint). Imported givens need nothing of the instance cache: a filled argument reads the module-level value, whose interface a key already holds. Initialization order needed no change, a given being a module-level value. Tests: tests/programs/run/given_import_{forms,named}, tests/programs/reject/given_import_{whole,per_file,private,two}, given_import_tests.sysl, instance_cache_tests.sysl (imported_given_*).
  5. Lambdas, function values, threads and actors. using lambda parameters as givens in the body; a function or method taken as a value filled where taken; captures of givens through the existing capture analysis; the @sendable, spawn, executor-task and actor checks naming a captured given; actor constructors’ sections. Files: check.sysl. Tests: run and reject files as above. Done (branch given-5): function_value and method_value take the parameters before the section, and with a section make the value a closure (value_closure) whose body is the call a call written there would be, checked with the closure as the current function and its parameters passed as checked arguments (passed_on, a repeated one spliced), so apply fills the section from the givens in scope where the value is taken or from its defaults, and each given read is recorded as the closure’s capture. Overloads, an object’s apply and constructors are chosen by the parameters before the section. The spawn, @sendable, executor and actor checks name a captured given through the existing capture analysis; an actor’s section is held to Sendable as any actor parameter. Tests: tests/run/given_{values,captures,threads}.avin, tests/reject/given_calls_values.avin, tests/reject/given_values_{more,threads}.avin.
  6. Tooling. Hover on a call shows each filled argument and the given it came from; go to definition from a call to the given it used; completion offers given and using. Files: lsp.sysl, completion.sysl, definition_index.sysl; tests in lsp_tests.sysl. The IntelliJ plugin’s grammar (avin-intellij) is its own item, shipped with the release that carries step 1. Done (branch given-6): fill_contextual records each call’s givens (index_filled_call), and when the call is indexed each becomes a reference at the call’s name marked filled with its parameter (index_fills). Hover adds “Filled from givens:” with tx = current // val current: Tx per parameter; definition answers the function, then each given; a given’s references and highlights include the calls it filled; rename and semantic tokens leave them out. Signatures write using once before the section, and a completed call’s snippet leaves the section out. completion_keywords offers given and using where a form may begin with them. Tests: lsp_tests.sysl (lsp_hover_filled_call, lsp_definition_filled_call, lsp_references_filled_call, lsp_semantic_tokens_filled_call, lsp_definition_given_levels, lsp_definition_given_other_file, lsp_signature_using_section, lsp_completion_given_using, lsp_completion_keywords_of_sites).

The test matrix. Each claim of the chapter is a test; these are the cases the steps owe.

  • Declaring: givens of a class, an object, a trait type, a data type with one and several variants, a generic instance (Pool[Conn]), a value type data Retries(count: int); a given with a declared wider type; scope from the declaration on (a call before it sees the outer one); a given not in its own value; a nested block’s given hiding an outer one; a Unicode-named given; given still an ordinary name after ., in a class body, as a field and after then.
  • Calls: a given filling a supertype’s parameter; a subtype parameter not filled by a supertype given; explicit tx = … beating a given; the default with no given and not with one; a default seeing the section; forwarding through recursion, mutual recursion and a tail call (still a tail call at -O0 and -O2); local functions; overloads where the written arguments choose and a missing given does not fall back; infix calls; clauses; a static member through T.m(); a trait method through a trait-typed value (dynamic dispatch) and through a bound; an extension’s method.
  • Classes and actors: a constructor’s section used in field initializers and methods; a subclass passing its own given to its superclass; a companion’s apply; an actor taking a sendable given.
  • Generics: a generic function calling a contextual one at many type arguments, one given for all; [T: Ord] code with an unrelated given in scope ordering by T‘s impl (the coherence claim: a TreeSet built in one file and searched in another with givens around keeps its order).
  • Lambdas: a closure capturing a given and called after its block ends, under GC stress; a using lambda parameter; a method value filled where taken; the error where none is in scope.
  • Imports: named, braced, renamed and exported imports bring a given; a whole import does not (reject, with the hint); a private given not importable; a module given beside an imported one of a fitting type (reject, both named).
  • Refusals: each message of the chapter’s diagnostics list, and each refused type and position.
  • Every run test at -O0 and -O2 and under GC stress, as the corpus runs.

Sound initialization: build plan

Designed in Initialization, its choices proposed in decisions: no field, module-level value or lazy val is read before it is set, proved when the program is compiled.

What 0.0.21 does (probed 2026-11-13). The class-body rule, the open-class rule, trait fields, the module order (within and across modules, through calls, dispatch, operators, iterators, default arguments and lambdas made) and locals are all checked at compile time, and every probe of them was refused with the error the chapter gives or ran correctly. What is not:

ProbeWhat happensKind
A lambda in a superclass’s arguments reading a field, class Late: Base(() -> late), the superclass calling it in its bodya long field read 0; a string, Vector or generic field crashed (exit 139)closed by item 1: refused
The same with a method value, Base(name)crashed (exit 139)closed by item 1: refused
The same with an argument passed by name, Base(pick(true, s * 2))read 0closed by item 1: refused
The same for an inherited field, Leaf: Mid(() -> m) with m Mid’sread 0closed by item 1: refused
The same from an object extending a classread 0closed by item 1: refused
lazy val first = second + 1, lazy val second = first + 1; a field lazy val l = l + 1trap at run time, although the cycle is in the codemodule-level closed by item 3, fields and locals by item 4: refused
A lazy’s initializer joining a thread that reads the same lazywaits for everliveness
object O whose lazy val or a lambda made after its last field names O.krefused: O is needed by its own initializer (bare k is accepted)closed by item 2: accepted

The holes have one cause: field_read in check.sysl refuses a field read only when the constructor is the current function, and the superclass’s arguments are never scanned by check_class_initialization, so a function made there (a lambda, a by-name thunk, a method value) reads the object unchecked. Nothing in library/, examples/ or packages/ passes such a function (grep of every class header with a superclass call for ->: none), so closing it changes no code there. The lazy change turns tests/run/lazy_cycle.avin and tests/run/lazy_threads_cycle.avin into reject tests; the library’s own self-referring lazy values (the LazyList knots in lazy_list.avin) read themselves by name inside an argument passed by name, which stays legal.

All four items are done: every probe above is refused at compile time or runs correctly, but the liveness case, which the chapter leaves to the threads rule. The items, each one agent, gated on its own, in this order:

  1. Done: superclass arguments use nothing of the object. check_class_initialization scans the superclass-initialization item with an InitScan for the superclass’s arguments (no field ready, inherited or own), so a lambda, a by-name argument, a local function or a method value that uses self, a field or a method is an error with the chapter’s wording; objects extending a class go through the same path. Files: compiler/dev/avinlang/compiler/check.sysl (check_class_initialization, init_violation‘s wording, the method-value case near check.sysl:15773). Tests: tests/reject/initialization_super_args.avin (a lambda reading an own field, one reading an inherited field, a method value, a by-name argument, an object’s arguments) and tests/reject/initialization_super_args_more.avin (a generic superclass, a lambda inside a lambda, a lambda calling a method, one in a tuple or a collection argument, a lambda through two levels of superclass); tests/run/initialization_super_args.avin, the legal cases (functions capturing class parameters, module values and another object, a by-name argument reading a parameter, the superclass calling each in its body), at -O0 and -O2 under GC stress. Every 2026-11-13 hole above is one of these cases. Also tests/reject/initialization_super_args_shapes.avin (a collection argument, a lazy val, a closure in an argument object’s field, a with copy, a conditional argument), tests/reject/initialization_super_args_values.avin (a method value inside a lambda, a lambda assigning a field, a by-name argument making a lambda, a trait’s val the class supplies, a generic subclass) and tests/programs/reject/initialization_super_args (the superclass in another module). A method of the object named as a value there is refused where it is written, as a call of one already was. A local function cannot be written in a superclass’s arguments, which take no block, so the scan’s case for one is reached by no source today.
  2. Done: an object’s name is self in its own body. global_read in check.sysl, where every read of a module-level value is made (a bare name, a call of the object’s apply, its constructor by the companion’s name, a pattern naming it), reads the object’s own name as self inside its body, methods, overrides, lambdas and lazy initializers, so the object rules apply to it and the module order counts only what the body runs while the object is made; the editor still shows the name as the object’s declaration. Tests: tests/run/initialization_object_self_name.avin (a lazy field reading O.k, a lambda made after the last field stored and called later and one called at once, a method, an override calling super, an object extending a class and a generic class, the field it inherits read before its own, a field assigned through the name, a companion’s constructor and apply, a pattern naming the object, two objects naming each other, a thread and a future in a method of an object with no var, a module value declared above the object reading it), tests/reject/initialization_object_self_name.avin (O.y above y, O passed before the last field, O.m() before the last field, O read in its superclass’s arguments directly and in a lambda), tests/reject/initialization_object_self_name_more.avin (a lambda, a method value, a lazy val read and a by-name argument through the name before the last field; a function outside the body reading the object, called while it is made, still a cycle), tests/programs/run/initialization_object_self_name and tests/programs/reject/initialization_object_self_name (the object in another module), and an lsp_tests.sysl case for definition from the name in the body. A field lazy val l = O.l + 1 in an object, a run-time trap here as a bare l was, is refused by item 4.
  3. Done: module-level lazy cycles at compile time. Uses (globals.sysl) keeps the functions a body calls (calls) apart from those it makes (made: lambdas, by-name thunks, method values); check_lazy_cycles in check.sysl follows only calls and the lazy values read (lazies_reached), stopping at another lazy value’s initializer, and a module-level lazy val that reaches itself is an error naming the chain of lazy values, reported from its earliest-declared member as module cycles are. The module order follows both, except a lazy val field’s initializer where a constructor makes it (only a read runs it, and a read is a call), which removed the false cycle of two objects whose lazy fields read each other. The run-time trap stays for reads through handed-on functions. Tests: tests/reject/lazy_cycles.avin (itself, through another lazy, through a function, through a trait’s implementation, through an operator), tests/reject/lazy_cycles_more.avin (an open class’s override, a generic function, a generic class’s method, a default argument, a comparison operator), tests/reject/lazy_cycles_reach.avin (a chain of three named from its earliest member when the check meets it from outside, a lazy field’s initializer, an iterator’s next in a for, a local lazy val in a called function, two values read by two threads), tests/reject/lazy_field_made_order.avin (a body reading its own lazy field, a lambda made and called while the object is made: still module cycles), tests/reject/lazy_cycle.avin (moved from tests/run), tests/programs/reject/lazy_cycle_modules/ (across two modules), tests/run/lazy_self_deferred.avin (ones, the Fibonacci knot, #::, a handler naming its own value, a method value stored, self-recursive and mutually recursive lambdas, a generic cell, a chain with no cycle, the two objects, a value holding a class and a generic class whose lazy field reads it, threads), tests/programs/run/lazy_objects_modules (the objects across two modules), tests/run/lazy_deferred_trap.avin (a lambda the initializer makes and calls at once: still the trap, .err) and tests/run/lazy_deferred_trap_passed.avin (one passed to a function that calls it).
  4. Done: field and local lazy cycles at compile time. check_lazy_field_cycles in check.sysl follows each lazy field’s initializer (reach_function, LazyReach) with the places its code holds the object (SelfAt: the captured self, a local given it, the parameter a called function receives it in, and an object’s name anywhere), through calls, the overrides a call through a slot on the object may reach in classes descending from the field’s, operators and local functions; a read of another instance is not followed. check_local_lazy_cycles follows each local lazy val‘s lambda through its block and the local functions it calls. Both report through report_lazy_cycle, worded as the module-level check. Tests: tests/reject/lazy_field_cycles.avin (direct, through another lazy field, a method, self.x, a subclass’s override), lazy_field_cycles_generic.avin (a generic class, a chain, a generic method, a generic subclass’s override, a generic function given self), lazy_field_cycles_object.avin (bare name, the object’s name, a function outside the body, a module-level lazy between), lazy_field_cycles_more.avin (an object extending a class, an actor, an operator, val me = self, a local function), lazy_field_cycles_reach.avin (a chain of three from its earliest member, a trait’s default method, a local lazy in the initializer, a default argument, a superclass’s field and the subclass’s override), tests/programs/reject/lazy_field_cycle_modules (a subclass and a function in another module), tests/reject/lazy_local_cycles.avin and lazy_local_cycles_more.avin (direct, nested, a local function, a method, a loop body, a lambda’s body, a field’s initializer, a generic function, two local functions, a match arm), tests/reject/lazy_threads_cycle.avin and lazy_local_self_direct.avin (moved from tests/run); tests/run/lazy_field_other_instance.avin (a node’s depth, a tree’s size, another instance’s field through a method, a generic chain, an object over instances, a chain with no cycle, an override reading another field, a handed-on lambda, threads), tests/run/lazy_local_no_cycle.avin, and tests/run/lazy_threads_handed_trap.avin (a handed-on read on a second thread: still the trap).

The test matrix every item fills, each cell a test that would fail if the rule were false:

RuleRefused shapesAccepted shapesNeighbours
Class bodyread below; method; self passed; lambda, by-name, local fn, method valueread above; after the last field anythinggeneric class, actor class, with-free data
Open/abstract bodyoverride reachable; trait val a subclass supplies; unsafe privatesafe private methodtrait default method
Superclass argumentsevery function using the objectparameters, module valuesobject extending a class, generic superclass
Trait fieldsmethod call; lambda; field belowfields above, parameterstwo traits, required traits
Object nameabove its field; passed earlylazy, lambda after last field, methodobject extending a class
Module valuescycles in one module, across modules, through dispatch, operators, defaults, iteratorsdeclaration order keptobject, var written by another initializer
lazy valself, chain, function, dispatch, field via selfother instance, handed-on read after returnthreads, actors, generic class

Higher-kinded types: build plan

Higher-kinded types and the standard constructor traits are designed in generics, their choices proposed in decisions. All nine steps are done. Each step is one agent’s item, gated on its own (targeted files plus the corpus), and lands the tests listed; no step builds a path a later one removes. The spec’s examples are plain text fences, which no test reads; step 7 makes the finished ones text run programs with text output fences, which corpus_tests.sysl then builds and runs.

Representation. TypeParam (syntax.sysl) gains its holes, each a variance and bounds; TypeExprKind gains Hole for a _ argument. Type (types.sysl) gains Constructor(body, arity), whose body is a data type, class or trait with Hole(i) among its direct arguments (the normal form, so same_type on constructors is structural), and Applied(head, args), an application of a constructor parameter. substitute reduces Applied(Constructor …) to the body with the holes filled, so after monomorphization no Applied or Constructor is left, and lowering, layout and emission see only the types they see today; type_key names a constructor (Result[_,ParseError]) so instance keys and the incremental store keep one copy per constructor.

  1. Kinds and constructor parameters, written. Done. Parse F[_], F[_, _], F[+_] in every type parameter list and _ in type arguments (parse_decl.sysl, formatter.sysl); the two Type forms, substitute, solve, same_type, type_key; kind checking wherever a type is resolved (check.sysl‘s type resolution); constructor arguments written at calls and in types: a bare generic type, a partial application, an alias that is a constructor, another constructor parameter; instance keys (lower.sysl instance_key, keys.sysl). Tests: tests/run/ constructor parameters on a function, a method, a data type and a class, at one and two holes, with value-type arguments (F[int] unboxed at Vector), -O0/-O2, under GC stress; Parsed and Result[_, E] one instance (a counter in a module value); tests/reject/ one file per kind error the spec names (constructor as a type, type as a constructor, wrong arity, nested _, F[_[_]], an alias that is no constructor); parse_tests.sysl and formatter_tests.sysl for the forms.
  2. Inference without bounds, hole variance and hole bounds. Done. F inferred from a type of as many parameters as it takes holes, and the error asking for it otherwise; F[+_] subtyping inside the declaration and the check on the constructor passed; F[_: B] checked at every F[X] written and against the constructor’s own bounds. Tests: inference from arguments and from the expected type; F[+_] accepting Option and refusing Array; F[_: Ord] taking TreeSet and plain _ refusing it; F[X] at an X missing the hole’s bound reported at the definition; polymorphic recursion through a growing constructor (expansion.sysl) rejected and a non-growing one accepted.
  3. Constructor traits and their impls. Done. Self[X] in a trait’s methods, its arity and the requirement chain; impls naming the holes and the bare form; coherence (once per type, the module rule, no inherited conformance); the meeting rule, recording per trait method the type’s method in its table and the type arguments the meeting decided (meet_method in check.sysl, TProgram.meetings), so a call through the bound lowers to a direct call of it; a value of F[X] has the bound’s members; constructor arguments written explicitly at calls, held to the bound’s conformance; default bodies compiled per implementing constructor, Self the constructor in each copy. Tests: tests/run/constructor_traits*.avin (a data type, a class by its header and by an impl, two-parameter types at each hole, List‘s overloaded flatMap and Result‘s lower-bounded one meeting, defaults at several constructors, two-hole traits, a bounded trait parameter, a conditional impl, -O0/-O2 and GC stress), tests/programs/run/constructor_trait_modules; reject files for each refusal (tests/reject/constructor_trait_*.avin, tests/programs/reject/constructor_trait_module_rule).
  4. Inferring a constructor through its bound. Done. Matching F[X] through the conformance and the nearest superclass (bound_constructor in check.sysl; the “one trait” case is unreachable while no impl is for a trait, see decisions); the written-out arguments joined by variance (widened_constructor: a Result[int, Dog] beside a Result[int, Cat]), the head required to agree; the expected type; a lambda’s result deciding G; two bounds disagreeing on the holes an error naming both. Inference no longer sees a subclass as its superclass off a read position (held_as), a soundness fix the superclass matching met. Tests: tests/run/constructor_bound_inference{,_more,_gc}.avin, tests/run/inference_subtype_reads.avin, tests/reject/constructor_bound_infer_failures.avin, tests/reject/inference_no_subtype_off_read.avin.
  5. Static members on constructors and per-constructor defaults. Done. F.pure and a constructor trait’s Self.pure in its default bodies (the parameter itself as the receiver, its bounds’ static members); Option.pure, Result[_, E].pure, Box[_].pure and an alias that is a constructor (constructor_receiver, constructor_statics in check.sysl: the static members of the constructor traits it implements at exactly its holes); each a BoundCall that lowering (bound_call) makes a direct call of the constructor’s own member, at Nothing for the holes, so one instance per constructor; function values of both; a default overriding a required trait’s method (Monad‘s map), its Self seen from the trait itself. Tests: tests/run/constructor_statics{,_defaults,_gc}.avin (F.pure at data types, a class, partial applications and an alias, through two bounds, in closures and a generic class; the default map at four constructors and the types’ own meeting map still called; GC stress), tests/reject/constructor_static_{refusals,receivers,bounds}.avin.
  6. Impls over constructor parameters. Done. impl[F[_]: B, A] F[A] and F[G[A]]: receiver matching through the conformance (match_applied in check.sysl, by bound_constructor, a subclass as the superclass that conforms, an F[X] in generic code where its bounds include the impl’s); the own-methods-first rule, as for an impl adding to a trait (adds_to_constructor); the impl the bound trait’s own in its module and an extension elsewhere (in_bound_module); extensions seen by import, their method values reported as calls are; two matching impls an error; a receiver that matches none told why. Tests: tests/run/constructor_param_impls{,_gc}.avin, tests/programs/run/constructor_param_extensions (an extension module adding to every Pointed, seen only where imported), tests/reject/constructor_param_impl_{calls,decls}.avin, tests/programs/reject/constructor_param_extension_{unseen,clash}.
  7. The library. Done. library/avin/functor.avin: Functor, Foldable, Applicative, Monad, Filter, Traverse, sequence, SendableFunctor, SendableMonad; the impls of the spec’s table, for concrete types only, each giving only what the type lacks (pure, traverse, foldLeft on Option, Result, Either), and impl SendableMonad for Future. Foldable is a trait for types that bounds constructors at its holes (bounds_constructors in check.sysl: bounds, a constructor trait’s requirements, impls over constructor parameters, inference), and Iterable requires it, so every collection folds through [F[_]: Foldable]; a constructor trait’s parameter bounds no longer demand anything of the conforming type’s parameters (conforming_type_param). Tests: library/tests/functors.avin (the functor and monad laws through the bounds for every type in the table, traverse and sequence answering the first failure with every element given to f, cartesian map2 beside zip, Future‘s pure), tests/run/functor_own_methods.avin (own methods’ result types by type patterns), tests/run/foldable_constructor_bounds{,_gc}.avin, tests/run/sendable_monad_conformance.avin, tests/reject/foldable_constructor_bound_{refusals,inference}.avin, tests/reject/sendable_monad_conformance.avin; the spec’s pairUp, Parser and traverse examples are run fences.
  8. Comprehensions by conformance. Done. for_yield_expr (check.sysl) admits each source by its roles (admitted_source, implements_role: an Iterable, or Functor/Monad/Filter or the sendable pair, through bounds in generic code) before checking its calls as before; the guard on a non-Iterable source calls filter; the library’s withFilter views conform to Iterable. The generator-mismatch diagnostic naming the later generator (yield_frames, taken_by_frame) is taken from the parked branch monadic-for. A bound of two traits reaching one method through an override (F[_]: Monad & Filter‘s map) has the override alone (bound_methods), a bug the comprehensions met. Migration: the Maybe of tests/run/for_yield_forms.avin and for_yield_definitions.avin and the Box of spec_collections_comprehensions.avin gain their impls; futures_for_yield.avin is unchanged, through SendableMonad. Tests: tests/run/for_yield_conformance{,_gc}.avin (every role at a class, a data type, two parameters, a subclass, Option, Result, Either, mixed with collections and through bounds, with the order of evaluation logged), tests/run/filtered_views_iterable.avin, tests/run/bound_override_diamond.avin, tests/reject/for_yield_roles{,_more}.avin, tests/reject/for_yield_generator_mismatch.avin, and the updated tests/reject/for_yield_{sources,definitions}.avin.
  9. Tooling. Done. Hover and completion of a constructor’s members: a value of F[X] offers and shows its bounds’ methods, F. and Self. their static members, Option., Result[_, E]. and an alias that is a constructor the static members of the constructor traits it implements (constructor_static_members in check.sysl; a partial application offered nothing before), and a conforming type the methods an impl over a constructor parameter adds; a signature, a declaration and a type parameter are shown with their holes (show_type_param in syntax_show.sysl, used by definition_index.sysl‘s headers and the type parameter’s own hover, type parameter F[_]: Monad). avin fmt of every form: constructor traits, their impls by name and by holes, impls over constructor parameters, F.pure and the static members of a partial application and an alias, hole variance and bounds. A method or a local function whose constructor parameter opens with -_ was read as an expression (local_function_ahead in parse_decl.sysl), a bug the formatter met. The editor grammar (editors/vscode/syntaxes/avin.tmLanguage.json, which the IntelliJ plugin bundles) reads the brackets after a name as types: a hole and its variance, a type parameter’s variance, and declarations and calls whose type brackets nest. Diagnostics give a letter standing alone its letter’s article (an F[int], a T, a unit; article in check.sysl). Tests: lsp_tests.sysl (lsp_hover_constructor_members, lsp_completion_constructor_members), formatter_tests.sysl (fmt_constructor_traits, fmt_constructor_param_impls, fmt_constructor_statics), parse_tests.sysl (constructor_param_contravariant_members), editors/grammar-tests/samples/constructors.avin, the plugin’s AvinEditorTest, and tests/reject/article_letter_{names,types,sendable}.avin.

Releases

Releases are cut from dev at any stage, as the language stands, by scripts/release.sh (Releasing). The first, 0.0.1, is the first installable compiler: a Homebrew formula and a macOS arm64 tarball.

Search

Esc
↑↓ to navigate ↵ to open Esc to close