Moxy language reference
Moxy is C11 plus a small set of additions: managed strings, lists and maps, tagged enums with match, optionals (T?), Result error values, closures, futures and channels, namespaces, defer, and automatic memory management. Any C you write inside a .mxy file means what it means in C. This reference covers what Moxy adds and how it interacts with C.
- Lexical structure
- Types
- Declarations
- Generics
- Methods and interfaces
- Compile-time reflection
- Expressions
- Statements
- Pattern matching
- Optionals
- Errors and Result
- Built-ins and methods
- Closures
- Concurrency
- Modules
- Working with C
- Diagnostics
- Testing
- Targets and platforms
- Standard library
Memory management has its own chapter: memory.md.
Lexical structure
Comments: // line and /* block */. A /// line or a /** ... */ block directly above a declaration is a documentation comment; see moxy doc.
Reserved words: every C11 keyword, plus bool, true and false (keywords in C23 too). string and null are the string type and the null pointer, but they can also name a variable, parameter, field or function, as they can in C.
Reserved names: names starting with mxy_ belong to the runtime. A program can't define or declare a function or a global with one, or put one inside a namespace named that way; that is a compile error. An extern declaration of a runtime function is allowed. Moxy's own library keeps its private helpers under std_.
Contextual words: match, in, defer, await, namespace, using, ref, weak, unowned, strong, fn, map, Result, Future, chan, select, Ok, Err, Some, None, impl, interface, dyn, self and Self have meaning only in their own syntax. They remain valid identifiers elsewhere, so C code that uses map, in or match as variable names keeps compiling.
Literals
| Kind | Examples |
|---|---|
| integer | 42, 0x2A, 0b101010, 052, 42u, 42L, 9000000000 (inferred long) |
| float | 3.14 (double), 2.5f (float), 1e9, 0x1p4 |
| char | 'a', '\n', '\x41' |
| string | "text", "tab\tnewline\n"; adjacent literals concatenate: "a" "b" |
| interpolated string | "\(name) is \(age) years old" |
| bool | true, false |
| null | null (also C's NULL) |
Inside a string, \(expr) evaluates expr and formats it the way print does. Interpolation nests: "outer \("inner \(x)")".
Types
C types
All C types work as written: int, unsigned long, char *, const char *, fixed arrays int buf[16], function pointers int (*cmp)(const void *, const void *), struct, union, C enum, and typedef. Types from headers (FILE, size_t, SDL_Window) can be used without declaring them.
Fixed-width integers
i8 i16 i32 i64 u8 u16 u32 u64 isize usize f32 f64 name the <stdint.h> and <stddef.h> types, and the generated C spells them that way:
| Name | C type | Name | C type |
|---|---|---|---|
i8 i16 i32 i64 |
int8_t ... int64_t |
u8 u16 u32 u64 |
uint8_t ... uint64_t |
isize |
ptrdiff_t |
usize |
size_t |
f32 |
float |
f64 |
double |
They are contextual, not keywords. A program that declares something with one of these names (int u8 = 3;, int i16(int x), a field) keeps its own meaning for that name everywhere, and a C typedef ... u8; wins over the alias. A name is read as a type only where a type can be followed by what comes next (u8 x, u8 *p, (u8), u8[], Pair<u8>), so a C variable from a header named u8 still reads as a value in u8 + 1 or f(u8 - 1); before *, ) or ,, as in f(u8), it reads as a type, the same ambiguity C has with typedef names. Lists and maps of these types print, compare, hash and sort like int.
Integer arithmetic
Signed + - * overflow and integer / % by zero are undefined in C. In a debug build (moxy run, moxy build, moxy test) they panic with the location instead, and so does INT_MIN / -1:
panic: integer overflow in '+'
at sum.mxy:7:15
A --release build (-O2 -DNDEBUG) compiles the same C to the plain operators: its machine code is what C would produce.
- Unsigned arithmetic wraps, as in C, in every build.
- Narrow types follow C's promotions:
i8 + i8is computed inint, so withi8 c = 127,c + 1is128; storing it back into ani8wraps without a panic. - Checked:
+ - * / %on integer operands,+= -= *= /= %=, and++/--onint,long,long longand the signed<stdint.h>types. Not checked: pointer arithmetic, floats, bit-fields, values whose type Moxy can't see (C macros such asINT_MAX, C globals), constant expressions (static initializers,caselabels,sizeof), division by a literal, and the step offor (...; i < n; i++)when nothing else in the function writesi. - In the generated C these are
MXY_ADD(a, b, "file.mxy:3:9"),MXY_SET(ADD, +=, x, y, ...)and so on, defined inruntime/arith.h. Without__builtin_add_overflow(non-GCC/Clang compilers) they are the plain operators in every build.
Explicit forms, on every integer type (char through unsigned long long and the names above), compute in the receiver's type in every build:
| Method | Result |
|---|---|
x.wrapping_add(y), wrapping_sub, wrapping_mul |
the result modulo 2bits: with i8 x = 127, x.wrapping_add(1) is -128 |
x.saturating_add(y), saturating_sub, saturating_mul |
the result clamped to the type's range: with u8 b = 250, b.saturating_add(10) is 255 |
x.checked_add(y), checked_sub, checked_mul |
a T?: the result, or null when it doesn't fit: with i8 x = 100, x.checked_mul(2) is null |
y converts to x's type first.
% on floating-point operands is C's fmod (C has no % for them): 7.5 % 2 is 1.5.
bool
bool with true and false. Comparisons and logical operators produce bool, so print(1 < 2) prints true.
string
An immutable, reference-counted UTF-8 byte string. In generated C it is a const char * to NUL-terminated data, so it can be passed to any C function that reads a string.
string name = "moxy";
string greeting = "hello " + name; // concatenation
bool same = greeting == "hello moxy"; // content comparison
print(name.len, name.upper(), name[0]); // 4 MOXY m
==,!=,<,<=,>,>=compare contents; comparing withnullcompares the pointer.s[i]is a bounds-checkedchar.- A
char *from C becomes astringby copying, which happens automatically on assignment, or explicitly withstring(p). - Adding a number to a string is an error. Use interpolation:
"n = \(n)".
Lists: T[]
Growable, bounds-checked arrays with value semantics (copy-on-write).
int[] xs = [1, 2, 3];
xs.push(4);
int[] ys = xs; // independent copy
ys[0] = 100; // xs[0] is still 1
Point[] pts = [Point{ .x = 1, .y = 2 }];
int[][] grid = [[1, 2], [3, 4]];
int[] xs = []; is an empty list. null is also an empty list. Lists of any type work, including structs, enums, other lists, maps, strings, closures and ref objects.
Slices: T[..]
A view of part of a list, a C array or another slice: a pointer to the first element, a length, and (for a list) a reference to the list, so the elements stay alive as long as the view does. Taking a slice copies nothing.
int[] xs = [1, 2, 3, 4, 5];
int[..] mid = xs[1..4]; // [2, 3, 4]
mid[0] = 20; // writes through: xs is [1, 20, 3, 4, 5]
int buf[64];
int[..] head = buf[0..n]; // a view of a C array
string s = "hello"[1..3]; // "el": a string slice is a string
| Range | Elements |
|---|---|
a[i..j] |
i up to, not including, j |
a[i..=j] |
i through j |
a[i..] |
i to the end |
a[..j], a[..=j] |
the start up to j (or through j) |
a[..] |
all of it |
- Bounds are integers, evaluated once. A range outside the value, or one that ends before it starts, panics with the range and its location:
panic: slice 1..4 out of range for list of length 3.s[i]on a slice is bounds-checked like a list. - Lists, C arrays and slices (and list literals) are all accepted where a
T[..]is expected, so one function serves all three:long sum(int[..] xs)takessum(xs),sum(buf),sum(xs[2..])andsum([1, 2]). Generic functions work the same way:T first<T>(T[..] xs)infersTfrom any of them. - Writes through a slice of a list reach that list. Slicing a list variable (or field, or element) makes its storage unique first, the same copy-on-write step as
xs[0] = 1, so a write through the view never shows up in another list that shared the storage. While a slice views a list, a copy of the list (int[] ys = xs;, passing it to a function that keeps it) gets storage of its own. - Changing the list itself while a slice views it (
xs[0] = 1,xs.push(x)) gives the list new storage; the slice keeps viewing the old elements. Reassigning the list variable does the same: the slice keeps the old list alive. - A
T[]parameter is the caller's value, so slicing it inside the function copies the list first (writes through that slice stay in the function). Declare the parameterT[..]to view the caller's elements without a copy. Slices that are only read (printed, compared, iterated, or asked forlen,containsand the like) never copy. - A view of a C array holds no reference and follows C lifetime rules: don't keep it after the array goes away. A C array's slice is checked against its declared length; an array of unknown length needs an explicit end (
a[0..n]) and is checked only against that. - Strings are immutable, so
s[i..j]on a string is a newstringrather than a view. ==and!=compare elements, also against a list or C array of the same element type (mid == [2, 3, 4]).printand interpolation show a slice like a list.- A slice can't be used as a condition and can't be assigned to as a whole (
xs[1..3] = ysis an error); assign its elements.
Maps: map[K, V]
Hash maps that remember insertion order, with value semantics. Keys can be any type with equality: numbers, chars, bools, strings, enums, or structs of those.
map[string, int] ages = {"ada": 36, "grace": 45};
ages["linus"] = 21; // insert or replace
int a = ages["ada"]; // panics if the key is missing
int z = ages.get_or("zed", 0); // default instead of panic
if (ages.has("grace")) { ... }
Optionals: T?
A T or null. int?, Node?, string[]?, Pair<int, string>?. A T? can't be used as a T until the compiler knows it isn't null. See Optionals.
Result<T, E>
A success value of type T or an error of type E; Result<T> is Result<T, string>, an error message. See Errors and Result.
Future<T>
The handle of an async function's call, which runs on the calling thread, of a Future<T> function's call or a spawn block, which run as tasks on the thread pool, or of a call to an actor. await gives its T. See Concurrency.
Channels: chan<T>
A queue that passes values between tasks: chan<T>(n) holds up to n values, chan<T>() hands each value directly from sender to receiver. Copies of a channel share it; a declared but unassigned chan<T> is null. See Channels.
Closures: fn(A, B) -> R
A callable value that may carry captured variables. fn(int) with no arrow returns void. See Closures.
Structs
Moxy defines a typedef for every struct you define, so struct Point { ... } can be used as Point. A trailing ; after the closing brace is optional when the brace ends the line.
struct Point { double x; double y; }
typedef struct {
string name;
int[] scores; // managed fields are fine
map[string, string] tags;
} Player;
Structs are values. Assigning a struct copies it, and managed fields inside are retained, so the copy is independent.
ref struct
A shared, reference-counted object.
ref struct Node {
string name;
Node[] children;
weak Node? parent; // does not keep the parent alive
}
Node root = Node{ .name = "root" };
Node same = root; // same object
same.name = "renamed"; // root.name is "renamed" too
Use . to access fields (Moxy dereferences automatically). == compares identity. A Node is never meant to be null; a variable or field that can be null is a Node? (see Optionals). For the 0.4 release, storing null in a non-optional ref struct, or leaving one unset, is a warning rather than an error.
Fields that hold a ref struct take one of three qualifiers:
| Field | Keeps the object alive | Reading it after the object is gone |
|---|---|---|
Node next; (strong, the default) |
yes | can't happen |
weak Node? parent; |
no | the field reads as Node?, null once the object is gone (with or without the ?) |
unowned Node owner; |
no | debug builds panic with the location; release builds read freed memory |
strong Node next; |
yes | can't happen; the same as no qualifier, but the cycle check leaves the field alone |
unowned is for a back-pointer whose object is known to outlive the holder, such as a card that points at the account holding it. It is only allowed in a ref struct.
The compiler warns when ref struct types can hold each other in a loop of strong fields (strong reference cycle: Child.owner -> Parent.kids -> Child), and debug builds list the objects still alive when main returns. Both are described in the memory chapter.
A plain ref struct stays on the thread that uses it. One that tasks share is declared shared ref struct, and its fields are written inside lock (x) { ... }. See Sharing between threads.
Enums
A Moxy enum has no = values and no trailing ;. Variants can carry data:
enum Color { Red, Green, Blue }
enum Shape {
Circle(double radius),
Rect(double w, double h),
Label(string text),
Empty
}
Color c = Color::Red;
Shape s = Shape::Rect(2.0, 3.0);
An enum with an = value or a trailing ; is a plain C enum, and its constants are global: enum Mode { READ = 1, WRITE = 2 };.
A Moxy enum's variants are named through the enum (Color::Red). Naming one bare (Red), which 0.3 allowed for enums without payloads, is warning W0209 in 0.4 and an error from 0.5.
Type inference with auto
auto x = expression; gives x the expression's type, as in C23: auto names = ["a", "b"]; declares a string[].
Declarations
Variables
C declarations, including several declarators per line and fixed arrays. A managed local or an optional without an initializer starts empty (null). A non-optional ref struct without one is null too, which is a warning (see Optionals).
Global variables can have any initializer. Initializers that aren't C constants run once at startup, before main.
Functions
C function syntax. Functions can be used before they're defined, so no forward declarations are needed (but they're allowed). Parameters are passed by value: a list parameter is the caller's list, and modifying it inside the function modifies a copy.
main
void main() { ... } // exits 0
int main() { return 3; } // exit code 3
void main(string[] args) { ... } // args[0] is the program
int main(int argc, char **argv) { ... } // classic C
Namespaces
namespace geo {
struct Point { double x; double y; }
double dist2(Point a, Point b) { ... }
namespace shapes { ... }
}
geo::Point p = geo::Point{ .x = 1.0, .y = 2.0 };
using geo; // bring geo's names into scope
Point q = Point{ .x = 0.0, .y = 0.0 };
In generated C, namespaced names become geo__Point and geo__dist2.
using geo; makes geo's names visible as if they were declared where the using is. If one of them shares its name with a name declared there, or with a name another using brings in, naming it after the using is an error that lists the candidates (E0331); write geo::Point to say which. Code before the using, such as a library included ahead of it, keeps its own names, and so does the standard library wherever it is included; a static function or global in another file is never a candidate.
Generics
Structs, ref structs, Moxy enums and functions can take type parameters, written in <...> after the name:
struct Pair<A, B> { A first; B second; }
enum Option<T> { Some(T value), None }
ref struct Tree<T> { T value; Tree<T> left; Tree<T> right; }
T first<T>(T[] xs) { return xs[0]; }
Pair<B, A> swap<A, B>(Pair<A, B> p) { return Pair<B, A>{ .first = p.second, .second = p.first }; }
Generic declarations go at the top level or directly inside a namespace, on their own (not inside a typedef or a function body). Unions can't be generic.
Type arguments
Write the arguments after the name, or leave them out where Moxy can work them out:
Pair<int, string> p = Pair<int, string>{ .first = 1, .second = "a" };
auto q = Pair{ .first = 1, .second = "a" }; // from the field values
Pair<long, string> r = { 2, "b" }; // from the declared type
Option<int> none = Option::None; // from the declared type
auto some = Option::Some("x"); // from the payload
auto other = Option<long>::None; // written out
int x = first([1, 2, 3]); // from the arguments
long y = first<long>(longs); // written out
int z = make(); // from the expected type, for T make<T>()
fn(int) -> int f = id<int>; // one instance as a function value
Inference looks at the arguments first, then at the type the result is assigned to, then at lambdas and other values that need a type from context ((x) => ..., {...}, [], null, Enum::Variant). When two arguments give a type parameter different number types, the wider one wins (int and double give double); any other disagreement is an error. A type parameter nothing determines is an error that names it:
error[E0639]: cannot infer type parameter T of make
= help: name the type at the call, as in make<int>(...)
Instances are ordinary types: Pair<int, string>[] is a list of them, they can be fields, map values and enum payloads, they print as Pair<int, string> { first: 1, second: "a" }, and match works on generic enums the same way as on others (Some(v) => or Option::Some(v) =>).
Where < starts a type-argument list
< after a name opens type arguments only when the program declares that name as a generic struct, enum or function (in any file it includes). Everywhere else it is C's less-than, so a < b keeps meaning what it means in C. In an expression the list must also be followed by (, { or :: (or, after a generic function's name, by ;, ,, ), ] or }), and a closing >> closes two lists. Writing type arguments after a name that isn't generic is an error: 'Point' is not generic; it takes no type arguments.
Type parameters inside a generic
A generic body is checked once, where it is written, with each type parameter standing for an unknown type. Without a bound, a type parameter's values can be copied, assigned, passed, returned, stored in lists, maps, structs and enums, printed and interpolated, and nothing else: a + b, a == b, if (a), casts and field access are errors in the body, whatever the instances would be.
T add<T>(T a, T b) { return a + b; }
// error: '+' is not defined between T and T
A bound names interfaces after a colon: <T: Ord>, <K: Hash + Eq>, <T: Into<string>>, <T: geo::Sized>. Inside the body a bounded parameter has the methods its bounds declare, == and != with Eq, <, <=, > and >= with Ord, + - * / % and unary - with Num, and .sort() on a T[] with Ord.
Num is implemented by every integer and floating-point type (char through unsigned long long, float, double, long double and the fixed-width names), and by nothing else; it has no methods. With T: Num, both operands of an arithmetic operator are T (or one is an integer literal, which C converts), an integer literal initializes a T (T total = 0;), and casts between T and number types are allowed. Comparisons still need Ord. Each instance is ordinary C arithmetic on its type, checked for overflow like any other:
T sum<T: Num>(T[] xs) {
T total = 0;
for x in xs { total += x; }
return total;
}
T clamp<T: Num + Ord>(T x, T lo, T hi) { return x < lo ? lo : x > hi ? hi : x; }
Every instantiation is checked against the bounds, and an argument that doesn't implement one is an error at the use, naming the type, the interface and the bound:
T bigger<T: Ord>(T a, T b) { return a > b ? a : b; }
bigger(1, 2); // fine: int implements Ord
bigger(p, p); // error: P does not implement Ord
// note: required by the bound T: Ord on bigger
// help: implement it: impl Ord for P { ... }
Bounds on generic structs and enums (struct Sorted<T: Ord>) are checked the same way when an instance is named. See Methods and interfaces for which types implement which interfaces.
A name in a generic declaration that looks like a type parameter (U, K2) but isn't declared is an error, unknown type parameter 'U', instead of being taken for a C type.
What it compiles to
Each distinct set of type arguments gets its own C struct, enum or function, named after the generic and its arguments: Pair<int, string> is struct Pair__int__string, first<long> is first__long, and Option<char *> is Option__pchar (pointers spell p, const spells c, lists list_, namespaces prefix as usual: geo__Vec__double). Instances are made once per program, however many files use them, and only for the arguments actually used. Instance functions are static. Generic declarations can't be repeated under different #if conditions yet.
Lists, maps and slices follow the same rule. Each element type used gets its own static functions for the operations the program performs: xs.push(p) on a Point[] calls mxy_list_push__Point, xs[i] calls mxy_list_at__Point, and counts[w] on a map[string, int] calls mxy_map_get__str__int. Inside them, copying, dropping, comparing and hashing an element are direct calls (or a plain assignment, for elements that hold nothing to release), and an element's address is computed with sizeof. Only the operations a program uses are written. Sorting, printing, insert, remove, slice, +, keys() and values() are shared by every element type and reach the element's operations through its value witness, as does copying a map that is shared. Result<T, E> is a plain C struct per instance (mxy_res_int). A Future<T> keeps its result's witness, since the pool that runs the task doesn't know T.
Methods and interfaces
Methods
An impl block adds methods to a type. Inside a method, self is the receiver: for a value type it is a pointer to the caller's value (Point *self), read and written with .; for a ref struct it is the reference. static methods have no self and are called through the type.
struct Point { double x; double y; }
impl Point {
double len() { return sqrt(self.x * self.x + self.y * self.y); }
void scale(double k) { self.x *= k; self.y *= k; }
static Point at(double x, double y) { return Point{ .x = x, .y = y }; }
}
Point p = Point::at(3, 4);
p.scale(2); // changes p
print(p.len()); // 10.0
Point *pp = &p;
pp.scale(0.5); // also through a pointer to the type
fn(double, double) -> Point make = Point::at;
- Methods work on structs,
ref structs, Moxy enums, generic instances, built-in types (impl string,impl int[]) and C types (impl FILE). Inside a method on a built-in type,self.len()and other built-in methods read throughself; elsewhere write*self. - A method can change a value receiver: calling it on a variable, field or list element changes that variable, field or element. Calling it on a temporary (
Point::at(1, 2).len()) works on a copy. .on a pointer reads a field only throughself; other pointers still use->.Selfnames the implementing type inside animplorinterfaceblock:static Self empty() { return Self{ .items = [] }; }.- A user method takes priority over a built-in method of the same name on that type.
- A type has one method of each name across all its
implblocks, inherent or for interfaces. Two interfaces that both declarename()can't both be implemented for one type. selfis implicit: declaring it as a parameter is an error, as are assigning to it, using it in a static method, calling a static method on a value (p.at(1, 2)) and calling a method that takesselfthrough the type (Point::len()).- Methods can't have their own type parameters yet.
Generic impls
impl<T> adds methods to every instance of a generic type that matches its target. Bounds on the impl's parameters limit which instances get the methods.
struct Pair<A, B> { A first; B second; }
impl<T: Eq> Pair<T, T> {
bool same() { return self.first == self.second; }
Pair<T, T> swapped() { return Pair<T, T>{ .first = self.second, .second = self.first }; }
}
impl Pair<string, int> {
string show() { return "\(self.first):\(self.second)"; }
}
Pair<int, int> p = Pair<int, int>{ 2, 5 };
print(p.same()); // false
Every type parameter of the impl must appear in its target. A method of a generic impl is instantiated, like a generic function, for each set of arguments it is used with. Calling a method whose impl exists but whose bounds the type doesn't meet is an error that points at that impl.
Interfaces
An interface lists methods a type can provide. A method with a body is a default that an impl may replace; one without is required.
interface Shape {
double area();
string name();
string describe() { return "\(self.name()) of area \(self.area())"; }
}
impl Shape for Point {
double area() { return 0; }
string name() { return "point"; }
}
double total<T: Shape>(T[] xs) {
double t = 0;
for x in xs { t += x.area(); }
return t;
}
- An impl must provide every required method with the declared signature (
Selfand the interface's type arguments filled in), and nothing that isn't in the interface. - Interfaces can take type parameters:
interface Into<U> { U into(); }. A type can implement the same interface once per set of arguments (impl Into<string> for Vandimpl Into<int> for V); a call is then chosen by the type the result is assigned to (string s = v.into();), or, inside a generic, by the parameter's bound. - Interface methods can't be
static. Interfaces live in namespaces like other names (impl geo::Sized for Circle). - A bounded generic calls the concrete method directly: interfaces cost nothing at run time unless you ask for
dyn.
Standard interfaces
| Interface | Method | Used by |
|---|---|---|
Eq |
bool eq(Self other) |
==, !=, map keys, contains, index_of |
Ord |
int cmp(Self other) (negative, zero, positive) |
<, <=, >, >=, sort() |
Hash |
uint64_t hash() |
map keys |
Format |
void format(Buf *b) |
print, interpolation, string(x), nested values |
Into<U> |
U into() |
explicit conversions, and error conversion by ? |
Drop |
void drop() |
runs when a ref struct object is released, before its fields |
Num |
none | + - * / % and unary - on a type parameter; only the number types implement it |
Built-in types implement Eq, Hash and Format (numbers, string, pointers, lists of Eq elements, Results and optionals of such types, and Eq for maps), and numbers, string and pointers implement Ord. Structs and enums implement Eq, Hash and Format structurally when every field or payload does, with no impl needed. A ref struct compares and hashes by identity. The standard methods can be called directly: (3).cmp(5), "a".hash(), p.eq(q).
An impl replaces the structural version:
struct Version { int major; int minor; string tag; }
impl Eq for Version {
bool eq(Version o) { return self.major == o.major && self.minor == o.minor; }
}
impl Hash for Version {
uint64_t hash() { return (uint64_t)(self.major * 100 + self.minor); }
}
impl Ord for Version {
int cmp(Version o) { return self.major != o.major ? self.major - o.major : self.minor - o.minor; }
}
impl Format for Version {
void format(Buf *b) { b.put("v\(self.major).\(self.minor)"); }
}
Buf is the output buffer inside format(); b.put(x) appends any value as print would. Eq, Ord, Hash and Format can be implemented only for Moxy structs, ref structs and enums, and Drop only for ref structs; built-in types keep their own. == on a ref struct that implements Eq is true for the same object or for two objects whose eq() says so, and comparing with null compares the reference.
Drop. drop() runs when a ref struct object is released, once, when its last reference goes, before its managed fields are released. It can't be called directly. Implementing Drop for a value type (a struct or an enum) is an error: values are copied by assignment, by lists and maps, and by parameters a function changes, and how many copies exist is up to the compiler, so a drop() there would run an unpredictable number of times. A resource that must be released once belongs in a ref struct, which can hold value types, including enums, in its fields.
dyn
dyn Iface is the only dynamic dispatch. A value becomes dyn where a dyn type is expected (a declaration, an argument, a return, a list element), and its type must implement the interface.
dyn Shape s = Point{ .x = 1, .y = 2 };
dyn Shape[] all = [s, Circle{ .r = 1 }];
for x in all { print(x.describe()); }
dyn Shape erase<T: Shape>(T x) { return x; } // a bounded parameter converts too
- A
dynvalue is a pair of a reference-counted box and a pointer to a static vtable (mxy_vt_Shape), one per interface and type. A value type is boxed as a copy; aref structis retained, so changes to the object show through. - Copying a
dynshares its box. Printing one formats the value inside. dynvalues have no==or<. Adynlocal declared without a value prints asnull, and calling a method on it panics with a location.- An interface can be used with
dynonly when it has no type parameters and none of its methods take or returnSelf.dyn Dropis an error.
What it compiles to
A method is a plain C function named after its type: p.len() is Point_len(&p), a method on a ref struct takes the reference (Counter_bump(c)), a namespaced type prefixes as usual (geo__V_get), built-in types spell as in generics (string_shout, list_int_total), and a method of a generic impl instance carries the arguments (Pair_same__int). An interface method's C name includes the interface's arguments when it has them (Version_into__string). A dyn call is a call through the vtable: vt->area(data).
Compile-time reflection
static for walks a type's fields or an enum's variants while the program is compiled, and static if picks code by a condition known at compile time. Together they let one generic function work over every field of whatever struct it is given:
string to_json<T>(T v) {
string out = "{";
static for f in T.fields {
static if (f.index > 0) { out += ","; }
out += "\"\(f.name)\":";
static if (f.type == int) {
out += "\(v.[f])";
} else static if (f.type == string) {
out += "\"\(v.[f])\"";
} else {
out += to_json(v.[f]);
}
}
return out + "}";
}
Nothing exists at run time: there are no type objects or field tables, only the code each copy of the loop body produces.
What a type exposes
| Expression | Meaning |
|---|---|
T.name |
the type's display name as a string literal: Point, Pair<int, string> |
T.fields |
the fields of a struct or ref struct, in declaration order |
T.variants |
the variants of a Moxy enum, in declaration order |
c.fields |
the payload fields of variant c |
xs.len |
the number of items in any of these lists, an integer constant |
f.name, c.name |
the field's or variant's name, a string literal |
f.index, c.index |
its position, an integer constant starting at 0 |
f.type |
the field's type, usable anywhere a type goes |
T.is_struct, T.is_enum, T.is_simple |
0 or 1: a struct or ref struct, a Moxy enum, an enum with no payloads |
T.is_list, T.is_map, T.is_optional |
0 or 1: U[], map[K, V], U? |
T.is_bool, T.is_int, T.is_unsigned, T.is_float |
0 or 1: bool, an integer type (char and bool excluded; i8 to u64, isize, usize included), an unsigned one, float or double |
T.elem |
the element type of a list, slice or optional, usable as a type: T.elem x = ...; json_of<T.elem>(...) |
T.key, T.value |
a map's key and value types, likewise |
T is a type parameter or a named type (Point.fields, Pair<int, string>.fields). The is_ properties are what lets one generic body choose a path per kind of type (static if (T.is_list) { ... } else static if (T.is_struct) { ... }), since .fields is an error on anything but a struct. T.elem, T.key and T.value need T to be a type parameter, and are errors on a type that has no such part. .fields on an enum, a union, a type with no visible definition or a builtin type is an error, as is .variants on anything but a Moxy enum. Asking for any other property (Point.size, f.offset) is an error that lists the ones that exist. A type keyword can't be written before the dot (int.fields doesn't parse); reach it through a type parameter instead.
static for
static for f in T.fields { ... }
static for c in Shape.variants { static for f in c.fields { ... } }
The body is copied once per item, each copy in its own block, with the loop variable standing for that item. In a generic function this happens per instantiation, like the rest of the body. The source must be T.fields, T.variants or a variant's .fields; a run-time value such as a list is an error that points at a plain for. static for works anywhere a statement does, including inside lambdas.
When a copy of the body has an error, Moxy reports it once with a note naming the item (note: in static for, with f = x) and skips the remaining copies.
Reading and writing fields: v.[f]
v.[f] is the field of v that f names, and p->[f] the same through a pointer. It is an lvalue, so it can be assigned, incremented or have its address taken:
void reset<T>(T *p) {
static for f in T.fields { p->[f] = (f.type)0; }
}
T scaled<T>(T v, int k) {
T out = v;
static for f in T.fields {
f.type tmp = v.[f];
out.[f] = tmp * (f.type)k;
}
return out;
}
f must be the variable of an enclosing static for over fields; using any other name is an error. A variant's payload has no lvalue form: read it with match.
static if
static if (cond) statement [else statement]
The condition is evaluated at compile time. It may use integer constants, f.index, c.index and .len, arithmetic and comparisons on them, type comparisons (f.type == int, T == string, T != char *), and &&, || and !. Anything that is only known at run time, including sizeof, is an error. T: Iface asks whether T implements an interface, by the same rules as a bound: an impl, a built-in implementation, or structural Eq, Hash and Format (see Standard interfaces). A generic interface takes its arguments (T: Into<string>), and the type can be a named one (Square: Shape). An unknown name, or a type where an interface belongs, is an error at the generic.
static if (T: Format) { out += "\(v)"; } else { out += "?"; }
Only the branch taken is type-checked. The other one is parsed but may use operations the type doesn't support, which is what lets a single body handle fields of different types:
static if (f.type == int) { sum += v.[f]; }
else { sum += v.[f].len; } // never checked for int fields
else static if chains the way else if does.
Expressions
Operators
Precedence, highest first:
| Level | Operators | Associativity |
|---|---|---|
| postfix | f(x) a[i] a[i..j] a.b a->b a?.b x++ x-- x! x? |
left |
| unary | - + ! ~ * & ++x --x sizeof _Alignof (T)x await |
right |
| multiplicative | * / % |
left |
| additive | + - |
left |
| shift | << >> |
left |
| relational | < <= > >= |
left |
| equality | == != |
left |
| bitwise | &, then ^, then | |
left |
| logical | &&, then || |
left |
| pipe | |> |
left |
| null coalescing | a ?? b |
right |
| conditional | c ? a : b |
right |
| assignment | = += -= *= /= %= &= |= ^= <<= >>= |
right |
| comma | , |
left |
Moxy-specific meanings:
string + stringconcatenates;s += tappends.list + listconcatenates;xs += ysappends.a[i..j],a[i..=j],a[i..],a[..j]anda[..]slice lists, C arrays, slices and strings (see Slices).==and!=compare lists, maps,Results, enums and structs by value, througheq()when the type implementsEq(see Standard interfaces). Onref structs they compare identity unless the type implementsEq.<,<=,>and>=on a struct or enum call itscmp()when it implementsOrd.a |> f(b)meansf(a, b), anda |> fmeansf(a).x!,x?,a?.banda ?? bare described under Optionals and Errors and Result. A?right after an operand is postfix unless an expression and then its own:follow, so C'sc ? a : bkeeps its meaning;!right after an operand (not at the start of a line) is always postfix, since C has no binary!.
Literals for composite values
Point p = Point{ .x = 1, .y = 2 }; // struct literal
Point q = (Point){ 1, 2 }; // C compound literal
Point r = { .y = 5 }; // initializer, other fields zero
int[] xs = [1, 2, 3]; // list literal
map[string, int] m = {"a": 1, "b": 2}; // map literal
Shape s = Shape::Circle(1.5); // enum variant
Lambdas
(int x) => x * 2
(string s, int n) => s.repeat(n)
() => print("hi")
(int x) => {
int y = x + 1;
return y * y;
}
The return type is inferred from the body.
Statements
Everything in C works: blocks, if/else (with or without braces), while, do/while, for (;;), switch/case/default (including GNU case 1 ... 5:), break, continue, return, goto and labels.
A trailing ; after an expression statement is optional when the next token begins a new line or is }.
for-in
for i in 0..10 { } // 0 through 9
for i in 1..=10 { } // 1 through 10
for x in xs { } // list elements
for i, x in xs { } // index and element
for k in m { } // map keys
for k, v in m { } // keys and values, in insertion order
for c in "text" { } // chars
for i, c in "text" { }
for v in fixed_array { } // C arrays with a known length
for x in xs[1..] { } // slices
for x in make_list() { } // any expression
Range bounds are evaluated once. A collection is held for the duration of the loop, so modifying it in the body changes a copy and doesn't disturb the iteration.
defer
defer statement; runs statement when the enclosing block ends, including through return, break and continue. Several defers run in reverse order.
FILE *f = fopen(path, "r");
if (!f) { return Err("cannot open"); }
defer fclose(f);
Pattern matching
match branches on enums, Results, optionals, structs, integers, chars, strings and bools:
match shape {
Shape::Circle(r) => print("circle", r),
Shape::Rect(w, h) => {
print("rect", w, h);
}
Label(text) => print(text), // the enum name may be left off
_ => print("something else"),
}
match code {
0 => print("ok"),
1 => print("warning"),
_ => print("error"),
}
- An arm's body is a statement or a block, followed by
,or a newline. breakandcontinueinside an arm apply to the enclosing loop.- Arms are tried in order; the first that matches runs.
Patterns
| Pattern | Matches |
|---|---|
_ |
anything |
name |
anything, and binds it to name |
0, -1, 'a', "text", true, MAX |
a value equal to the literal or constant |
Shape::Circle(p), Circle(p) |
that variant, with its values matching p, ... by position |
Some(p), None |
an optional with a value matching p, or without one |
Ok(p), Err(p) |
a Result |
Point{ .x = p, .y = q } |
a struct or ref struct whose named fields match; fields left out match anything |
p1 | p2 |
either pattern |
Patterns nest, so payloads and fields can hold any pattern:
match lookup(key) {
Some(Ok(0)) => print("zero"),
Some(Ok(n)) => print("found", n),
Some(Err(e)) => print("failed:", e),
None => print("missing"),
}
match event {
Event::Click(Point{ .x = 0, .y = _ }) => print("left edge"),
Event::Click(Point{ .x = x, .y = y }) => print("click", x, y),
Event::Key('q') | Event::Key('Q') => quit(),
Event::Key(c) => print("key", c),
}
A bare name is a constructor of the matched type when it has one by that name (a variant, Some, None, Ok, Err); otherwise a name starting with a lowercase letter or _ binds, and any other name is a constant compared by value. So Red and MAX compare, while n binds. To compare against a lowercase variable, use a guard: x if x == limit =>.
A struct pattern names the struct's type, Point{ ... } or geo::Point{ ... }; it cannot read weak or atomic fields, or the fields of a shared ref struct.
Alternatives
p1 | p2 => matches either. Every alternative binds the same names, at the same types; the binding takes its value from whichever alternative matched:
match shape {
Circle(size) | Square(size) => print("size", size),
Rect(w, h) => print(w, h),
Empty => {},
}
Inside a pattern, | separates alternatives, so 1 | 2 => matches 1 or 2. Parenthesize to use C's bitwise or as a value: (FLAG_A | FLAG_B) =>. Arm bodies are ordinary C, where | keeps its meaning.
Guards
pattern if cond => runs the arm only when cond holds. The guard sees the pattern's bindings; when it fails, matching continues with the next arm:
match n {
0 => print("zero"),
x if x > 0 => print("positive"),
_ => print("negative"),
}
Exhaustiveness
Matching an enum, Result, optional, bool or struct must cover every value, or include _ =>; anything else (numbers, chars, strings) must include _ =>. A missing case is a compile error that names it (missing Some(Err(_))). A guarded arm never counts as covering its pattern, since its guard may fail.
An arm that can never run, because earlier unguarded arms already match everything it would, is a warning (W0208), and no code is generated for it. An alternative that earlier patterns already cover is a compile error.
Optionals
T? holds a T or null, for any Moxy type: int?, string?, Point?, Node?, int[]?, T? inside a generic. fn?(A) -> R is an optional closure (fn(A) -> R? is a closure that returns an optional).
ref struct Node { string name; Node? parent; Node[] children; }
Node? find(Node root, string name) { ... return null; }
Node? n = find(root, "x");
if (n != null) { print(n.name); } // n is a Node inside this branch
string label = n?.name ?? "none";
match n { Some(v) => print(v.name), None => print("missing") }
Node m = n!; // panics with a location if null
- A value converts to its optional where one is expected (
int? x = 5;,return node;), and so doesnull. Where an optional is expected,NoneisnullandSome(v)isv(p = None;,return Some(x);,x == None); elsewhere an undeclaredNoneorSomeis left to C. Optionals of different number types convert like the numbers (i32?tolong?). - A
T?can't be used as aT:x + 1,x.name,x[0],x(1)andint y = x;on anint?are errors until the compiler has provedxisn't null. ==and!=compare an optional withnull, with another optional of the same type (two nulls are equal), or with a value.printshows the value ornull.- An optional
ref struct, closure or C pointer is a nullable pointer, with no extra storage. Any otherT?is a struct holding a flag and the value (mxy_opt_int, with fieldssomeandval).
Narrowing
A local variable or parameter of type T? reads as a T wherever the compiler can see it isn't null:
- inside
if (x != null)(andif (x)for aref struct, closure or pointer), and in itselseafterif (x == null); - after
if (x == null) return ...;, or anyifwhose null branch always leaves (return,break,continue,goto,panic(...),exit(...)); - on the right of
x != null && ...andx == null || ..., and in the matching arm ofx != null ? a : b; - in a
while (x != null)orfor (...; x != null; ...)body, and after a loop whose conditionx == nullfailed without abreak; - after storing a value that can't be null:
Node? n = make();,x = 5;; - at the end of an
if, a variable stays narrowed when every path that reaches the end narrowed it:if (x == null) { x = fallback(); }leavesxnon-null.
Narrowing ends at any assignment to the variable, except x += ..., x++ and the other compound forms on a narrowed x, which update its value in place and leave it narrowed (on an unchecked int? they are errors). Code that can run more than once or out of order (a loop body, a switch case, a match or select arm, the right side of && and ||, a label) starts without narrowing for every variable it assigns, so a second pass never relies on a stale check. A defer body runs when its block ends, after the statements that follow it, so it keeps the narrowing in effect where the defer is written only for variables that none of those statements assigns (and none at all in a block with a goto or a label):
Node? n = find(id);
if (n == null) return false;
defer n.busy = false; // fine: nothing below assigns n
n.busy = true;
If n were assigned after the defer, the body could see that value instead, so n.busy there is an error; check n inside the defer, or copy it to a non-optional local (Node live = n;) before it. Globals, fields and variables whose address is taken (&x) are never narrowed; copy a field into a local to check it.
?., ?? and !
a?.banda?.m(args)evaluate the access only whenaisn't null, and give its result as an optional (string?for astringfield). The arguments run only whenaisn't null. Avoidmethod call gives nothing.?.doesn't skip the rest of a chain:a?.b.creads.cof an optional and is an error; writea?.b?.c.a ?? bisa's value, orbwhenais null;bruns only then. Its type isT, orT?whenbis optional too:user?.address?.city ?? "nowhere".x!isx's value, and panics whenxis null:panic: unwrapped a null Node?with the location. It is the only run-time null check on optionals; everywhere else the compiler has checked. On a non-optionalref struct(which can still be null during 0.4)!checks too.x?inside a function that returns an optional returnsnullearly whenxis null, and isx's value otherwise; see Errors and Result for?on aResult.
Weak fields
Reading a weak field gives an optional, whether or not the field is declared with ?: a weak reference is null once its object is gone. Write n.parent!.name, n.parent?.name, or copy it to a local and check it. A local copy is a strong reference, so the object stays alive while it's in use:
Node? p = n.parent;
if (p != null) { print(p.name); }
A null check on the field itself doesn't narrow it: n.parent != null && n.parent.name == "x" reads the field twice, and a call in between (or the last other reference going away) can leave the second read null. Only a local is narrowed.
n.parent.name on a field declared weak Node (without ?) is warning W0207 in 0.4, so code from 0.3, where the read gave a Node, keeps compiling; the access is checked like n.parent!.name and panics with its location when the object is gone. It becomes an error in 0.5. On a field declared weak Node?, and on any other optional, it is error E0530.
Cycle collection
--cycles on moxy build, moxy run, moxy test and moxy emit, or cycles: true under build: in moxy.yaml, builds the program with a collector for ref struct cycles. Without it the program is compiled exactly as before. std/cycles.mxy has cycles::collect() (collect this thread's garbage cycles now; returns how many objects were freed) and cycles::enabled(); without the collector they return 0 and false. What it covers, the order it runs Drop in, and what it costs: Memory management.
Non-optional ref struct
A Node is never null. Fields of ref struct type that aren't optional must be set in the struct literal, and a Node variable needs a value. In the 0.4 release, a non-optional ref struct that may be null is a warning, not yet an error, reported at the declaration that should be optional, with a fix-it (also offered by the language server) that adds the ?:
warning[W0204]: 'next' may be null, but Node is not optional
--> list.mxy:1:30
= help: make it optional: Node? next
note: it is left null here
--> list.mxy:5:14
It is reported for Node n = null;, Node n;, a Node field a literal leaves out, return null; from a function returning Node, null passed for a Node parameter, and a Node? stored in a Node. From 0.5 these are errors.
C pointers stay C: T * is unchecked, as in C, so existing C code keeps compiling; a null C pointer dereference is reported by the fault handler with the location of the statement.
Errors and Result
A function that can fail returns Result<T, E>: an Ok(value) of type T, or an Err(error) of type E. Result<T> is Result<T, string>, an error message:
Result<int> parse_digit(char c) {
if (c < '0' || c > '9') { return Err("not a digit: \(c)"); }
return Ok(c - '0');
}
Result<void> save(string path, string data) {
if (!store(path, data)) { return Err("cannot write \(path)"); }
return Ok();
}
enum ParseError { Empty, BadDigit(char c, int at) }
Result<int, ParseError> parse(string s) {
if (s.len == 0) { return Err(ParseError::Empty); }
...
}
Using the result:
match parse_digit('7') {
Ok(n) => print(n),
Err(e) => print("error:", e), // e is the error type: string, ParseError, ...
}
int n = parse_digit('x').unwrap_or(0);
if (r.is_err()) { print(r.error()); }
int v = r.unwrap(); // panics with the error on Err
Ok(...) and Err(...) need a known Result type from their context: a return, an assignment, an argument, or a typed declaration.
?
Postfix ? on a Result returns the error early and otherwise gives the Ok value. It runs defers and releases what the function holds, as return does:
Result<Config> load(string path) { // Result<T> is Result<T, string>
string text = read_file(path)?; // returns early on Err
int port = parse(text)?; // ParseError becomes a string through Format
return Ok(Config{ .port = port });
}
In a function returning Result<U, F>, x? on a Result<T, E> returns Err(conv(e)), where conv is:
- nothing, when
EandFare the same type; e.into(), whenEimplementsInto<F>(impl Into<AppError> for ParseError { AppError into() { ... } });- formatting, when
FisstringandEimplementsFormat(every enum and struct of formattable fields does), soParseError::BadDigit('x', 1)becomes the message"ParseError::BadDigit('x', 1)".
On a Result, r?.field and r?.method() mean r? followed by .field: the error returns early.
Anything else is an error that names the missing conversion: '?' can't convert the error type Raw to Wrapped, which wrap() returns. ? in a function that doesn't return a Result (or, for an optional, an optional) is an error, and so is ? inside a defer.
A panic stops the program with a message and exit code 101. It happens on panic("message"), an out-of-range index or slice range, a missing map key, unwrap() of an Err, x! on a null optional, calling a null closure, or (in debug builds) reading an unowned field whose object is gone. A failed assert exits with code 1. It prints the condition as written and, when the condition is a comparison (==, !=, <, >, <=, >=), the value of each side formatted as print would:
assertion failed: x + 1 == 4 (left: 3, right: 4)
message: x should be 3
at main.mxy:7:5
Each side of the comparison is evaluated once, and the message (assert(cond, "message"), shown on the message: line) is evaluated only when the assertion fails. Other conditions, such as ready && n > 2, print without values.
A null or invalid memory access (a null ref struct, a bad C pointer) and a stack overflow are reported the same way, with exit code 101:
panic: null or invalid memory access (address 0x10)
at main.mxy:7:5
The at line names the statement that was running. Debug builds record it as each statement starts; --release builds skip that bookkeeping, so they report the fault without a line.
Built-ins and methods
Functions
| Built-in | Meaning |
|---|---|
print(a, b, ...) |
prints the values separated by spaces, then a newline |
assert(cond) / assert(cond, "message") |
if cond is false, prints it (with both sides of a comparison) and the message, then exits with code 1 |
panic("message") |
stops with the message |
string(value) |
formats any value as a string; copies a C char * |
print and interpolation format values as follows:
- integers in decimal;
- floats in the shortest form that reads back exactly (
0.1,3.0,10.0), with an exponent from1e16up and below1e-4(1e+20,1.5e-07); boolastrueorfalse, andcharas the character;- lists as
[1, 2], maps as{"a": 1}, structs asPoint { x: 1, y: 2 }, enums asShape::Circle(1.5),Results asOk(1)orErr("..."), and optionals as their value ornull; - values of unknown C types through C's
_Generic; - any type that implements
Formatthrough itsformat()method, wherever it appears (inside lists, maps, fields and payloads too).
string
| Method | Result |
|---|---|
s.len |
length in bytes (long) |
s.is_empty() |
bool |
s.contains(t), s.starts_with(t), s.ends_with(t) |
bool |
s.find(t) |
index or -1 |
s.slice(a, b) |
bytes [a, b) |
s.split(sep), s.lines() |
string[] |
s.trim(), s.upper(), s.lower() |
string |
s.replace(a, b), s.repeat(n) |
string |
s.chars() |
char[] |
s.at(i), s[i] |
char |
s.to_int() |
Result<long> |
s.to_float() |
Result<double> |
T[]
| Method | Result |
|---|---|
xs.len, xs.is_empty() |
long, bool |
xs.push(x), xs.insert(i, x) |
add elements |
xs.pop(), xs.remove(i) |
remove and return an element |
xs.clear(), xs.reverse(), xs.sort() |
modify in place; sort needs an element type that implements Ord |
xs.contains(x), xs.index_of(x) |
bool, index or -1 |
xs.first(), xs.last() |
element (panics if empty) |
xs.slice(a, b) |
T[] |
xs.join(sep) |
string of the formatted elements |
xs.map(f), xs.filter(f), xs.each(f) |
new list, new list, void |
T[..]
| Method | Result |
|---|---|
s.len, s.len(), s.is_empty() |
long, bool |
s.to_list() |
a new T[] holding copies of the elements |
s.contains(x), s.index_of(x) |
bool, index or -1; need T: Eq |
s.sort() |
sorts the viewed elements in place, so xs[2..].sort() sorts the end of xs; needs T: Ord |
map[K, V]
| Method | Result |
|---|---|
m.len, m.is_empty() |
long, bool |
m.set(k, v), m[k] = v |
insert or replace |
m.get(k), m[k] |
value (panics if missing) |
m.get_or(k, default) |
value or default; where a V? is expected, a null (or V?) default makes it a V?: Node? n = m.get_or(k, null); |
m.has(k) |
bool |
m.remove(k) |
bool: whether it was there |
m.keys(), m.values() |
lists, in insertion order |
m.clear() |
removes everything |
Result<T, E>
is_ok(), is_err(), unwrap(), unwrap_or(default), and error(), which gives the E (an empty string, or a zero E, on Ok). unwrap() of an Err panics with the error formatted as print would.
Closures
fn(int) -> int adder(int n) {
return (int x) => x + n; // captures n
}
fn(int) -> int add5 = adder(5);
print(add5(1)); // 6
int[] doubled = [1, 2, 3].map((int x) => x * 2);
- Captures are copies taken when the lambda is created. Assigning to a captured variable inside the lambda is an error. Pass the value as a parameter or keep a local copy instead.
- A named function can be used wherever a closure is expected.
- A C function pointer parameter (
int f(int)orint (*f)(int)) accepts named functions and lambdas that capture nothing. A capturing lambda needs afn(...)parameter. - Closures can be stored in variables, struct fields, lists and maps.
Concurrency
Moxy has three tools, one per job, and each call that runs later returns a Future<T> that await turns into a T:
- An
asyncfunction is for waiting: I/O, timers, channels, coordinating other work. It runs on the thread that calls it, takes turns with the other async calls there, and shares any value with its caller, as in JavaScript, TypeScript or Swift. - An
actoris for state that several tasks use: one value whose fields only its own methods touch, one message at a time, as with an Elixir GenServer or a GCD serial queue. Nothing needs a lock. - Parallel work is explicit:
parallel for,xs.par_map(f),spawn { ... }andFuture<T>functions run on a pool of worker threads, so what they are given must be safe to share between threads.
| You want to | Use |
|---|---|
| wait for I/O, timers or other work without blocking the thread | async functions |
| keep state (a cache, a connection table, a counter) that many tasks read and change | an actor |
| run a loop's iterations, or a list's elements, on every core | parallel for, par_map |
| run one computation in the background and collect it later | spawn { ... } or a Future<T> function |
| hand values from one task to another as they are made | a channel |
| share a structure with fine-grained locking | a shared ref struct |
Async functions
#include "std/time.mxy"
ref struct Page {
string url;
string[] lines;
}
async int fetch(Page p, long ms) {
p.lines.push("asked for \(p.url)");
sleep_ms(ms); // waits; other async calls run meanwhile
p.lines.push("got \(p.url)");
return p.lines.len();
}
Page p = Page{ .url = "/a", .lines = [] };
Future<int> a = fetch(p, 20); // runs until sleep_ms, then returns
Future<int> b = fetch(p, 10);
print(await a + await b); // 7: b finished with 3 lines, a with 4
async T name(params) { ... }declares one;async voidreturnsFuture<void>. Methods (async long deposit(long n)in animpl, on aref struct),staticmethods and lambdas (async (int x) => x * 2, afn(int) -> Future<int>) can be async too.asyncis a word only before a function's type or a lambda's(, so C code that usesasyncas a name still compiles.- Calling one runs its body at once, on the calling thread, until it first waits. Then the call returns its
Future, and the caller carries on. A body that never waits has finished when the call returns. - Everything an async call does happens on the thread that called it: it never runs at the same time as other code there. It switches only where it waits, so the code between two waits runs without interruption, and no lock is needed around a read and a write of a shared value. Being on one thread, an async call may be given, may capture and may return anything: plain
ref structs, slices, values the caller keeps using. Nothing is marked shared and nothing is checked. - What waits:
await,send,recv,for v in c,select,sleep_msandtime_sleep(std/time), and socket operations in std/net. A waiting async call parks, and its thread runs the next async call that is ready, in the order they became ready, or sleeps until one is. Socket and timer wakeups come from the same poller and timer threads that serve the pool. - An async call can await anything: another async call, a
Futurefunction's task (its finishing wakes the waiting thread), all of them throughall,raceandtimeout. - When code that isn't itself an async call waits, as
maindoes inawait a, its thread runs its async calls until what it waits for is done. A thread gets this machinery (its own stack becomes one of the stacks it switches between) at its first async call. - A
Futurefunction that calls an async function runs it on the worker thread it is on, and that async call stays on that worker, as the task's own waits do. - An async call's
Futurebelongs to the thread that made it. It can't be passed to aFuturefunction, returned from one, sent on a channel or stored in ashared ref struct: the compiler reports it where it can see that aFuturecomes from an async call (the call itself, or a variable it initialized), and the runtime panics as one crosses anywhere else (in aFuture<T>[], a closure), naming the crossing. Awaiting one on another thread, reached through a global, panics too. mainreturning ends the program, as with tasks. AFuturedropped without being awaited cancels its call (see Cancellation), so an async call made as a statement,save(doc);, runs up to its first wait and no further, unlike in JavaScript; the compiler warns about it. Keep theFutureand await it.- Each waiting async call keeps the stack it runs on: 8 MB of address space, of which only the pages it touched take memory (16 KB for a short body on arm64 macOS). 10,000 waiting async calls take about 170 MB there. When they are done, each thread keeps up to 16 spare stacks for reuse and gives the rest back: after such a burst the program is back to a few MB.
- Inside
lock (x) { ... }(or with astd/synclock held) an async call can't switch away: it runs to its end inside the call, its waits sleeping the thread, and anawaitthere on an async call that isn't finished panics, since nothing else on the thread could finish it. - Without fibers (targets other than x86_64 and arm64 on macOS, Linux and the BSDs, and Windows; builds with
-DMXY_NO_FIBERS) the same holds everywhere: an async call runs to its end inside the call, its waits sleep the thread, and itsFutureis done when the call returns, soawaitnever waits. The order of the program's output can differ from a build with fibers, and an async call that waits for something its caller does only after the call (a channelrecvthe caller latersends to) can't get it: it waits until its timeout, or forever without one.
Actors
actor Cache {
map[string, string] entries;
int misses;
void put(string k, string v) { self.entries[k] = v; } // a cast: c.put(...) returns at once
string? get(string k) { // a call: await c.get(k)
if (!self.entries.has(k)) {
self.misses += 1;
return null;
}
return self.entries[k];
}
int stats() { return self.misses; }
}
Cache c = Cache{ .entries = {} };
c.put("a", "1");
c.put("b", "2");
string? a = await c.get("a");
print(a ?? "none", await c.stats()); // 1 0
An actor is a reference type, declared like a ref struct with its methods inside the braces (an impl Name { ... } block may add more). It has a mailbox, and runs on the thread pool one message at a time.
Name{}orName{ .field = value }makes one, as with aref struct. There is no constructor; give fields their first values in the literal, or with a first message.- From outside the actor, a method call is a message. A
voidmethod is a cast: the call puts the message in the mailbox and returns at once. Any other method is a call: it returns aFuture<T>of the method's result, whichawaitwaits for (T x = await c.get(k);). - Messages are handled one at a time, in the order they arrived. The messages one sender sends arrive in the order it sent them, casts and calls alike; messages from different senders interleave in some order.
- Inside its methods,
selfis the actor itself: its fields are read and written directly, with no lock, andself.m()is a plain call, not a message. Nothing else runs on the actor's fields meanwhile. - A field can be read or written only by the actor's own methods:
c.missesanywhere else is a compile error (field 'misses' of actor Cache is reached only by its own methods), with a hint to add a method that returns it. The same holds inside a lambda in one of its methods, since the lambda may run on another thread later: call a method there instead. A pattern can't match on an actor's fields either. - What a message carries crosses threads, so its arguments and its result follow the crossing rules: values,
shared ref structs and actors may cross, plainref structs and slices can't. The values a literal gives the actor's fields cross too. An actor reference itself may go anywhere: into another actor's message, a task, a channel, ashared ref struct, a global. - The fields themselves may be of any type, plain
ref structs included: they never leave the actor except through a message's result, which is checked. A method called only onselfmay take and return anything. - A method of an actor can't be
asyncor return aFuture: called from outside, it returns one already. An actor can implementDrop, which runs when it is freed, but no other interface, whose methods would be called directly from any thread.Name::methodcan't be used as a function value. print(c)showsactor Cache;==compares identity, as with anyref struct.lock (c)is an error: an actor needs no lock.- Static methods are allowed and are plain functions.
Lifetime and cost
- An idle actor is its object and nothing else: no thread, no task. A 16-byte header, a 40-byte mailbox and the fields; a million idle actors with one
longfield took 74 bytes each on arm64 macOS, counting the list that held them. - An actor is scheduled onto the pool when its mailbox goes from empty to not empty, as one entry in a worker's queue. The worker that runs it handles messages until none are left, or until 64 of them, when it puts the actor behind the other queued work so a busy actor can't starve the rest.
- A message is one allocation (its
Future, its arguments and its result in one block), pushed onto the mailbox with one compare-and-swap. - An actor lives while anything references it or while it has messages to handle: dropping the last reference with casts still queued handles them, then runs
Dropand frees the fields. A message'sFutureholds its actor weakly, so a handle kept after the actor is gone keeps only its memory, not its fields. - Messages are never cancelled. Dropping a call's
Futuregives up its result; the message is still handled, since the actor may change its state in it. A call whose result is unused is not a warning. - Actor objects are counted with atomics from the start (any thread may send to them), and the cycle collector (
--cycles) never collects them; it does collect the plainref structcycles their methods make. A cycle of actors that reference each other strongly is a leak, as withref structs; make one sideweak.
Waiting inside a message
A method may await (or use a channel, a socket, sleep_ms). While it waits, its actor stays busy: the next message starts only after this one returns. So a method that changes the fields, waits, and changes them again is never seen half done by another message, and the rule "one message at a time" holds without exceptions. The worker thread isn't held: the waiting message parks with its stack, and the worker runs other actors and tasks meanwhile.
The price is that two actors that await each other can't both go on. When actor A's message awaits a call to B while B's running message awaits a call to A (or any longer cycle), the await that closes the cycle panics instead of waiting forever, naming every await in it:
panic: deadlock: actor Back awaits actor Front at app.mxy:20:16, and actor Front awaits actor Back at app.mxy:10:16
An actor awaiting a call to itself through a reference (Cache me = self; await me.get(k)) panics the same way; call self.get(k) instead. The panic fails that message like any other (below), which breaks the cycle. Cycles that pass through something other than actor calls (an actor awaiting a Future function that awaits the actor, a channel both sides wait on) are not detected and wait forever.
Crash isolation
A panic inside a message (a failed assert, an index out of range, x! on null, panic(...), a crossing check) fails that message, not the program:
actor Parser {
int parsed;
int parse(string s) {
int? n = number(s);
self.parsed += 1;
return n!; // panics on "x"
}
}
Parser p = Parser{};
Result<int> r = await p.parse("x").result();
print(r.is_err()); // true: r.error() is the panic and its place
print(await p.parse("12")); // 12: the actor goes on
int n = await p.parse("y"); // the panic again, raised here
The actor goes on with its next message. Its fields keep whatever the failed message left in them: there is no rollback.
A call's
Futurefails.awaiton it raises the panic again in the awaiter, with where it happened and where it was awaited:panic: unwrapped a null int? at app.mxy:5:16 in actor Parser's parse(), awaited at app.mxy:13:15If the awaiter is itself an actor's message, that message fails in turn, and so on up the chain.
f.result()gives aFuture<Result<T>>instead:Okwith the value, orErrwith the panic's text and place. It never raises the panic.int n = await p.parse(s).result()?;passes the failure on as an error.A cast's panic is printed to standard error once, with where the message was sent, and the program goes on:
panic: ... in actor Parser's parse() sent at app.mxy:20:7; the actor goes on with its next message. So is a call's, when itsFutureis dropped without being awaited.all,raceandtimeoutover a failed call fail the same way.The failed message is unwound with
longjmp:defers in the frames it leaves don't run, and what their variables held is never released. Memory a failed message allocated leaks, and C resources it opened stay open; debug builds' leak report says how many panics were caught. A gate opened inside the message is closed.A panic while the message holds a lock (
lock (x) { ... }, or astd/synclock) still ends the program: the lock can't be given back safely while another thread may be waiting on what it guards half-written. A note says so.A panic in a
Futurefunction's task or in an async call stays fatal, even when an actor's message started it. So does a memory fault (a C pointer gone wrong, a stack overflow): the program's state can't be trusted after one.Panics outside actors (in
main, a task, a thread started from C) end the program as before.
Supervisors and restart policies (start a fresh actor when one has failed too often) are for the standard library, later.
Parallel work: Future functions
A function that returns Future<T> runs as a task on the thread pool when called, and the call returns its handle at once. await waits for the task and returns its result.
Future<long> sum_to(long n) {
long total = 0;
for i in 0..n { total += i; }
return total;
}
Future<long> a = sum_to(1000000);
Future<long> b = sum_to(2000000);
print(await a + await b);
- Tasks run on a pool of worker threads, one per CPU.
MOXY_THREADS=nin the environment sets the count; it is read when the first task starts, which is also when the pool's threads start. A program that never calls aFuturefunction starts no threads. - Each worker keeps its own queue of the tasks it started and takes the newest; idle workers steal the oldest from the others. Tasks started outside the pool (from
main) go to a shared queue. awaiton a task no thread has picked up yet runs it right there, on the awaiting thread. On a task that's running elsewhere, the awaiting task parks and its worker goes on with other tasks; outside the pool (inmain) the thread sleeps, or runs its async calls if it has made any. Futures that await futures, nested deeper than the pool is wide, can't deadlock the pool.- A task that waits (
await,send,recv,select,sleep_ms, and socket operations in std/net) doesn't hold its worker thread: the task keeps the stack it is running on, and the worker carries on with other tasks on another stack until the task is woken, then resumes it. A program with thousands of waiting tasks keeps one thread per worker. Each extra stack reserves 8 MB of address space and only takes memory as it grows; a worker keeps up to 16 spare stacks for reuse and returns the rest to the system. A parked task resumes on the worker it parked on. This needs x86_64 or arm64 (macOS, Linux, the BSDs) or any Windows target; elsewhere, and in builds with-DMXY_NO_FIBERS, a waiting task sleeps its thread and the pool starts another worker in its place until it wakes. - Arguments are copied into the task when it's created.
- What may be passed to a task, returned from one or sent on a channel is checked at compile time: see Sharing between threads.
- The program exits when
mainreturns, whether or not tasks are still running. - Programs that use futures, async functions or channels link with
-lpthreadautomatically. On Windows they use Win32 threads, SRW locks and condition variables instead; MinGW gcc builds of them are linked with-staticso the program doesn't needlibwinpthread-1.dll.
Parallel loops and spawn
long[] steps = [];
for i in 0..n { steps.push(0); }
parallel for i in 0..n {
steps[i] = collatz(i); // each index written by its own iteration
}
int[] squares = xs.par_map((int x) => x * x); // in order
Future<long> total = spawn { return sum(big); }; // a block on the pool
print(await total);
parallel for i in a..b { body }(ora..=b) runs the body once for eachi, spread over the pool's workers in chunks, about 32 per worker; idle workers take the next chunk, so uneven iterations balance, and a stop (a panic, a cancel) waits for at most one chunk per worker. The statement ends when every iteration has. The loop variable has the range's type, as in a plainfor.- The body may read anything it captures, which crosses threads under the crossing rules (no plain
ref struct, no slice, no async call'sFuture). It can't assign a variable from outside (sum += xis an error with a hint), write a global,returnorbreak(continueends the iteration). - One write reaches outside:
out[i] = value, whereoutis a list declared before the loop andiis the loop variable itself. Each index belongs to one iteration, so no two threads ever write the same element. The list is made unique (copied, if shared) before the loop and written in place, so the writes land in the caller's variable. The list must already be long enough (an index out of range panics, below); the body can't otherwise use that list, since readingout[j]could see another iteration's write half done. xs.par_map(f)callsfon every element of the listxs, on the pool, and returns a new list of the results, in order. The elements and the results cross threads.- When the whole loop would take less than about 50 microseconds, it runs on the calling thread alone: the first chunk runs there first and is timed, and the rest are given to the pool only when they are worth waking workers for. A small
par_mapcosts about whatmapdoes. spawn { ... }runs the block as a task on the pool and returns aFuture<T>of the value itreturns (Future<void>without one). What it captures crosses threads; it can't assign variables from outside. Like aFuturefunction's task, dropping itsFuturecancels it.- A panic in a parallel for's body or in
par_map's function stops the loop: chunks not yet started are skipped, and once the running ones end, the panic is raised in the caller with the loop's place (in a parallel forand its location). A panic in aspawnblock fails itsFuture, as a failed actor call does:awaitraises it,result()returns it as anErr. - A cancelled caller stops a parallel loop the same way, between chunks, and
cancelled()turns true in the chunks that are running; the elements of skipped chunks keep their old values. - Iterations allocate on the heap, even when the loop is inside a gate.
- The calling thread runs chunks too, and waits for the others by parking, like an
await: a loop inside a task or an actor's message lends its worker to other work meanwhile.
On a 10-core M1 Max under heavy load from other processes (load average 15 to 25), a 1600 x 1000 Mandelbrot with up to 1000 iterations per point took 1061 ms with a plain for, 180 to 191 ms with parallel for and 184 to 209 ms with par_map (release builds, three runs each).
all, race, timeout and result
string[] pages = await all([fetch("/a"), fetch("/b")]); // each result, in order
string first = await race([mirror1(), mirror2()]); // the first; the others are cancelled
string? quick = await fetch("/slow").timeout(100); // null after 100 ms; fetch is cancelled
f.result()gives aFuture<Result<T>>:Okwithf's value, orErrwith the panic that failed it (an actor's call or aspawnblock, see Crash isolation), instead of raising that panic in the awaiter. For aFuture<void>it is aFuture<Result<void>>.all(fs)takes a list or slice ofFuture<T>and gives aFuture<T[]>of their results in the order given (Future<void>forFuture<void>s).race(fs)gives aFuture<T>of whichever finishes first and cancels the others;raceof none panics.f.timeout(ms)gives aFuture<T?>that isf's result, ornulliffhasn't finished withinmsmilliseconds, in which casefis cancelled (Future<bool>, whether it finished, for aFuture<void>).- They work on async calls, pool futures and actor calls alike, and on a mix. Each is itself an async call: its
Futurestays on the calling thread, and it waits there without running any pool task in place (exceptall, which awaits each in turn). When one of the futures failed with a caught panic,all,race(when the failed one finishes first) andtimeoutfail with it. - Cancelling a
Futureit was given cancels it however many handles to it exist. The program can still await a race's loser or a timed-out future, and gets what the call returned once cancelled (the zero value of its type for a task that never started). - They are found only where the program declares no function of the same name: a program with its own
allorracekeeps it.timeout(ms)arms ofselectare unrelated.
Host run loops
A program whose thread is driven by something else, such as a GUI toolkit's main loop, runs its async calls from there. The runtime exports three C functions, which C code linked with the program (or Moxy code declaring them extern) can call:
| Function | Does |
|---|---|
int mxy_async_run(void) |
runs the async calls that are ready on this thread, and those they make ready in turn up to this call's own turn, then returns the number of async calls this thread started that haven't finished |
int mxy_async_fd(void) |
a descriptor that turns readable when async work on this thread is ready; mxy_async_run empties it. -1 on Windows and without fibers |
void mxy_async_notify(void (*fn)(void *), void *arg) |
fn(arg) is called whenever async work on this thread becomes ready. It is called from whichever thread readied the work (the poller, the timer thread, a pool worker), often with runtime locks held, so it should only arrange for mxy_async_run to be called on this thread soon (for example post an event to the host's loop) |
Watch the descriptor (or take the callback) and call mxy_async_run on the thread that made the async calls whenever it fires. Code on that thread that waits (await in an event handler) still runs the async calls itself until what it waits for is done.
Sharing between threads
Values cross from one thread to another as a Future function's arguments and result, through a channel, as an actor message's arguments and result, as what an actor literal hands its fields, and as what a parallel loop, par_map's function or a spawn block captures. Each crossing is checked when the program compiles.
- Strings, lists, maps, structs, enums, optionals,
Results and closures are values. They cross freely; a list or map changed after crossing is copied first (copy-on-write), so no thread sees another's change. - A plain
ref structcan't cross: its fields are written without any lock.Future<int> count(Node n),Future<Node> make(),chan<Node>(1), and a struct or list holding aNodeare all errors that name the crossing. - A
shared ref structcan cross. Its fields are written, and those holding counted values read, only insidelock (x) { ... }, wherexis a variable holding that object (selfin a method); What a lock guards has the exact rule.atomicfields need no lock. - An actor can cross: its fields are only ever touched by its own messages.
- A slice (
T[..]) can't cross: it views storage the sending thread keeps using. Copy it with.to_list(). - A
shared ref structcan hold only fields that may cross.
shared ref struct Account {
long balance;
string[] history;
}
Future<void> deposit(Account a, long amount) {
lock (a) {
a.balance += amount;
a.history.push("deposit \(amount)");
}
}
Account acct = Account{ .balance = 0, .history = [] };
Future<void> d1 = deposit(acct, 10);
Future<void> d2 = deposit(acct, 20);
await d1;
await d2;
lock (acct) { print(acct.balance); } // 30
lock (x) { ... }:
- Each object gets a mutex the first time it is locked. Every way out of the block unlocks it, as with
defer: the end of the block,return,break,continue, and?. - A task may lock an object it already holds, so a locked method can call another one on
self. - A task that waits inside
lock(anawait, a channel, a socket) keeps the lock and sleeps its worker thread rather than parking, and the pool starts a stand-in worker meanwhile. The same holds while astd/synclock is held. - Two tasks locking two objects in opposite orders can deadlock, as with any mutex.
- Assigning the locked variable inside its own block is an error.
print(x)andstring(x)on ashared ref structwithout its ownFormattake its lock while they read the fields.- In a program that starts no threads,
lockdoes nothing.
What a lock guards
"Inside lock (x)" means inside the block of a lock (x) { ... } in the same function, where x is the variable the field is reached through: x.f, or self.f in a method. A lambda's body is a function of its own that runs later, so a lambda written inside the block is not inside the lock. For a field x.f of a shared ref struct:
| Access | Outside lock (x) |
|---|---|
a write: =, +=, ++, &x.f, a mutating method (x.items.push(v)) |
error: field 'f' of shared ref struct T is written outside a lock |
a method of a struct field (x.pos.len()), which receives the field by address |
error: ... is lent by address to a method outside a lock |
a read of a counted field: string, list, map, closure, Future, chan, dyn, Result, a ref struct (also weak and unowned), a struct, enum, optional or C array that holds one, or a type parameter |
error: ... is read outside a lock, with a fix-it to read it inside lock (x) { ... } |
a read of any other field: numbers, bool, C pointers, C structs and arrays of them |
allowed |
a read or write of an atomic field |
allowed: one atomic operation |
A counted field needs the lock to read because another thread replaces it under the lock and releases the old value; read without the lock, that value could be freed while it is being used. A field reached through another object (x.head!.text) is guarded by that object's lock, so copy the object into a variable and lock it:
lock (board) {
Note pinned = board.pinned!; // retained: the local keeps it alive
lock (pinned) { print(pinned.text); }
}
Inside the lock, other threads can't replace the field until the block ends. What the block keeps (stored in a variable, returned, captured by a lambda) is retained first, so it stays alive after the lock is left; what it only passes along is lent without a retain, unless the callee may change that field itself.
Atomic fields
shared ref struct Stats {
atomic long hits;
atomic bool done;
string[] log;
}
Future<void> work(Stats s) {
s.hits += 1; // no lock: one atomic add
s.done = true;
lock (s) { s.log.push("worked"); }
}
- An
atomicfield is allowed only in ashared ref struct, holds an integer type,boolor a C pointer, and has no bit width. - A read is one atomic load,
=one atomic store, and+=,-=,&=,|=,^=,++and--one atomic read-modify-write, all sequentially consistent and compiled to the__atomicbuiltins. Integer arithmetic on them wraps without the overflow check of debug builds. - An atomic
boolor pointer is only read and assigned.*=,/=,%=,<<=and>>=are errors, since no single atomic operation does them: write a compare-exchange loop on the field's address instead. x.n = x.n + 1is a load and a store: another thread's update in between is lost. Writex.n += 1.&x.nis a plain pointer (long *) for the__atomicbuiltins (__atomic_compare_exchange_n(&x.n, ...)); reading or writing through it any other way is not atomic.T{ .n = 0 }sets the field with a plain store, before any other thread can see the object.
What the compiler doesn't check
- A plain scalar field read without the lock while another thread writes it is a data race, as in C: the value may be stale or, on wide types, torn. Make it
atomic, or read it inside the lock. - Raw pointers.
string *p = &x.name;inside the lock, used after the block, can point at a value another thread has since freed; so can any C pointer into a shared object. - A global named by
lock (g): another thread may store a different object ingwhile the block runs, since globals aren't checked. Lock a local copy. Mutex.lock()andunlock()(std/sync) held by hand are not alock (m)block to the compiler.- Deadlocks: two tasks that lock two objects in opposite orders wait for each other forever.
What the compiler can't see is checked as the value crosses: a closure or dyn value that holds a plain ref struct panics when it is passed to a task, returned from one or sent (a plain ref struct Node crossed into another thread (passed to future run)).
Globals are reachable from every thread. A managed global written on one thread is safe to read from another after the writer's next crossing: starting a task, a channel send or close, the end of a task, or leaving a lock. Reading a global while another thread writes it is a data race, as in C, and a plain ref struct in a global is not checked.
Reference counts across threads
Reference counts are plain increments and decrements until a value crosses a thread boundary. At the crossing it is marked shared, together with everything it holds, and from then on its counts are atomic. A value is marked once and stays shared; marking stops at values already marked, so a structure handed to tasks again and again is walked only the first time, and the walk is never deeper than the C stack allows. Channels are shared from the start. A shared list or map that is changed is copied first, so the copy (counted plainly again) is what changes.
An unshared retain and release pair costs about 2 to 5 ns; an atomic pair costs about 14 ns (Apple M1 Max).
Cancellation
Dropping the last handle to a future cancels its task. That happens when the handle is reassigned, set to null, or goes out of scope without being returned or stored.
Future<void> poll(chan<string> out) {
while (!cancelled()) { out.send(check()); }
}
void watch() {
Future<void> p = poll(updates);
...
} // p is dropped here: poll stops at its next check
Async calls are cancelled the same way: dropping the last handle to one makes cancelled() true in it and its waits return early, from wherever it is waiting.
- A task that hasn't started never runs. (An async call has always started: it runs until its first wait inside the call.)
- In a task that is running,
cancelled()turnstrue, and the operations that wait return early instead of waiting:awaitreturns the zero value of its type (0,false, ornullfor strings, lists, maps and other handles),sendreturnsfalse,recvreturnsnull, afor v in cloop ends, and aselectruns none of its arms. - A task that an
awaitis running in place is cancelled with the task awaiting it, unless another handle to it exists. - Cancellation is cooperative: a task that never waits and never calls
cancelled()runs to the end. Nothing is killed in the middle of a statement. cancelled()outside any task (inmain) isfalse.- Calling a
Futurefunction or an async function as a statement,work();, drops the handle at once and is a warning. - When
mainreturns, the async calls its locals'Futures were holding are cancelled; before the debug leak report each gets a turn to unwind (up to half a second in all), so what they hold isn't reported as a leak.
Channels
chan<int> c = chan<int>(16); // buffered: up to 16 values
chan<int> u = chan<int>(); // unbuffered: send waits for a receiver
Future<void> producer(chan<int> c) {
for i in 0..10 { c.send(i); }
c.close();
}
Future<void> p = producer(c);
for v in c { print(v); } // until c is closed and empty
await p;
| Operation | Result |
|---|---|
chan<T>(n), chan<T>() |
a new channel with room for n values, or none. A negative n panics. |
c.send(v) |
waits for room (or, unbuffered, for a receiver), then true. false when c is closed or the task is cancelled. |
c.recv() |
waits for a value and returns it as a T?: null once c is closed and empty, or when the task is cancelled. |
c.close() |
no more sends. Values already buffered can still be received. Closing twice does nothing. |
for v in c |
receives until c is closed and empty, or the task is cancelled. |
- Values move into the channel. A value that can't be delivered (closed channel, cancelled task) is released.
send,recvandcloseon anullchannel panic.recvgivesnullfor a closed channel and for a cancelled task alike;cancelled()tells them apart. On achan<T?>a receivednulllooks the same as a closed channel, so usefor v in cor aselectarm to tell them apart.chan<void>is an error: a channel carries values.
select
select waits on several channel operations and runs the arm of the first one that can go.
select {
v = jobs.recv() => handle(v),
done.send(true) => print("reported"),
timeout(100) => print("idle for 100 ms"),
}
select {
v = results.recv() => print(v),
default => print("nothing yet"),
}
- An arm is
v = c.recv()(vis the receivedT),c.recv()(the value is discarded),c.send(value),timeout(ms), ordefault(also_). The arm's body follows=>, as inmatch. - Every channel and sent value is evaluated once, in order, before
selectwaits. - When several arms are ready,
selecttakes them in turn rather than always the first, so no arm starves. defaultruns when no arm is ready right now;timeout(ms)runs when none became ready withinmsmilliseconds. Aselectcan have one of them, not both.- A
v = c.recv()arm fires only when a value arrived, sovis never null and needs no check. Oncecis closed and empty that arm is never ready, like an arm on anullchannel:selectwaits on its other arms, and values still buffered incare received first. Aselectleft with only such arms, and nodefaultortimeout, panics rather than waiting forever. - A
c.recv()arm that binds nothing is ready whencis closed, so it can watch a channel that is closed to signal (done.recv() => return). - A send to a closed channel fires and returns nothing to the arm; its value is released.
- An arm whose channel is
nullis never ready.select { timeout(10) => {} }sleeps for 10 ms. - The value of a send arm that didn't fire is released.
breakandcontinueinside an arm apply to the loop around theselect.
Modules
#include "file.mxy" brings another Moxy file into the program. Moxy resolves the path in this order:
- next to the including file (a file never resolves to itself, so
tests/words.mxycan includewords.mxyfromsrc/); - the project's
src/and configured include directories; - each dependency's directory;
- the embedded standard library (
std/...).
Each file is included once, no matter how many times or in what order it's included, so diamonds and cycles are fine. Errors in included files report that file's name and line.
#include <header.h> and #include "header.h" are C includes, passed to the C compiler unchanged. #define, #pragma and the other directives also pass through.
A macro defined once is visible to the whole program, so modules can include each other in any order. A macro that is redefined or #undef'd follows C: each use sees the definition in effect where it was written. Moxy's runtime comes before your directives, so your macros never change it.
Conditional compilation works anywhere, including around declarations, inside function bodies and inside struct bodies. Two definitions of the same function or global in different branches are allowed:
#ifdef DEBUG
void log(string s) { print(s); }
#else
void log(string s) { }
#endif
Packages
A dependency is a git repository named in moxy.yaml (moxy add <git-url>). The package index maps short names to those repositories so you can write moxy add geom instead. It is a git repository with one JSON file per package, described in docs/design/packages.md. The index is only used by moxy search, moxy add <name> and moxy publish; a build never contacts it.
moxy search [words] list packages whose name, description or keywords contain every word
moxy add <name> [--version tag] add from the index (latest version unless --version is given)
moxy add <git-url> [--name n] [--version v] add straight from a repository, as before
moxy publish [--index-dir dir] [--keywords a,b] [--tag tag]
An argument to moxy add with no /, : or @ is a name. The entry written to moxy.yaml is an ordinary git: dependency with the tag as its version, and moxy add reports an error if the commit pinned in moxy.lock is not the one the index lists for that tag.
The index is read from, in order, the MOXY_INDEX environment variable, index: under build: in moxy.yaml, and https://github.com/moxylang/index. A copy is cached under ~/.cache/moxy/ ($XDG_CACHE_HOME/moxy/), updated on each command, and used with a warning when the update fails.
moxy publish checks that moxy.yaml has a lowercase name, a version, a description and an explicit license, that the tree is clean, and that a tag v<version> (or <version>, or --tag) exists. It prints the index entry, or with --index-dir writes packages/<name>.json into a local checkout of the index, merging with versions already listed. It never pushes or opens a pull request; open one against the index yourself. A tag already listed with a different commit is refused.
The hosted index (github.com/moxylang/index) has not been created yet. Until it exists, point MOXY_INDEX at any git repository laid out as above.
Working with C
- Unknown names are C. An identifier Moxy can't find is assumed to come from a C header. If it's close to a Moxy name, Moxy warns ("did you mean"). If it doesn't exist at all, the C compiler reports it at your
.mxyline, through#linedirectives in the generated C. - Typed declarations.
extern char *getenv(const char *name);orint[] helper();tell Moxy the type of a C function or a function in another file. - Strings. Pass a
stringwherever C wants aconst char *. Turn C strings into Moxy strings withstring(p)or by assigning to astringvariable, which copies. String literals passed to C functions stay plain C literals, so format checking keeps working. - Values Moxy can't see into (
FILE *,size_t,struct stat) flow through unchanged. Moxy refuses to turn them into lists or maps. - @type.
@type Namedeclares a C typedef name so the parser treats it as a type before any header is seen. This is rarely needed: common C typedefs and anyName namedeclaration are recognized automatically. - Headers next to your code.
#include "native.h"finds headers beside any.mxyfile in the program; their directories are passed to the C compiler. - Types as macro arguments. C macros that take a type work as you'd expect:
va_arg(ap, int),offsetof(Point, y). - Declaration macros from library headers. A macro wrapping a function's return type (
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)) and a calling-convention macro before a function's name (void * CJSON_CDECL internal_malloc(size_t size)) are kept and written back in the same place in the generated C, where the C compiler expands them. A calling-convention macro inside a function pointer declarator (void *(CJSON_CDECL *allocate)(size_t)) is dropped: every Moxy target is x86-64 or ARM64, where C compilers ignore calling conventions. A name afterconstorvolatile(const cJSON *item) is read as a type. - Loop macros. A call to a name that isn't a Moxy function, followed directly by a block, is a C macro that expands to a loop header:
cJSON_ArrayForEach(element, array) { ... }compiles to exactly that, with the block as the loop body, sobreak,continueand the release of the body's managed locals work as in afor. Temporaries the arguments need are made once, before the loop. When the name is a Moxy function, the same text is a call followed by a block. A loop macro without braces (each(x, xs) count++;) is not recognized. sizeofon a string literal is the size of the C array, terminator included:sizeof("abc")is 4.- Generated C is plain C11 with the GNU builtins
__atomic_*and__attribute__, which gcc and clang support.moxy emit file.mxyshows it.
Modernizing C with moxy fix
A C file renamed to .mxy already compiles. moxy fix [--write] [files|dirs] then offers mechanical modernizations. Without --write it prints a unified diff to standard output and changes nothing; with --write it applies the diff. Suggestions it could not apply go to standard error as file:line:col: suggestion: ..., each with the reason.
A rewrite is applied only when the compiler can show the program behaves the same; anything short of that stays a suggestion.
| C | becomes | when |
|---|---|---|
goto cleanup; jumps to one label at the end of the function |
defer { ... } after the declarations the cleanup uses; each goto becomes the final return |
there is one label, no other return, the cleanup doesn't jump, and the returned value is a constant or a local the cleanup doesn't touch |
T *p grown with realloc, a length and a capacity |
T[] p = [];, p.push(v), reads of the length become p.len |
T is a number or a plain struct; every use is the growth if, a push p[len++] = v, free(p), or p[i] inside for (i = 0; i < len; i++) that changes neither |
char buf[N] filled with strcpy, strcat, sprintf, snprintf |
string buf, with =, += and interpolation |
the buffer is only written by those calls and only read where C reads a string without keeping it (%s, puts, strlen, strcmp, ...); snprintf only when the output provably fits |
printf("...\n", args), fprintf(stdout, ...), puts(s) as statements |
print("...\(arg)...") |
the format ends in \n and uses only %d %i %u %ld %lu %lld %llu %zu %c %s %%, without flags, width or precision, each matching its argument's type; %f and friends print differently and are left alone |
A struct holding a C enum tag and a union, switched on by its tag, is reported as a candidate for an enum with payloads and match; that change is never applied automatically. Fixes are repeated until nothing changes, so running moxy fix twice gives the same result as running it once.
Debug builds
moxy run, moxy build and moxy test without --release take a faster path to the C compiler on macOS and Linux. The generated C is the same as moxy emit prints; only the way it is compiled changes. Cross builds (--target, or a compiler for Windows) and builds on Windows keep the plain compiler command described under Targets and platforms, and never use tcc or the xcrun shortcut.
- The compiler runs directly, without a shell. Flags that need a shell to mean what they say (quotes,
$, backticks, globs) send the build back throughshas before. - On macOS,
ccandclangin/usr/binare resolved throughxcrunonce and cached, and the real compiler is run with the environmentxcrunwould give it. - The runtime at the top of every generated file is compiled once into a precompiled header, and the rest of the file is compiled from
name.body.cnext to the generated C. Headers are kept in~/.cache/moxy/pch($XDG_CACHE_HOME/moxy, or$MOXY_CACHE) for each compiler, flag set and Moxy version, about 2 MB each; only the 8 most recently used are kept (see Disk use). If the compiler rejects a cached header, the build retries the whole file and drops it. moxy runandmoxy testbuild throwaway binaries without debug info (with it under--sanitize), which on macOS also skipsdsymutil.moxy runuses tcc when one is onPATH(or named byMOXY_TCC;MOXY_TCC=0turns it off): it compiles and runs the program in memory, with no link step. Programs that start threads (futures,async, channels: tcc's-runhas no thread-local storage), builds with extra C sources or custom flags, and an explicitCCstay withcc. The runtime fills in the__atomicbuiltins tcc lacks from the ones it has, so gates, arenas and the rest compile under it;tests/tcc/run.shchecks that when a tcc is installed. A file tcc can't compile, including one that calls an undeclared function, goes tocc, which reports the errors. tcc's warnings are not shown;moxy buildshowscc's.
MOXY_FAST=0 turns all of this off. MOXY_TIME=1 prints how long each stage took, and MOXY_VERBOSE=1 prints the compiler commands.
On macOS the first launch of a newly linked binary takes roughly 70 to 100 ms longer than later launches of the same file. moxy run and moxy test through cc pay that on every program, because every build is a new file; tcc runs the program in memory and doesn't.
C syntax Moxy doesn't parse
Moxy parses your C, so it reads only the C it understands. These extensions are not accepted in .mxy code. They're fine inside C headers you #include and in the body of a #define, because Moxy passes both to the C compiler untouched (a macro used where a declaration keyword belongs is not understood).
| Construct | Workaround |
|---|---|
__attribute__((...)) on declarations |
declare it in a .h file and #include it; the definition can stay in Moxy |
_Alignas(n) |
declare the variable or struct in a .h file |
_Generic(...) used directly in code |
use it inside a #define macro |
statement expressions ({ ... }) |
a helper function or a block |
designator ranges [0 ... 9] = x |
a loop, or list each element |
K&R function definitions int f(a) int a; {} |
prototype-style parameters |
bool, true, false as names |
they're keywords, as in C23; rename the variable |
inline assembly with operands (asm("..." : "=r"(x))) |
put it in a C file listed under sources in moxy.yaml |
Diagnostics
Every compiler error and warning carries a stable code: error[E0805]: match is not exhaustive; missing Color::Blue. E codes are errors and W codes warnings; the first two digits name the phase (E01 lexing, E02 syntax, E04 expressions, W01 lint, and so on). A code always means the same mistake and is never reused, so it is the thing to search for, link to, or match in a .err test; the wording of a message may improve between releases.
moxy explain E0805 prints what the code means, a program that gets it, and the fix: the entry for that code in docs/errors.md, which is built into the compiler. moxy explain --list lists every code with its message. The language server attaches the code, with a link to its entry, to each diagnostic.
A crash inside the compiler is reported as error: internal compiler error, with the location being compiled and a request to report the bug, and exits with code 70. Code nested deeper than the compiler's stack can take (parentheses, blocks or operator chains tens of thousands deep) is error E0003 at the innermost construct, not a crash.
Testing
moxy test [files|dirs] [--sanitize] [--release] [--cycles] [--target t] [--filter text] runs three kinds of test.
Test files. Every .mxy file under a tests/ directory (or named *.test.mxy, or given on the command line) that has a main is built and run. It passes if it exits 0, with files next to it adding expectations: name.out (exact standard output), name.code (exit code), name.err (compile errors), name.warn (warnings), name.stderr (lines standard error must contain), name.own (ownership decisions) and name.fix (moxy fix output). A test also fails if it prints the debug leak report. A file that another file in the run includes is a part of that file, not a test of its own (lib/util.mxy under tests/, std/nettcp.mxy of std/net.mxy): it is built through its includer, and only its own test blocks and doc examples run.
Test blocks. A test "name" { ... } block at file scope is a test written next to the code it tests:
static int parse_digit(char c) { return c >= '0' && c <= '9' ? c - '0' : -1; }
test "digits" {
assert(parse_digit('7') == 7);
}
test "anything else" {
assert(parse_digit('x') == -1, "not a digit");
}
testis a keyword only at file scope, followed by a string literal and a block; a C function or variable namedtestkeeps working. The name is a plain string (no\(...)), and blocks can't go inside a namespace. A block under a false#ifis reported asok (left out by #if).- A block is a function body: it sees the file's
staticfunctions and globals, and can declare locals, usedeferand call anything the file can. moxy test file.mxybuilds the file once, with its blocks, into a binary that runs one block per process: a failedassert, a panic or a crash ends that block only, and the next one starts from fresh globals. Each block is reported asfile: name, with the assert or panic message and its location when it fails, and checked for leaks (the debug leak report) on its own. A file with blocks needs nomain; when it has one, the main still runs against the file's.out,.codeand.stderrfiles.- Only the blocks of the file being tested run. Blocks in files it includes are left out, as they are in every other command:
moxy build,runandemitparse them and generate nothing for them, so the program's C has no trace of them. Astaticfunction that only test blocks call is marked unused in that C, so the C compiler doesn't warn about it. moxy checkandmoxy lintcheck the blocks of the files they are given, so editors show errors inside them.- Walking a directory,
moxy testruns the test files and also every other.mxyfile that has a test block or a doc example (found by a text scan for a line starting withtest ", and for```moxyfences in doc comments). Those other files are built for their blocks only; theirmainis not run. In a project,moxy testcoverstests/andsrc/this way.
Doc examples. A ```moxy fence in a /// or /** */ comment is an example. moxy doc shows it; moxy test compiles and runs it:
/// Clamps `x` to `[lo, hi]`.
///
/// ```moxy
/// assert(clamp(5, 0, 3) == 3);
/// print(clamp(-1, 0, 3)) // prints: 0
/// ```
int clamp(int x, int lo, int hi) { ... }
- An example is a block of statements. It runs as a test block of a program that includes the documented file, so it sees everything that file declares,
staticones too. Each example is reported asfile:line (doc), the line of its opening fence. Errors in an example point at its line in the comment. - It passes if it compiles and runs without a failed assert, a panic or a leak. If it has
// prints: textcomments, its standard output must be exactly those texts, one per line, in order. ```moxy noruncompiles the example but doesn't run it (code that blocks, needs the network, or exits).moxy docshows it as an ordinary```moxyfence. Fences with any other language, or none, are ignored.- The standard library's examples run with
moxy test std.
Options. --filter text runs only the tests whose label contains text: a test file's path, file: block name, or file:line (doc). Files that can't match are not built. --sanitize, --release, --cycles and --target apply to every kind of test; with a --target this machine can't run, each binary is only built.
Cache. In a project, test files, files with test blocks and the programs built for doc examples each keep a directory under build/<mode>/cache/tests, so an unchanged one is run without being rebuilt (see Incremental builds). An entry goes when its file is deleted, or no longer has the blocks or examples it was built for.
Documentation: moxy doc
moxy doc [paths] [-o dir] [--format html|md] [--private] writes API documentation for the declarations in the given files or directories (default: src, else the current directory). A documentation comment is a run of /// lines or one /** ... */ block that ends on the line right above the declaration; a blank line in between detaches it. The text is Markdown-flavoured: paragraphs, - lists, fenced code, # headings, `code` and **bold**. A ```moxy fence is an example that moxy test runs (see Testing). In /** */ blocks a leading * on each line is stripped.
/// A point in the plane.
struct Pair<T> {
T first;
/// The other one.
T second;
}
/** Largest of two values. */
T biggest<T: Ord>(T a, T b) { return a > b ? a : b; }
What is documented: functions (with type parameters), structs, ref structs, unions, Moxy enums (each variant with its payload) and C enums, typedefs, and global variables, each with its fields, variants or enumerators as members. Namespaces qualify the names of their contents, and a doc comment above namespace x { becomes the description of that group. Files pulled in with #include "x.mxy" are documented as their own modules, once, however many files include them; the embedded standard library is not. static functions and variables are left out unless --private is given. Undocumented items are still listed, with their signature.
--format html (the default) writes one page per source file, an index.html listing every item with its first sentence, and style.css, into -o dir (default build/doc). Type names in signatures and in `code` spans link to the item that declares them, across files. --format md writes one Markdown file, index.md, into -o dir, or to standard output when -o is not given. A file that fails to parse is reported and skipped, and the exit status is 1.
Incremental builds
moxy build, run and test in a project (a directory with moxy.yaml) keep a cache under build/<debug|release>/cache and skip work whose inputs did not change.
- Emit. After a successful emit, the cache records every
.mxyfile that went into the program with a hash of its contents. The record is valid only for the same compiler binary, build mode,moxy.yamlandmoxy.lockcontents, include paths and-I/cflags/ldflags. When it still matches, the compiler does not read the sources again. - C compile. The C compiler is run with
-MMD -MF, and the files it read (the generated C, your.csources, and every header outside the system ones) are recorded with their hashes.ccruns again only when one of them or the command line changed, so editing a comment that leaves the generated C byte-identical emits but does not compile, and editing a C header compiles but does not emit. - Output.
Freshmeans nothing ran,Unchangedmeans the emit ran but the C compile did not,Finishedmeans the artifact was rebuilt. Libraries cache each object separately and re-archive only when one changed. - Tests.
moxy testin a project keeps each test's emitted C and binary in a directory per test undercache/tests(one for each test file, each source file with test blocks, and each file's doc examples), so unchanged tests are run without being rebuilt. Tests are always executed. After each run, the entries of tests that no longer exist (or of files that no longer have test blocks or examples) are removed, and then the least recently used until the rest fit in 256 MB (MOXY_TEST_CACHE_MB).
Hashes are 64-bit FNV-1a over file contents: they catch edits, not adversaries. A C compiler that does not accept -MMD -MF (gcc and clang do) cannot be used with build. moxy clean removes the cache with the rest of build/. A build that did any work also removes files that a renamed project or a deleted C source left in build/gen, the step records and obj/. Single-file commands (moxy run file.mxy, moxy build file.mxy) and tests run outside a project are not cached.
Disk use
Moxy keeps its footprint small and bounded: every cache it writes has a cap, and nothing grows with the number of builds.
| Where | What | Cap |
|---|---|---|
build/ in a project |
generated C, objects, binaries, step records, one directory per build mode and --target |
what the current configuration produces; stale files are pruned after each build that did work |
build/<mode>/cache/tests |
each project test's C and binary, about 200 KB per test | tests that still exist, then 256 MB, least recently used first (MOXY_TEST_CACHE_MB) |
~/.cache/moxy/pch |
precompiled runtimes for debug builds, about 2 MB each | the 8 most recently used (MOXY_PCH_KEEP) |
~/.cache/moxy/xcrun* |
the macOS compiler lookup | one line per compiler name |
~/.cache/moxy/index* |
a shallow clone of each package index used | one per index URL |
$TMPDIR/moxy<pid>.* |
scratch for moxy run, single-file build and test |
removed when the command ends, including on errors and on SIGINT, SIGTERM or SIGHUP; one left by a killed or crashed process is removed the next time a precompiled runtime is built, or by moxy clean --cache |
The user cache is $MOXY_CACHE, else $XDG_CACHE_HOME/moxy, else ~/.cache/moxy. Eviction only runs when something new is written (a new precompiled runtime, the end of a test run, a build that did work), so a build that finds everything fresh pays nothing for it. An entry is removed by renaming it aside and then deleting it, and entries used in the last minute are never evicted, so concurrent builds sharing a cache see whole entries or none; a build whose precompiled runtime disappears under it retries without one.
moxy clean remove build/ (and each workspace member's), show the cache size
moxy clean --cache also empty the user cache and remove stale temporary directories
moxy clean --dry-run list what would be removed and how big it is, remove nothing
moxy clean --cache removes only the entries Moxy writes (pch, xcrun*, index*), so a MOXY_CACHE pointing at a shared directory is safe.
Targets and platforms
Moxy builds for the machine it runs on unless you name a target. --target <triple> on moxy build, moxy run and moxy test, or target: under build: in moxy.yaml, cross-compiles:
moxy build --target x86_64-linux-musl app.mxy # a static Linux binary, from any host
moxy build --target x86_64-windows-gnu app.mxy # app.exe
moxy build --target aarch64-linux-gnu # a project: build/aarch64-linux-gnu/debug/<name>
build:
target: "x86_64-windows-gnu"
The command line wins over moxy.yaml. Triples are zig's: <arch>-<os>-<abi>, such as x86_64-linux-gnu, aarch64-macos, x86_64-windows-gnu or native.
The C compiler. build.cc in moxy.yaml comes first, then $CC. Either one is used as it is, so with a target it must already be a cross compiler for that target (CC=x86_64-w64-mingw32-gcc moxy build --target x86_64-windows-gnu app.mxy). With neither set, a target builds with zig cc -target <triple>, so zig is the only toolchain you need for every target. Without a target the compiler is cc (gcc on Windows). cc: "cc", which older moxy new wrote into every moxy.yaml, counts as not set. Libraries are archived with $AR, zig ar, or the cross compiler's own ar (x86_64-w64-mingw32-ar for x86_64-w64-mingw32-gcc).
Output. Programs for Windows targets end in .exe unless -o names the file. Project builds for a target go to build/<triple>/<mode>/, so they don't replace host builds.
Running. moxy run --target refuses a target this machine can't run. moxy test --target compiles every test for the target and runs the ones this machine can (same CPU architecture and operating system, so x86_64-linux-musl runs on x86-64 Linux); the rest are reported as built. A test with an .err file is checked the same way on every target.
Windows
Windows programs build with MinGW-w64 gcc or zig cc (x86_64-windows-gnu, aarch64-windows-gnu). MSVC is not supported yet: the generated C uses GNU builtins and attributes.
- The runtime uses Win32 directly: threads, SRW locks and condition variables for the task pool and channels, an unhandled-exception filter that reports access violations and stack overflows as panics (exit 101), and the performance counter for
monotonic_ms. It declares the handful of Win32 functions it calls rather than including<windows.h>, so names likemin,max,near,far,DELETEorERRORstay free in your code. You can still#include <windows.h>yourself. longis 32 bits on Windows, as in C there. Uselong long(orint64_t) for values that need 64 bits.- Standard output is in text mode, as in C:
\nis written as\r\n.moxy testignores that difference when comparing.outfiles. std/osrun()runs the command withcmd.exe /d /s /c, so the command is acmd.execommand line.- Programs are linked with
ws2_32for std/net. Includingstd/net.mxy(orstd/http.mxy) includes<winsock2.h>, and with it<windows.h>(withWIN32_LEAN_AND_MEANandNOMINMAX), so its macros are visible in that program. Its waits useWSAPoll.
Standard library
Include with #include "std/<module>.mxy".
| Module | Contents |
|---|---|
std/string.mxy |
str_len, str_eq, str_contains, str_starts_with, str_ends_with, join, pad_left, pad_right, reverse, count |
std/math.mxy |
abs_int, min_int, max_int, clamp_int, min_float, max_float, clamp_float, gcd, pow_int, sum_ints, plus <math.h> |
std/io.mxy |
eprint, eprintln, readln, read_file, write_file, append_file, read_lines |
std/os.mxy |
args, env, has_env, run (through sh, or cmd.exe on Windows) |
std/time.mxy |
now_ms (a long long), monotonic_ms, sleep_ms, now_ns, monotonic_ns, Duration, Instant, Date, Time, DateTime, ISO 8601 parsing and output, strftime, UTC and local conversion, time_sleep (see std/time) |
std/hash.mxy |
hash_fnv1a, hash_wyhash, hash_siphash (SipHash-1-3), hash_combine, hash_mix, Hasher, hash_of, hash_all (see std/hash) |
std/rand.mxy |
Rng (xoshiro256**), unbiased below/range, floats, rand_shuffle, rand_choice, rand_sample, OS entropy, a default generator (see std/rand) |
std/fmt.mxy |
fmt_fixed, fmt_sci, fmt_thousands, fmt_hex/fmt_bin/fmt_oct/fmt_radix, fmt_align, fmt_bytes, methods on numbers and strings, Format wrappers (see std/fmt) |
std/path.mxy |
path_join, path_parent, path_file_name, path_stem, path_extension, path_with_extension, path_split, path_components, path_normalize, path_is_abs (see std/path) |
std/fs.mxy |
namespace fs: metadata, exists, read_dir, walk, mkdir_all, remove_all, rename, copy, read_text, write_text, read_bytes, make_temp_dir, current_dir, all returning Result<T, IoError> (see std/fs) |
std/process.mxy |
namespace process: Command, Child, Output, ExitStatus, Stdio, env_get/env_set/env_list (see std/process) |
std/ioerror.mxy |
IoError, the error type of std/fs and std/process |
std/json.mxy |
Json, JsonError, json_parse, json_emit, json_pretty, derive-style to_json, from_json<T>, json_of, from_value<T>, ToJson, FromJson (see std/json) |
std/sync.mxy |
Mutex<T>, RwLock<T>, Atomic<T>, Once, WaitGroup (see std/sync) |
std/set.mxy, std/deque.mxy, std/heap.mxy, std/orderedmap.mxy |
Set<T>, Deque<T>, Heap<T>, OrderedMap<K, V> (see Collections) |
std/net.mxy |
TcpListener, TcpStream, UdpSocket, IpAddr, SockAddr, net_resolve, net_resolve_addr, NetError; tasks waiting on sockets park instead of blocking a worker (see std/net) |
std/http.mxy |
HttpServer with routes and a task per connection, http_serve, http_get, http_post, http_request, HttpRequest, HttpResponse, HttpError (see std/http) |
std/test.mxy |
assert_eq_int, assert_eq_float, assert_eq_str, assert_true, assert_false |
std/debug.mxy |
todo, unreachable |
std/cycles.mxy |
namespace cycles: collect, enabled, for programs built with --cycles (see Cycle collection) |
std/hash
#include "std/hash.mxy"
All hashes are 64-bit (u64) and the same on every platform.
| Function | Notes |
|---|---|
hash_fnv1a(string), hash_fnv1a_bytes(u8[]) |
FNV-1a. Unkeyed and simple, with the published test vectors; weak against crafted input |
hash_wyhash(string, u64 seed), hash_wyhash_bytes(u8[], seed) |
the fast one: wyhash (final v4 construction), for tables and checksums over trusted keys. It needs a 128-bit multiply (__uint128_t: gcc, clang and zig, not MSVC) |
hash_siphash(string, u64 k0, u64 k1), hash_siphash_bytes(u8[], k0, k1) |
the DoS-resistant one: SipHash-1-3 with a 128-bit key. Take the key from rand_os_u64() once per table when keys come from outside |
hash_mix(u64) |
a bijective bit mixer (splitmix64's finalizer) |
hash_combine(u64 seed, u64 h) |
folds h into seed; order matters |
hash_of(v), hash_all(xs) |
v.hash() for any T: Hash, and an order-sensitive hash of a T[] |
Hasher |
Hasher::new(), Hasher::seeded(s), write_u64, write_i64, write_bool, write_f64 (0.0 and -0.0 agree), write_str, write_bytes, finish(); hash_into(&h, v) feeds any T: Hash |
Hasher is how an impl Hash combines fields:
impl Hash for Point {
uint64_t hash() {
Hasher h = Hasher::new();
h.write_i64(self.x);
h.write_i64(self.y);
return h.finish();
}
}
std/rand
#include "std/rand.mxy"
Rng r = Rng::seeded(42); // the same seed gives the same sequence on every platform
long long die = r.range(1, 7); // 1 to 6
rand_shuffle(&r, &deck);
Result<Card> c = rand_choice(&r, deck);
Rng is xoshiro256** seeded through splitmix64. It is fast and statistically strong and it is not cryptographically secure.
| Method | Result |
|---|---|
Rng::seeded(u64), Rng::from_entropy() |
a generator; the second seeds from the operating system |
next_u64(), next_u32() |
raw output |
below(n) |
uniform in [0, n), by rejection sampling, so no modulo bias; 0 when n is 0 |
range(lo, hi), range_incl(lo, hi) |
uniform long long in [lo, hi) and [lo, hi]; lo when the range is empty |
next_f64(), f64_range(lo, hi) |
uniform doubles from 53 random bits, in [0, 1) and [lo, hi) |
coin(), chance(p) |
bool, with probability 1/2 and p |
normal(mean, stddev) |
normally distributed (Box-Muller) |
jump() |
skips 2128 outputs, for independent streams from one seed |
| Function | Result |
|---|---|
rand_shuffle(&r, &xs) |
Fisher-Yates, in place |
rand_choice(&r, xs) |
Result<T>: a random element, or Err on an empty list (a T? once optionals exist) |
rand_sample(&r, xs, k) |
k distinct elements in random order; all of them when k >= xs.len |
rand_os_u64(), rand_os_bytes(n), rand_os_fill(buf, n) |
operating-system randomness: getrandom on Linux, arc4random_buf on macOS and the BSDs, RtlGenRandom on Windows, /dev/urandom as the fallback. Use these for keys and tokens |
rand_int(lo, hi), rand_float(), rand_u64(), rand_coin(), rand_seed(s) |
one thread-local default generator, seeded from the OS on first use or by rand_seed |
std/time
#include "std/time.mxy"
std/time.mxy includes four parts: clock (the original functions, plus now_ns() for nanoseconds since the epoch and monotonic_ns()), duration, date and datetime.
Duration is a signed nanosecond count in a long long (about 292 years either way): Duration::nanos/micros/millis/secs/minutes/hours/days(n), secs_f(x), zero(); as_nanos/micros/millis/secs/minutes/hours() (truncating), as_secs_f(); add, sub, mul(k) (saturating), div(k), neg, abs, is_zero, is_negative, subsec_nanos. Durations compare with == and <, and print as 1h2m3.5s, 250ms, 1.5us, 0s.
Instant is a reading of the monotonic clock: Instant::now(), elapsed(), since(earlier) (a Duration, negative when earlier is later), add(d), sub(d), and ordering. time_sleep(d) sleeps for at least d.
Date is a proleptic Gregorian date { year, month, day }: Date::new(y, m, d) (a Result: Err("invalid day 30 for 2023-02")), Date::from_days(n) and days() (days since 1970-01-01), weekday() (ISO: 1 is Monday, 7 is Sunday), weekday_name(), month_name(), day_of_year(), is_leap(), add_days(n), add_months(n) and add_years(n) (a day past the end of the month moves to its last day), days_until(o), iso(), Date::parse("YYYY-MM-DD"). Free helpers: time_is_leap, time_days_in_month, time_days_from_civil.
Time is a time of day { hour, minute, second, nano }: Time::new(h, m, s), Time::with_nano(h, m, s, n), Time::midnight(), Time::from_secs, secs_of_day(), iso(), Time::parse("hh:mm[:ss[.fraction]]"). There are no leap seconds: second is 0 to 59.
DateTime is { date, time, offset }, a wall clock and the seconds it is east of UTC (0 for UTC):
DateTime::from_unix(secs), from_unix_ms, from_unix_ns, now_utc(), now_local() |
build one; the from_unix forms and now_utc are UTC |
DateTime::new(y, mo, d, h, mi, s), DateTime::of(date, time), of_offset(date, time, off), from_local(date, time) |
from fields; from_local uses the machine's zone |
unix(), unix_ms(), unix_ns() |
the instant as a timestamp (unix_ns only for 1678 to 2262) |
to_utc(), to_local(), with_offset(secs) |
the same instant on another zone; time_offset(h, m) builds an offset |
add(d), sub(d), diff(o) |
instant arithmetic with a Duration |
add_days, add_months, add_years |
calendar arithmetic that keeps the wall-clock time |
iso(), wall(), strftime(pattern) |
2026-11-30T09:05:00+01:00 (or Z), 2026-11-30 09:05:00, and %Y %m %d %e %H %I %p %M %S %f %N %a %A %b %B %j %u %z %:z %Z %s %F %T %% |
DateTime::parse(s) |
ISO 8601: 2026-11-30, 2026-11-30T09:05, a space for the T, fractions, Z, +hh, +hhmm, +hh:mm. A missing zone is read as UTC |
== on DateTimes is structural, so two zones for one instant differ; < and cmp compare the instant. to_local and from_local use the C library's time zone (TZ, or the system's); on Windows they cannot see instants before 1970 and a TZ value needs the C library's PST8PDT style.
std/fmt
#include "std/fmt.mxy"
Width and padding count characters (UTF-8 code points), not bytes. Floats are formatted by the C library, so fmt_fixed(2.5, 0) is "2" (round half to even on the binary value).
| Function | Example |
|---|---|
fmt_fixed(x, prec), fmt_sci(x, prec), fmt_percent(ratio, prec) |
"3.14", "1.50e+03", "25.6%" |
fmt_thousands(n, sep), fmt_thousands_f(x, prec, sep), fmt_group(digits, sep, size) |
"1,234,567", "1,234,567.89" |
fmt_hex(n), fmt_bin(n), fmt_oct(n), fmt_radix(n, base, upper), fmt_radix_signed(n, base, upper) |
"ff", "101", "-ff" |
fmt_prefixed(n, base), fmt_zero(n, width), fmt_radix_zero(n, base, width) |
"0xff", "007" |
fmt_align(s, width, fill, Align::Left/Right/Center), fmt_left, fmt_right, fmt_center, fmt_truncate(s, width), fmt_width(s) |
" ab ", "hello..." |
fmt_bytes(n), fmt_bytes_si(n) |
"1.5 KiB", "1.5 MB" |
The same as methods: s.pad_start(w, fill), s.pad_end(w, fill), s.center(w, fill), s.truncate(w), s.width() on string; hex(), bin(), oct(), radix(base), zero_pad(w), thousands(sep) on int and long long (hex, bin, oct, radix on uint64_t too); fixed(prec), sci(prec), thousands(prec, sep), percent(prec) on double.
Wrapper types implement Format, so they work in interpolation, lists and string(x): fixed(x, 2), hexed(n, width, prefix), binary(n, width, prefix), and fmt_aligned(v, width, Align::Right) for any T: Format:
print("total: \(fmt_aligned(fixed(total, 2), 10, Align::Right))");
Because Duration, Date, Time and DateTime implement Format too, fmt_aligned(duration, 8, Align::Left) pads them the same way.
IoError
std/fs.mxy and std/process.mxy include std/ioerror.mxy:
enum IoError {
NotFound(string path), Permission(string path), Exists(string path),
NotDir(string path), IsDir(string path), NotEmpty(string path),
Other(int code, string msg)
}
path is what the failed call was given (the program name for process). Other carries the system error code and its message. IoError implements Format (not found: a/b), == works on it, and io_error(errno, path) builds one from an errno value. Match it with match e { NotFound(p) => ..., Exists(p) => ..., _ => ... }; patterns do not nest, so Err(NotFound(p)) is written as a match on r.error().
std/path
#include "std/path.mxy"
String work only; no file is touched. / separates components; on Windows \ does too, and a drive prefix such as C:\ is a root. Joined and normalized results use the platform separator.
| Function | Result |
|---|---|
path_join(a, b), path_join_all(parts) |
joined with one separator; an absolute b replaces a; "" is skipped |
path_parent(p) |
string?: "/a/b" gives "/a", "/a" gives "/", "a" gives ""; null for "" and a root |
path_file_name(p) |
string?: the last component, ignoring trailing separators; null for "", a root or a path ending in .. |
path_stem(p), path_extension(p) |
string?: x.tar.gz gives x.tar and gz; a leading dot (.bashrc) is not an extension |
path_with_extension(p, ext) |
replaces or adds the extension; "" removes it |
path_split(p) |
a PathSplit with dir and name ("" when absent) |
path_components(p) |
the names between separators, without the root |
path_normalize(p) |
drops . and empty components and resolves .. lexically (symlinks are not consulted); ".." above a root is dropped, above a relative start kept; the empty result is "." |
path_is_abs(p), path_is_sep(c), path_root_len(p) |
std/fs
#include "std/fs.mxy"
Everything is in namespace fs and returns Result<T, IoError> when it can fail. Windows paths use the ANSI code page, so a path with characters outside it is not supported there.
fs::mkdir_all("out/logs")?;
fs::write_text("out/logs/a.txt", "hi")?;
for e in fs::read_dir("out/logs")? { print(e.name, e.kind); }
fs::remove_all("out")?;
| Function | Result |
|---|---|
metadata(p), symlink_metadata(p) |
fs::Metadata: size, mtime_ms (ms since the epoch), mode (permission bits), kind; is_file(), is_dir(), is_symlink(). The second does not follow a final symlink (POSIX) |
exists(p), is_file(p), is_dir(p) |
bool, following symlinks |
read_dir(p) |
fs::DirEntry[] (name, path, kind, depth), sorted by name, without . and .. |
walk(root, max_depth, keep), walk_all(root) |
every entry below root, depth first, parents before children, names sorted. max_depth 1 lists the children, -1 is unlimited. keep is an fn(fs::DirEntry) -> bool; a rejected entry is left out and a rejected directory is not entered. Symlinks are listed, not followed; a subdirectory that cannot be read is skipped |
mkdir(p), mkdir_all(p) |
one directory; or with missing parents (an existing directory is fine) |
remove(p), remove_all(p) |
a file, symlink or empty directory; or a whole tree (symlinks are removed, not followed) |
rename(from, to) |
replaces an existing destination file |
copy(from, to) |
the bytes copied; keeps permission bits on POSIX |
read_text(p), write_text(p, s), append_text(p, s) |
whole files as string |
read_bytes(p), write_bytes(p, bytes), append_bytes(p, bytes) |
u8[]; bytes is a u8[..], so lists and slices both work |
current_dir(), set_current_dir(p), absolute(p) |
the working directory; a path made absolute and normalized lexically |
temp_dir(), make_temp_dir(prefix), make_temp_file(prefix) |
$TMPDIR/$TEMP/$TMP or /tmp; a new unique directory or empty file under it, which the caller removes |
std/io's read_file, write_file and append_file keep working and report errors as strings.
std/process
#include "std/process.mxy"
Programs are started directly, never through a shell, so arguments reach the program as given. POSIX uses posix_spawn; Windows uses CreateProcess with the command line quoted for the Microsoft C runtime (a program that parses its own command line differently, such as a .bat file run through cmd.exe, may see arguments differently). The Windows side is compile-checked only; it has not been run.
process::Output o = process::Command::new("git").arg("status").arg("--short").output()?;
if (o.status.success()) { print(o.out); }
process::Child c = process::Command::new("sort").pipe_in().pipe_out().spawn()?;
c.write("b\na\n")?;
c.close_stdin();
print(c.read_out_all()?); // ["a", "b"] as lines
print(c.wait()?); // exit 0
A process::Command is a value; each builder returns an adjusted copy: arg, args(list), setenv, unsetenv, clear_env, cwd, stdin_is, stdout_is, stderr_is, and the shorthands pipe_in, pipe_out, pipe_err. A stream is a process::Stdio: Inherit (the default), Pipe, Null, File(path) (stdin reads it; stdout and stderr replace it), Append(path), and ToStdout (stderr only).
| Call | Result |
|---|---|
cmd.status() |
runs to the end and returns the ExitStatus |
cmd.output(), cmd.output_with_input(s) |
a process::Output (status, out, err). Stdout and stderr are piped unless set otherwise, stdin is null (or s), and both streams are read at once, so large outputs cannot stall the child. Output is binary-safe |
cmd.spawn() |
a process::Child (a ref struct; dropping it closes its pipes but does not wait or kill) |
process::run(program, args) |
Command::new(program).args(args).output() |
child.wait(), child.try_wait() |
the ExitStatus, repeatable; try_wait gives null while the child runs. wait closes the child's stdin first |
child.kill(), child.terminate() |
SIGKILL and SIGTERM; both are TerminateProcess on Windows. A child that already ended is not an error |
child.write(s), child.close_stdin() |
the child's stdin pipe |
child.read_out_chunk(), child.read_err_chunk() |
string?: what is available (up to 64 KB), null at the end of the stream |
child.read_out_all(), child.read_err_all() |
until the stream ends. Reading one of two piped streams to the end can stall the child; use communicate |
child.communicate(s) |
feeds s to stdin, closes it, collects stdout and stderr and waits |
child.id(), process::id() |
process ids |
ExitStatus has code, signal (POSIX; 0 when the process exited), success() and shell_code() (128 plus the signal). It prints as exit 3 or signal 9. A program that cannot be started gives IoError::NotFound(program) (or Permission). Ignoring SIGPIPE in the parent happens once a stdin pipe is created, so writing to a child that has exited returns an error instead of ending the program; the child still starts with the default. cwd needs posix_spawn_file_actions_addchdir_np (glibc 2.29, macOS 10.15, musl).
Environment: process::env_get(name) (string?), env_set, env_remove, env_list() (a map[string, string]), and process::exit(code).
Collections beyond list and map
#include "std/set.mxy" // Set<T: Hash + Eq>
#include "std/deque.mxy" // Deque<T>
#include "std/heap.mxy" // Heap<T>
#include "std/orderedmap.mxy" // OrderedMap<K: Ord, V>, Entry<K, V>
All four are generic structs with methods, written in Moxy. Each is a value like a list: assigning one copies on the first write. Moxy has no user-defined iteration, so for x in coll does not work on them; every one has each(fn) and a method that returns a list (to_list, keys, entries, into_sorted). Each implements Format (when its element types do) and Eq (when they do).
| Type | Core methods |
|---|---|
Set<T> |
Set<T>::new(), from(list), add(x) (true if new), has, remove (true if present), len, is_empty, clear, to_list, each, unite, intersect, minus, is_subset, is_disjoint. Insertion order. Prints {1, 2}; equality ignores order. (union is a C keyword, so the union is unite.) |
Deque<T> |
A ring buffer. new(), from(list), push_back, push_front, pop_back, pop_front (each T?), front, back, get(i) (T?), at(i) (panics out of range), set(i, x), len, is_empty, clear, contains (T: Eq), to_list, each. All O(1) amortized. Prints [1, 2] |
Heap<T> |
A binary heap. Heap<T>::min(), max(), from(list) (these need T: Ord), Heap<T>::by(fn(T, T) -> int) (any T; the lowest comparison comes out first), push, pop and peek (T?), len, is_empty, clear, to_list (heap order), into_sorted(), each |
OrderedMap<K, V> |
An AVL tree in index-linked lists, sorted by K: Ord. new(), set(k, v) (true if new), get(k) (V?), get_or, has, remove (true if present), first, last, pop_first, pop_last, floor(k), ceil(k) (each an Entry<K, V>?), range(lo, hi) (lo <= key < hi), from(lo), keys, values, entries, each, each_range, len, is_empty, clear, valid() (checks the invariants; for tests). Prints {a: 1, b: 2}. Lookups and updates are O(log n); range is O(log n + hits) |
Lambdas passed to these take typed parameters ((string k, int v) => ...).
std/json
#include "std/json.mxy"
std/json.mxy includes jsonvalue (the Json type), jsonparse, jsonemit and jsonmap (the derived mapping).
enum Json { Null, Bool(bool b), Int(long long i), Num(double d), Str(string s),
Arr(Json[] items), Obj(map[string, Json] members) }
Numbers are two cases: Int for an integer literal that fits in 64 bits, so ids and counters survive; Num (a double) for everything else. An object is a map[string, Json], so member order is the insertion order. Int(1) == Num(1.0) is true.
json_parse(text) |
Result<Json, JsonError>. Strict RFC 8259: no comments, trailing commas, leading zeros, NaN or single quotes; the whole text must be one value; invalid UTF-8 and unpaired surrogate escapes are errors; at most 512 levels of nesting; a repeated key keeps its first position and last value. "\u0000" is an error, because Moxy strings end at a NUL byte |
JsonError |
message, line and col (from 1, columns count characters), offset (bytes), and path (set by the mapping, like $.items[2].qty). Printed as line 3, column 7: unexpected character 'x', expected a value or $.qty: expected number, found string |
json_emit(j), json_pretty(j), json_pretty_with(j, indent) |
compact and indented text (also j.emit(), j.pretty(), and print(j)). NaN and infinity are written as null |
j.get(key), j.at(i), j.has(key), j.keys(), j.len() |
Json?, Json?, bool, string[], long |
j.as_bool(), as_int(), as_num(), as_str(), as_arr(), as_obj(), is_null() |
T? of the matching kind (as_int also takes a whole Num) |
json_of(v), to_json(v), to_json_pretty(v) |
any supported T to a Json, compact text, or pretty text |
from_json<T>(text), from_value<T>(j) |
Result<T, JsonError> |
The mapping follows the type through compile-time reflection, so a struct needs no code:
| Moxy type | JSON |
|---|---|
bool |
true, false |
| any integer type | an integer; decoding checks the width and signedness (u8 rejects 256 and -1). A u64 above 2^63 - 1 is written as a floating-point number and comes back rounded (the largest u64 survives) |
float, double |
a number; decoding takes an Int or a Num |
string |
a string |
T[] |
an array |
map[string, V], or an integer key type |
an object; integer keys are written as strings |
T? |
null or the value. An absent member of an optional field decodes to null; an optional field is always written |
struct, ref struct |
an object with one member per field, in order. Decoding ignores members it has no field for, and reports a missing member unless the field is optional |
| enum without payloads | the variant name as a string |
Json |
itself |
Anything else, an enum with payloads for example, is a compile error that names ToJson or FromJson: implement them to say how the type maps, and the mapping uses your code in place of the derived one, wherever the type appears:
impl ToJson for Version { Json to_value() { return Json::Str("\(self.major).\(self.minor)"); } }
impl FromJson for Version {
Result<void, JsonError> set_value(Json j) { // `self` starts as the zero value
string s = from_value<string>(j)?;
...
return Ok();
}
}
Errors from decoding name their location: $.outline[1].x: expected number, found string.
std/sync
#include "std/sync.mxy"
Shared state for futures and threads. Everything here is a shared ref struct (or a generic one), so passing it to several futures shares one object. Their fields follow the sharing rules. A Mutex's lock is the object's own, the one lock (m) { ... } takes: its methods, lock() and the lock statement all exclude each other, and m.value is used inside lock (m) or through the methods. Atomic.v, Once's state and the sockets' descriptors are atomic fields. RwLock adds a reader-writer lock, a pthread one on POSIX and an SRW lock on Windows. Note that a Future that is dropped without being awaited is cancelled: keep the handles in a list, even when a WaitGroup is what you wait on.
| Type | Methods |
|---|---|
Mutex<T> |
Mutex<T>::new(v), lock(), try_lock() (true when it now holds the lock), unlock() (in a program that starts threads, panics in a task that doesn't hold it), with(fn(T *)), get() (a copy), set(v), the public field value, and locked(m, fn(T *) -> R) for a result |
RwLock<T> |
new(v), read(fn(T *)) (many at once, on a copy taken under the object's lock), write(fn(T *)) (alone), read_lock(), read_unlock(), write_lock(), write_unlock(), get() (a copy), set(v), read_locked(l, f), write_locked(l, f) |
Atomic<T> |
T an integer type or bool: new(v), load, store, swap, cas(expected, desired) (bool), compare_exchange (returns the old value), add, sub (return the new value), fetch_add, fetch_sub, fetch_and, fetch_or, fetch_xor (return the old value). Sequentially consistent; arithmetic wraps |
Once |
Once::new(), run(fn()) (true for the call that ran it; the others wait for it), done() |
WaitGroup |
new(), add(n), done(), wait(), pending(). done() below zero panics. wait() blocks its thread: call it from main, and inside a pool task await the futures instead |
Mutex<long> total = Mutex<long>::new(0);
total.with((long *p) => { *p += 1; });
long n = locked(total, (long *p) => *p);
lock (total) { total.value += 5; } // the same lock as the methods take
total.lock(); // held by hand until unlock()
defer total.unlock();
A Mutex's lock is reentrant: the task that holds it may take it again, so a closure passed to with can call get() on the same Mutex, and try_lock() in the holder succeeds. lock() held by hand doesn't count as being inside lock (m) for the compiler, so read m.value inside lock (m) { ... } (which then just goes one level deeper) or through the methods. An RwLock's reader-writer lock is not reentrant, and taking it again from the task that holds it deadlocks. Holding any lock across an await, a channel operation or another lock invites a deadlock. A Mutex is for several tasks that update one value in place; a chan<T> is for handing values from one task to another, and needs no lock at all. Methods cannot take type parameters yet, so a result comes back through the function locked instead of a method.
std/net
#include "std/net.mxy"
TcpListener l = TcpListener::bind("127.0.0.1:0")?; // port 0: any free port
print(l.local_addr()); // 127.0.0.1:52144
TcpStream c = l.accept()?;
string got = c.read(4096)?; // up to 4096 bytes; "" once the peer is done
c.write_all("echo: " + got)?;
Every operation returns Result<T, NetError>. Sockets are non-blocking underneath. Inside a task (a Future function), waiting for a socket parks the task and frees its worker for other tasks: one poller thread watches the sockets (kqueue on macOS and the BSDs, epoll on Linux, WSAPoll on Windows) and wakes the task when its socket is ready. Outside a task, a wait blocks the thread. A timeout, close() on the socket from another task, and dropping the task's future all end a wait early, with NetError::TimedOut, Closed or Cancelled.
| Type | |
|---|---|
IpAddr |
a value: IpAddr::v4(a, b, c, d), localhost(), any(), v6_localhost(), v6_any(), IpAddr::parse(s) (numeric only); is_v4(), is_v6(), is_loopback(), is_unspecified(); prints as 127.0.0.1 or ::1 |
SockAddr |
{ ip, port }: SockAddr::of(ip, port), SockAddr::parse("1.2.3.4:80") or "[::1]:80"; prints the same way |
TcpListener |
TcpListener::bind("host:port"), bind_addr(sockaddr); accept(), accept_timeout(ms), local_addr(), close(), is_closed() |
TcpStream |
TcpStream::connect("host:port"), connect_timeout(addr, ms), connect_addr(sockaddr, ms); read(max), read_exact(n), read_all(), write(s) (some bytes), write_all(s), set_timeout(read_ms, write_ms), set_nodelay(on), shutdown_write(), peer_addr(), local_addr(), close(), is_closed() |
UdpSocket |
UdpSocket::bind("host:port"); send_to(s, sockaddr), recv_from(max) (a Datagram { data, from }), connect(sockaddr), send(s), recv(max), set_timeout, local_addr(), close() |
NetError |
Refused, Reset, Closed, TimedOut, Cancelled, AddrInUse, AddrUnavailable, Unreachable, NotFound(host), Invalid(reason), Os(code, message); prints as a message (connection refused) |
- Listeners, streams, UDP sockets and
HttpServerareshared ref structs, so tasks can share them: the socket closes when the last reference goes.close()closes it at once and wakes every operation waiting on it; the descriptor itself is released when the last operation using it returns. A stream can be read by one task and written by another at the same time. - Timeouts are milliseconds,
0for none (the default). A stream's read timeout applies to eachread, not toread_allas a whole. - Data is bytes in a
string, which may hold any byte,\0included. net_resolve(host)gives theIpAddr[]of a name,net_resolve_addr("host:port")theSockAddr[]. Numeric addresses come back as they are andlocalhostis127.0.0.1and::1without a lookup; other names go togetaddrinfo, which a task runs on a thread of its own while it parks.bindandconnectresolve names the same way and try each address in turn.TcpListener::bindsetsSO_REUSEADDR(except on Windows, where it means something else) and listens with a backlog of 512. Writes never raiseSIGPIPE: a write to a closed connection fails withNetError::Reset.- On Windows, Winsock starts with the first socket.
WSAPollbefore Windows 10 version 2004 doesn't report a refused connection; useconnect_timeoutthere.
std/http
#include "std/http.mxy"
HttpServer srv = HttpServer::bind("127.0.0.1:8080").unwrap();
srv.get("/hello", (HttpRequest r) => HttpResponse::text(200, "hello\n"));
srv.get("/items/:id", (HttpRequest r) => HttpResponse::json(200, "{\"id\": \"\(r.params["id"])\"}"));
srv.post("/echo", (HttpRequest r) => HttpResponse::text(200, r.body));
Future<int> running = http_serve(srv); // a task: accepts until stop()
HttpResponse got = http_get("http://127.0.0.1:8080/items/7").unwrap();
print(got.status, got.body); // 200 {"id": "7"}
srv.stop(); // closes the listener and open connections
print(await running); // the number of connections served
HTTP/1.1 over std/net, without TLS (only http://), HTTP/2 or compression. std/http uses futures, so a program that includes it starts the task pool when it serves or fetches.
Server. HttpServer::bind(addr) (or HttpServer::on(listener)) makes a server; route(method, path, handler), get, post, put and delete add routes, whose handlers are fn(HttpRequest) -> HttpResponse. http_serve(srv) is a Future<int> that accepts connections and handles each one in its own task until srv.stop(), then closes what is still open, waits for those tasks and returns how many connections it served. Dropping that future cancels it: it stops accepting and closes its open connections, but the listener stays open until stop() or the server's last reference goes.
- Routes match the method and the whole path. A
:namepart matches any one part and is captured inr.params["name"]; a final*matches the rest of the path (r.params["*"]). A path that matches only other methods gets405with anAllowheader, any other404.HEADruns theGETroute and sends no body. HttpRequesthasmethod,target(as sent),path,query(after?, undecoded),version,headers(HttpHeader { name, value }, in order),body,paramsandpeer;r.header(name)is the first header of that name in any case, as astring?.- Request bodies are read by
Content-LengthorTransfer-Encoding: chunked;Expect: 100-continueis answered before the body is read. - Limits (
set_limits(max_head, max_headers, max_body)): the request line and headers together, 16 KiB by default (414when the request line alone is over it,431otherwise); 100 header lines (431); a 1 MiB body (413). A malformed request gets400, an HTTP version other than 1.0 and 1.1505, and the connection is closed. - Connections are kept alive (HTTP/1.1 unless the request says
Connection: close; HTTP/1.0 only withConnection: keep-alive) until idle for 5 seconds (set_idle_timeout(ms)). - Handlers run on any worker, several at once; what they share must be safe to share between threads. Add routes before calling
http_serve.
Responses. HttpResponse::text(status, body), html, json, empty(status) and chunked(status, content_type, chunks) (sent with Transfer-Encoding: chunked, one chunk per string); r.set_header(name, value) adds or replaces a header; r.header(name) reads one. The server sets Content-Length (or Transfer-Encoding) and Connection itself. http_reason(status) is the reason phrase.
Client. http_get(url), http_post(url, body, content_type) and http_request(method, url, headers, body, timeout_ms) return Result<HttpResponse, HttpError>. Each request uses its own connection (Connection: close) and a 30-second timeout for connecting and for each read and write (http_request takes it as an argument, 0 for none). The response body may be sized by Content-Length, chunked, or run to the end of the connection, up to 64 MiB; 1xx responses are skipped.
HttpError is Net(NetError), BadUrl(url), BadMessage(reason) or TooLarge(what), and a NetError converts to it with ?.