muro-lang.dev / docs
Emit
In brief: emit keeps run. run internal is defp. Spec and evidence are omitted. A temporal declaration is evidence about one meeting, so the Zig backend omits it with the others. A family is spec. Elixir, C, Rust, Zig, JavaScript, assembly, OTP, --node, and ExUnit omit it. --backend fsm emits one dispatcher for a family that checks, beside the session machines. Erased Π-arguments are dropped from the generated arity. A non-run fragment that somehow remains becomes raise "erased term". --backend c writes C for closed Nat, data, and run streams, and each session as a pure step the host drives. An exported run of Nat arguments and a Nat result is also a NIF. --backend rust writes the same closed run as Rust. --backend zig writes that same closed run as Zig. --backend js writes that run as an ES module and a declaration file, and a lambda is a closure. --backend asm writes a Cortex-M0 Nat run. --backend otp writes a GenServer for each process that conforms to a session. --backend fsm writes each session endpoint as a state machine and leaves the transport with the host. --node writes one call for each cross, on the node the flag names.
A meeting that marks a party may fail is checked. --backend otp monitors that party and runs the failure arm when the peer dies before it has halted. --backend fsm takes the same arm with down. C, Rust, Zig, JavaScript, assembly, --node, the ExUnit backend, and the pytest backend still refuse the book with c:mayfail. The declaration stays in the book.
From a file
iex -S mix{:ok, src} = Muro.emit_file("examples/half_ok.muro", Foo)
IO.puts(src)
Muro.emit_file/2 parses, checks (with the prelude in scope), then emits. If the book does not check, you get the error and no module. A prelude run the file calls is emitted as defp. One the file does not call is left out. The file’s own run definitions are unchanged. A book that uses U8, U32, U64, or I64 calls Muro.Word from the emitted module. Compiling that module needs a muro dependency. The archive does not supply it. See Machine numbers.
The generated file starts with:
defmodule Foo do
# Generated by Muro. Evidence never becomes a run.C
--backend chooses the emitter. The default is Elixir, the same text as Muro.emit_file/3.
mix muro.emit path.muro
mix muro.emit path.muro --backend elixir
mix muro.emit path.muro --backend c
mix muro.emit path.muro --backend c --prefix admit_
mix muro.emit path.muro --backend rust
mix muro.emit path.muro --backend zig
mix muro.emit path.muro --backend js
mix muro.emit path.muro --backend asm
mix muro.emit path.muro --backend otp
mix muro.emit path.muro --backend fsm
mix muro.emit path.muro --backend exunit
mix muro.emit path.muro --backend pytest
mix muro.emit path.muro --backend mbi
mix muro.emit path.muro --node a
--backend mbi writes <stem>.mbi beside the book only when the book has exactly one exported run and that body erases, and the binder grades stay. A run the entry calls, including a run internal and a prelude run, is a closed definition in the image. A run that calls none still writes format 1. Two definitions that call each other are refused. A refusal writes nothing. An image already at that path stays byte for byte, including when the book has no exported run (mbi:entry) and when it has more than one. The file is the image muro-beam loads. It is not Erlang BEAM bytecode. The other backends still replace a grade pair with the affine quantity. See MBI images.
--backend c writes <name>.h and <name>.c next to the file and prints those paths. It emits run and run internal, and a session in the same book is a pure step. The host passes the state and an event. muro__sess_<name>_step_word takes a direction, a payload kind, and a uint64_t instead of that event. A data word is the constructor’s number in this book. The name-string step remains. A word the kind does not accept is refused before the tag is stored, and expected is word. Each book’s source defines muro__sess_word_step once, and every step_word in that book calls it. The function returns the next state and the action, or refuses an event the protocol does not allow. The actions are the ones --backend fsm takes on that step. Agreement with that machine is checked by a bounded walk: at most 14 states, and depth at most 6, including events the protocol does not allow. A foreign key and a position that is not a step are the same unexpected refusal. The host keeps the transport. There is no protocol loop. down is not a step. Init takes each initial nat as uint64_t, so a negative cannot be supplied, where the state machine’s init raises on a negative. A meeting marked may fail is still refused (c:mayfail). A session the machine cannot represent, a payload with a repr, and an unboxed payload, including an unboxed type nested under boxed data, are refused (c:session). A run the case calls is one this backend already emits. The value that run sees is built for the call and freed when the step finishes, including when a field of that value does not build. A nat inside that run is built with muro__suc, and a nat above 100000 is refused before that term is built. run internal is static. Erased arguments are dropped. Nat is a tagged struct (0 is zero, 1 is suc) with constructors muro__zero and muro__suc. Unit and user data, indexed data included, are a tag plus fields. match on Nat, on an atom, and on declared data is a switch. match on WBool is a test of the uint8_t. match on Opt is a test of tag, and the payload is val by value. Division, remainder, and checked arithmetic declare that Opt struct even when the function returns the payload rather than the Opt. A match whose result is a string is muro__str_empty(). A match whose result is another struct, including Slice and Bytes, initializes the temporary with {0}. A pointer or a word still uses 0. A constructor with no fields is one static object, written as a designated initializer of the tag and the unused union member, and its function returns that address. A binder the arm does not use is not declared. An unused parameter is (void). A static function the book does not call is marked unused. The generated file compiles with -Wall -Wextra -Werror -std=c11. A constructor with fields allocates through muro__ALLOC. unboxed data is that same struct, returned by value. Its constructor is a compound literal and does not call muro__ALLOC. A field of unboxed data is the struct, not a pointer, and a boxed constructor may store one. A pair, or a stream seed or environment, that contains unboxed data is refused (c:unboxed). An Opt of unboxed data is refused the same way. An Opt of ordinary data is a pointer to that data. wsome t sets tag to 1 and stores that pointer in val. Every identifier is either a source spelling or a generated name. A source spelling is an injective encoding of the source identifier: z and Z are doubled, _ is zu, - is zd, and ' is zq. It gains _k when that encoding is a C keyword through C23, a typedef from <stdint.h> or <stdbool.h>, or a common function from the C library and POSIX (true, read, malloc). The encoding has no underscore, so a source uint8_t is uint8zut and does not spell the typedef. A spelling that is already taken, by an earlier definition or by a constructor function, gains a numeric suffix. A binder is claimed against every name visible in its scope, including type names. A source spelling contains no __. A helper, a step, a constructor argument, and a temporary are muro__ plus a tag, so they always contain __. a-b, a_b, and a_b_2 stay three functions. That spelling is the C, Rust, Zig, or JavaScript symbol. --prefix TEXT on this backend, and c_prefix: on a :c manifest entry, prepends TEXT to every run, including a run internal, to that book’s session entry points, to each data struct, and to that struct’s tag enum. TEXT is a C identifier and includes the separator (admit_). An empty prefix leaves every name as an unprefixed book emits it. run internal stays static and is not a header entry. Rust, Zig, JavaScript, and assembly do not take the prefix. A host export is the source name: the Elixir NIF maps it the same way as the Elixir backend and calls the prefixed symbol.
A run stream is a struct: the seed, an environment for values the step closes over, and a function pointer for the step. unfold n (λ k → (k, suc k)) is muro__stream_new of n and that step. uncons calls the step and returns the head together with a new struct for the tail. The original seed stays in place, as Enum.take plus Stream.drop does on the Elixir backend. examples/zeros.muro and examples/nats.muro are the drivers. Always and ~ are evidence, so they are omitted. A lambda applied on the spot is a local: the argument is evaluated once and the body uses it. An unapplied lambda, and a call of a local function, are refused (c:lambda).
A run of U8, U32, U64, or I64 is passed by value on C, Rust, and Zig. Signed wrapping on C is unsigned arithmetic, cast back. A shift at or past the width is not a host shift. Division by zero, and signed division of the minimum by −1, are not evaluated. F32, Tensor, addt, and packI are refused (c:machine) and still emit on the Elixir backend. A raw ν, Always, or ~ inside a run is refused (c:stream). Evidence that mentions a string is omitted, the same way other evidence is. Elixir still emits a string as a binary, and JavaScript emits { string: "…" }.
Bytes and Slice are one C type, passed and returned by value:
typedef struct { const uint8_t *p; size_t n; } muro__slice;
The header declares that typedef only when a run uses octets, under #ifndef MURO__SLICE, and with it a one-byte static empty buffer. Two headers that use octets define the typedef once. The empty buffer is marked unused, so a translation unit that includes the header and does not mention the buffer still compiles with -Wall -Wextra -Werror. n == 0 and p points at that byte. p is never null. A literal is a static const uint8_t array in the function, and the value is {p, n} of that array. An empty literal uses the static empty buffer. slice is pointer arithmetic: an in-range span, including a length of zero, is {s.p + off, len} and shares the buffer. A span that starts past the end, or that does not fit, is the static empty value. bytesCat allocates once, muro__ALLOC of the combined length, and copies both sides. A combined length that would wrap size_t is abort, the same as an allocation failure. An empty concatenation does not allocate. The image never frees the buffer. A host buffer stays the host’s: muro__slice_of(p, n) wraps it without copying, and a null pointer or a length of zero is the static empty value. The slice is a view into that buffer, or into a buffer muro__ALLOC returned. Its lifetime is the host’s: the view dangles if the buffer is freed, or if the arena is reset, while the slice is still held. Read or copy what a call returns, then reset the arena cursor. Evidence that only mentions octets is omitted, and the rest of the book is unchanged. Elixir emits a binary: length is byte_size, a view is :binary.part, and an octet is :binary.at. JavaScript emits a Uint8Array. A view is a subarray of the same buffer. Assembly is the Nat fragment, so a run that returns octets is asm:scope.
A string is a different C type, also passed and returned by value:
typedef struct { const uint8_t *p; size_t n; } muro__str;
n is the number of UTF-8 octets, not the number of scalars. There is no trailing NUL, so scalar 0 is an octet in the buffer: "a\u{0}b" is {0x61, 0x00, 0x62} and strLen of it is 3. The header declares the typedef when a run uses a string, under #ifndef MURO__STR, and with it a one-byte static empty buffer. Two headers that use strings define the typedef once. The empty buffer is marked unused, so a translation unit that includes the header and does not mention the buffer still compiles with -Wall -Wextra -Werror. An empty string is {p, 0} of that byte, and p is never null. A literal is a static const uint8_t array in the function. strEq compares n and then the octets with memcmp, and does not allocate. strLen walks the lead bytes, counts scalars, and builds that Nat with muro__zero and muro__suc. It assumes well-formed UTF-8. A string muro emits always is. A malformed host string, passed in over the FFI, may be miscounted. strCat allocates once, muro__ALLOC of the combined octet length, and copies both sides. A combined length that would wrap size_t is abort. An empty concatenation does not allocate. strBytes is (muro__slice){s.p, s.n}: the same buffer, no copy. A string stored in a pair slot or a stream seed is one heap copy of the struct; the octets stay where they are. Assembly refuses a string (c:string).
The header is shaped like this:
/* generated by muro — do not edit */
#ifndef muro__H_halfzuok
#define muro__H_halfzuok
#include <stdint.h>
#ifndef muro__ALLOC
#define muro__ALLOC(n) malloc(n)
#endif
#ifndef MURO__PRELUDE
#define MURO__PRELUDE
typedef struct muro__nat muro__nat;
struct muro__nat { uint8_t muro__field_tag; muro__nat *muro__field_suc; }; /* 0 = zero, 1 = suc */
typedef struct muro__unit muro__unit;
struct muro__unit { uint8_t muro__field_tag; };
#endif
muro__nat *half(muro__nat *n);
#endif
MURO__PRELUDE is the same guard in every book, so struct muro__nat and struct muro__unit are defined once when two headers share a translation unit. A session header also names muro__sess_status, muro__sess_dir, and muro__sess_tag, and it guards muro__sess_st by the number of nat slots. Two session headers with that same count share the struct. A different count is a compile error. The unprefixed muro__sess_init and muro__sess_step prototypes are guarded the same way. A prefixed book emits those names with the prefix and does not use that guard, so they can sit beside an unprefixed book. Each data type has a tag enum (muro__tag_Reply_replyzdok is 0 when reply-ok is the first Reply constructor). The book has one flat word enum (muro__word_<stem>_Reply_replyzdok). A prefix is prepended to that word enum, to the tag enum, and to the data struct (admit_Piece, admit_muro__tag_Piece). These stay unprefixed: struct muro__nat, struct muro__unit, and the MURO__PRELUDE guard; the session status, direction, and payload enums and the MURO_SESS_* constants; muro__sess_val, muro__sess_st, and muro__sess_res; the MURO__SESS_SLOTS guard; muro__slice under MURO__SLICE and muro__str under MURO__STR; an Opt typedef name (muro__opt_*); the atom enum muro__atom; generated helpers (muro__zero, muro__ALLOC, muro__field_tag); a constructor function and a union member, which keep the source spelling; and the static session helpers (muro__sess_word_step, muro__sess_word_bad, muro__sess_src_*, muro__sess_build_*, muro__sess_free_*). The Elixir function name stays the source name. An Opt of a word, Nat, Unit, a string, or a slice sits under MURO__OPT_<PAYLOAD>, and the field type is that shared payload. An Opt of data keeps muro__opt_* with no guard, because the field type is that book’s struct spelling, prefixed when the book is. Two books that both emit an Opt of the same data type still share that name. Two books that both declare Piece can share a translation unit when each is emitted with its own prefix. Without a prefix they still cannot. Two session books with no prefix both define muro__sess_init.
muro__ALLOC is malloc unless you define it before the generated file is compiled. Every allocating constructor calls it, and so do muro__nat_new, muro__mk_pair, and a stream’s environment. A fieldless constructor is a static object and does not. The pointer a function returns points into that storage. Read or copy it, then set the cursor back to the start. The next call reuses the block. The static objects stay where they are.
#define muro__ALLOC(n) arena_alloc(n)muro__nat *n = two();
/* copy what you need from n */
arena_at = 0;A Nat run is a NIF
An exported run whose live arguments and result are Nat is a NIF entry. When the working directory is the loaded Mix project, --backend c writes <stem>_nif.h, <stem>_nif.c, <stem>.mk, and <stem>.ex beside the C, and elixir_make runs that makefile. The library is priv/<stem>.so. The module is the camelized stem (half_ok.muro is HalfOk). HalfOk.half(4) is the integer 2, and HalfOk.plus(2, 3) is 5. Outside that directory, and in the self-contained executable, the same command writes the .h and the .c only.
The entry builds the tagged struct and reads it back. An argument that is not a non-negative integer fitting in 64 bits is a bad argument, and so is a result that does not fit. Allocation goes through muro__ALLOC, defined as one block for the call. The call copies the integer out and resets the block, so the next call reuses it. Two calls do not share the cursor.
run internal stays static and is not an entry. A run whose argument or result is not Nat stays in the C file and is not an entry. A file with no Nat entry writes the .h and the .c only. The allocator in that unit is the generated name muro__nif_alloc. A source spelling has no __, so it cannot take that name. The Elixir loader stays muro_nif_load. The Elixir function is the name every Elixir-facing backend uses for that run. A hyphen folds to _. A name whose fold is already a function name takes that fold, so foo_bar is foo_bar/0, read is read/0, and foo-bar is foo_bar/0. A book that also defines foo_bar is refused at check. Anything the fold cannot make plain is muro__ plus the encoding: Bit is muro__Bit/0 and and is muro__and/0. The name is claimed for every run, in book order, before internal and non-Nat runs are dropped, so the suffix does not depend on which runs the NIF keeps. A run named muro_nif_load is muro_nif_load_2. The C symbol is still the spelling, so read calls read_k. A prefix is prepended to that symbol. The stub calls that symbol. cc translates the C. The proof stops at the run image.
Rust
--backend rust writes <name>.rs next to the file and prints that path. It prints the same closed run as the C backend. run internal is a private function. muro__Nat is muro__tag_zero or muro__tag_suc. An atom is one variant of a closed enum. A stream is a seed and a step. muro__from_u64 builds a Nat and muro__to_u64 reads it back. Identifiers use the same split as the C text: a source spelling contains no __, and a helper, a step, a constructor argument, or a temporary always contains __. A binder is claimed against every name visible in its scope, including type names. Rust reserves primitive types and the prelude names its runtime uses (Clone, Copy, PartialEq, Eq, Fn). It names u64 as ::std::primitive::u64, and it writes derives and dyn Fn with a full path. half(4) is 2 and plus(2, 3) is 5, the same integers the Nat NIF returns. A term the C backend refuses is refused here, with the same reason, including an unboxed value in a pair, a stream, or an Opt (c:unboxed). An unboxed product is the enum, passed by value, and its constructor does not call Rc::new. Bytes and Slice are muro__slice, a #[repr(C)] pair of *const u8 and usize, passed by value. The layout is the C layout. A literal is a static array. A sub-slice is pointer arithmetic. Concatenation allocates one Vec and does not free it, the same contract as the C arena. muro__slice_of wraps a host buffer. A string is muro__str, that same #[repr(C)] shape with its own type. n counts UTF-8 octets. strLen counts scalars by walking lead bytes and assumes well-formed UTF-8: a string muro emits always is, and a malformed host string may be miscounted. strCat allocates one Vec and does not free it. A combined length that would wrap usize is abort, and so is bytesCat. strBytes is that pointer and length as a muro__slice.
A match on WBool is true and false. A match on Opt is Some and None, and an unused payload is _. wsome of ordinary data is Some of that value. A match whose result is muro__slice is that struct. Neither word match builds an Rc.
rustc translates this text. cc translates the C. CompCert is the high-assurance C translator. Neither is the proof. The proof stops at the run image.
Zig
--backend zig writes <name>.zig next to the file and prints that path. It prints the same closed run as the C backend. run internal is a private function. Nat and user data are tagged unions. A fieldless constructor is one static value. match on Nat and on declared data is switch. match on WBool tests the u8 against 0. match on Opt is if (o) |v|, and an unused payload is |_. wsome of ordinary data is that optional. A match whose result is muro__slice is that struct. Neither word match allocates. A stream is a seed, an environment, and a step. A lambda applied on the spot is a local. half(4) is 2 and plus(2, 3) is 5, the same integers the Nat NIF returns. A term the C backend refuses is refused here, with the same reason, including an unboxed value in a pair, a stream, or an Opt (c:unboxed). An unboxed product is the union, passed by value. Its constructor returns the value and does not call create. Bytes and Slice are muro__slice, an extern struct of [*]const u8 and usize, passed by value. The layout is the C layout. A literal is a function-local struct whose bytes have static storage. A sub-slice is pointer arithmetic. Concatenation allocates once through muro__allocator and can return an error. The other octet operations do not. A string is muro__str, that same extern struct with its own type. n counts UTF-8 octets. strLen counts scalars by walking lead bytes and assumes well-formed UTF-8: a string muro emits always is, and a malformed host string may be miscounted. strCat allocates once through muro__allocator. strBytes is that pointer and length as a muro__slice.
A function that allocates takes muro__allocator: muro__std.mem.Allocator first and returns an error union. The caller can pass a muro__std.heap.ArenaAllocator and reset it. muro__from_u64 builds a Nat. muro__to_u64 reads one back. Identifiers use the same split as the C text. A source spelling contains no __. It gains _k when the encoding is a Zig keyword, a primitive such as u64, bool, type, or anyopaque, or a width such as u8, and a numeric suffix when that spelling is already taken. Zig has no path for a primitive, so the spelling is what keeps u64 in scope. A binder is claimed against every name visible in its scope, including type names. A helper, a step, a constructor argument, or a temporary is muro__ plus a tag, so a suffix cannot move it into the source spellings. A binder hidden by a later binder in the same pattern is discarded.
The text is Zig 0.15. zig translates it. The proof stops at the run image.
JavaScript
--backend js writes <name>.mjs and <name>.d.ts next to the file and prints both paths. It emits run and run internal, and each session endpoint the machine can represent as a stepper. run internal is a function the module does not export. Nat is a JavaScript bigint: 0 is 0n and suc adds one. The host passes 4n, not 4. Unit is null. U8, U32, and U64 are unsigned residues. At the host boundary I64 is a signed bigint: the host sees -1n for I64 −1 and -(2n**63n) for the minimum, and a signed input is accepted. Inside the module, word operations keep the unsigned residue, the same integer the Elixir backend computes. A constructor field of I64 stays that residue. match on Nat tests 0n. match on WBool tests the boolean. match on Opt tests k === "some" and reads v. wsome of ordinary data is { k: "some", v } of that value. match on data switches on the constructor name. A match whose result is a Uint8Array returns that array, and a sub-slice is a subarray of the same buffer. A constructor is {tag, fields}. Declared Bool stays that tagged object ({tag: "true", fields: []} or {tag: "false", fields: []}), and the declaration file types it as the union of those two objects so a host checks .tag. A word bool is a JavaScript boolean. An atom is the source name as a string. A string is { string: "hello" }. strLen is the number of scalars, and strCat concatenates. The declaration file types String as { readonly string: string } and Atom as string. muro__canon prints "hello" for the string and hello for the atom. Bytes and Slice are a Uint8Array. A view is subarray, so it shares the buffer. An out-of-range view is a fresh empty array. muro__canon prints a Uint8Array as b"…", with the same escapes as a bytes literal. strBytes of a string value encodes UTF-8. A closed string literal is already those octets.
A match may scrutinize a variable the enclosing arm binds. The element of a list is that variable. The inner match may be the arm or an argument of a constructor, and the function may recurse on the tail. A refusal names the definition it stopped on, and names the construct when it has one.
A lambda is a JavaScript closure. A definition is one function of its live arguments, so the host calls plus(2n, 3n). A function value is curried, so a parameter of type Nat → Nat is called as f(n). An unapplied lambda, a definition passed as a value, and a call of a local function are emitted. A wrapper that only passes its one argument on to a function of one argument is that function: ident passed as a value is ident, and λ (n : Nat) → f n is f. A partial of a function of several arguments stays an arrow, (m) => plus(n, m), because plus takes both arguments at once and the arrow closes over n. C, Rust, and Zig still refuse an unapplied lambda, a definition passed as a value, and a call of a local function (c:lambda). F32, Tensor, addt, and packI are refused (c:machine). A raw ν, Always, or ~ inside a run is refused (c:stream). A gone variable used as a value is refused (c:erased). A string is emitted. A host placement (place, scheme, or move) refuses the book, and nothing is written. A session endpoint the machine can represent is a synchronous stepper (init, send, recv, done, expected, check_trace). The host owns the transport. A protocol the machine cannot represent, and a session whose payload type has a repr, is omitted, and the runs are still written. A run that names a session is refused, and nothing is written. A repr emits decode_<type> and encode_<type> beside the runs. Decode returns {ok: {value, table}} or {error: {path, reason}} and does not throw. Encode takes the value and the name table and returns {ok: wire} or {error}. The stepper does not use those codecs.
A run stream is an object: the seed, an environment for values the step closes over, and the step. uncons calls the step and returns the head together with a new object for the tail. The original seed stays in place. The step is a function of the module. half(4n) is 2n and plus(2n, 3n) is 5n, the same integers the Nat NIF returns.
A hyphen in a source name folds to _. golden-silence is golden_silence. A name that is already a JavaScript identifier stays, including zeros, fromMaybe, and Bit. A keyword, a host name such as Array or undefined, or a TypeScript word the declaration file cannot reuse gains _k. A character outside that alphabet is an injective $ escape. The module and the declaration file use that same spelling. Two source names that reach one identifier are refused before any file is written, and the message names both. a-b and a_b are that refusal. C, Rust, and Zig keep the injective encoding, so a-b, a_b, and a_b_2 stay three functions there. A binder is claimed against the function names in the file. A parameter _ stays _, and a second one is _2. A helper or a step is muro__ plus a tag.
The declaration file names the exported runs, the data they build, and each session stepper. A data type with a parameter of sort Type is generic: List (A : Type) is List<A>, a field List A is List<A>, a field List (List A) is List<List<A>>, and a field List Nat is List<Nat>. An index is not a parameter, so Vec A n is Vec<A>. Stream carries its element. A Stream Nat is Stream<Nat>, and muro__uncons returns a head of that element and a stream of the same element. The seed stays unknown, because the seed is not the element. An erased type parameter of an exported run is a generic of that function. The module does not take it. A type the declaration cannot name stays unknown. I64 in that file is the signed bigint the host sees. Internal runs and steps are not exported. node runs the module. The proof stops at the run image.
A self-tail call compiles to a loop. Other named recursion is trampolined, so a deep Nat recursion stays within the JavaScript stack. A host closure that recurses on itself uses the host stack.
Cortex-M
--backend asm writes <name>.s next to the file and prints that path. The text is GNU assembler, Thumb, for Cortex-M0. It prints a Nat run. half(4) is 2 and plus(2, 3) is 5, the same integers the Nat NIF returns. run internal is a label the file can call. It is not exported. A string is refused (c:string). A run that returns octets is outside this fragment (asm:scope). An unboxed product is outside it (asm:scope). An Opt of ordinary data is outside it (asm:scope). Evidence that only mentions octets is omitted.
The assembler translates this text. The proof stops at the run image.
OTP
--backend otp writes <stem>_otp.ex next to the file and prints that path. ping.muro is ping_otp.ex, and the module is PingOtp. Each conform is a child module. PingOtp.Pong.start/1 takes the peer pid and returns {:ok, pid, ref}. ref is a monitor of the server, installed before the process takes its first action.
A nil-buffer process, and start/2, send {:muro, from, value}. A nat is an integer. A bit is :b0 or :b1. Unit is :tt. A pair is a two-element tuple. A record is a map whose keys are the field names. A choice is {:muro_pick, from, :b0} or :b1. A bit index is {:muro, from, :b0} or {:muro, from, :b1}. The receiver holds both arms and takes the one that bit names. A match that names a constructor receives that value: :nothing takes the nullary arm, and {:just, b} binds b. A put of that field, or of a run of it, sends the value. It receives the same shapes from that peer. A message that arrives before the server reaches that receive is kept, in order. On start/2, done stops the server with :normal at that finish. stop stops it with {:shutdown, :abandon}. A monitor of the server sees that reason. A value of a type the process did not name stops it with {:shutdown, {:unexpected, value}}.
An integer buffer N on a paired meeting uses another wire for data and choice. The payload is {:muro, from, id, value}. The choice is {:muro_pick, from, id, bit}. id is a fresh integer for that send, starting at 0. At most N ids are waiting for an ack. An id stays there after the peer consumes the token, until that ack is applied, so the set can include a consumed token in transit. While N ids are unacked the sender yields. That yield applies a peer failure already recorded, and a later ack or failure still runs if the process stays up. Consumption sends {:muro_ack, from, id}. The ack returns that credit when from is the peer and id is still unacked. Queuing the token does not ack it. A repeated ack, an unknown id, and {:muro_ack, from} leave the set as it is. Ids are not reused. Buffer 0 is this bound with no room: every send yields. A meeting that sends deadlocks. A done/done meeting can finish. Buffer 0 is not the nil-buffer meeting.
A paired process stays up after its skeleton reaches done. It sends {:muro_settled, from} once its unacked set is empty, its queue is empty, and it is not waiting to send. It stops :normal after the peer’s settled message has been applied. The caller of a meeting sees that reason on the monitor, later than the return of the meeting function. On a meeting that does not mark the peer, a DOWN whose reason is not :normal stops this process with {:shutdown, :abandon}, including while it is yielded for credit or waiting to settle. A :normal DOWN before this process has settled is the same abandon, including one already recorded when a full buffer yields. A peer marked may fail is below. A :normal DOWN after this process has settled, while an id is still unacked or a token is still queued, is {:shutdown, :orphan} even when the peer sent no settled message. The same orphan is the stop when the peer has settled and this process still holds an unacked id or a queued token. A compatible generated pair that finishes the handshake stops :normal. A data or choice tuple whose from is the peer and whose arity belongs to the other cap stops {:shutdown, :incompatible_wire}. A message from another pid is still ignored. Pairing an integer buffer with a nil buffer, or with start/2, is a manual composition. The server has one peer. A protocol message is taken when from is that pid. Another pid does not move credit or the handshake. from is not a check of the sending BEAM process. Regenerate every generated process that shares a conversation, and run that set as one version. The formal account is the Agda model. The executable checker is not that theorem. Temporal and fairness transfer to this schedule is unproved.
The server talks to one peer. The run emitters still omit the protocol and the process. The BEAM runs this server. The proof stops at the conformance derivation.
A process whose peer is marked may fail monitors that peer, the same monitor this image already installs. A :DOWN that is not a halt, while this process is at a receive from that peer, runs the failure arm of that receive, once. A reason on the arm is the :DOWN reason, as a host term. The image does not check that term against the payload type. :kill arrives as :killed. A match on the name selects the arm and binds the constructor’s fields. A reason that matches no arm stops {:shutdown, {:unexpected, reason}}. A put to a peer already observed dead is consumed and is not an error. The death is handled at the next receive. Protocol done is :normal, and that exit is a halt only after this process has settled or the peer has sent its settled mark. A :normal exit before that runs the failure arm. Protocol stop sends {:muro_halt, _} and then exits {:shutdown, :abandon}. That exit is a halt even when the halt message has not arrived, and the failure arm does not run. Any exit {:shutdown, :abandon} is that stop. A meeting that does not mark a party emits none of this machinery. It keeps abandon, settle, and orphan: a peer exit other than :normal is still {:shutdown, :abandon}.
A message that reached this mailbox is applied before that :DOWN. On one node, a message that actually arrived, including {:muro_settled, _}, is delivered ahead of :DOWN. The checker also counts a run that drops a message already queued toward the survivor. This image does not take that run. When the survivor is at a receive, the queue from that peer is empty, and the death has been observed, the failure arm runs.
A read is the same process. The actions are the reading’s process, and the child module is the reading’s name.
mix muro.emit examples/located.muro --backend otp
That writes examples/located_otp.ex. The module is LocatedOtp. read stay pong : ping-home at home is LocatedOtp.Pong.start/1, and read cross pong-away : ping-home at away is LocatedOtp.PongAway.start/1. Both take the peer pid. Both receive a nat and send 1, then stop with :normal at local finish. start/1 on the child calls start/2 and is not paired. pong-poly, pong-poly-away, and pong-done are that same exchange, as PongPoly, PongPolyAway, and PongDone. left-open is LeftOpen. It sends 0 and stops with {:shutdown, :abandon}. Pong stays at home and PongAway crosses at away. A process name whose function spelling is plain snake case (lowercase words of letters and digits joined by single underscores) camelizes, so pong is Pong, foo_bar is FooBar, and pong-away is PongAway. Any other name is M plus the function spelling. Two aliases that camelize to one name take _2. The server talks to one peer either way. The boundary is the call --node writes.
A meeting starts the two processes it names as each other’s peer. Both are running before either takes its first action. Both are paired. A nil buffer keeps the 3-tuple wire and leaves the mailbox unbounded. Completion still waits for the settled handshake. An integer buffer uses the 4-tuple wire and the credit bound.
mix muro.emit examples/meet.muro --backend otp
That writes examples/meet_otp.ex. The module is MeetOtp. meet wire : pong with peer is MeetOtp.wire/0. It returns {:ok, left, right, left_ref, right_ref} once both processes are peers and both have been sent their first action. left runs pong and right runs peer. Each ref is a monitor of that server, installed before the first action. Both servers of wire are the nil-buffer image. They stop :normal after the handshake. arm is the choice, and both servers finish with :normal the same way. drop is both ends abandoning after 0, and both stop with {:shutdown, :abandon} at stop. wrapped sends (b0, {x = 0, y = 0}), which the peer receives as a tuple whose second element is a map with keys x and y, and both servers finish with :normal after the handshake. Pong.start/1 still takes a peer pid supplied by the caller and stops :normal at its own finish. The payload stays on the session. The place stays the call --node writes.
examples/indexed.muro is the same image for a bit index. IndexedOtp.wire/0 starts the server that offers both arms and the client that sends :b0. The server answers 1. wire_one sends :b1 and then 0. echo_wire sends :b1 and receives that same bit. The message is {:muro, from, bit}. A nat sent where the index is expected stops the server with {:shutdown, {:unexpected, value}}.
examples/recursive.muro is the same image for a protocol that repeats. RecursiveOtp.wire/0 starts the server that echoes a nat while the bit is b0 and the client that sends b0, 1, and then b1. Both finish with :normal after the handshake. The skeleton of the loop is {:loop, name, body} and the jump is {:jump, name}. drive stores the body and a jump calls drive on that body. The call is in tail position. Forever is rec X. get (n : Nat) (put n X). It does not finish. A caller sends a nat and receives that nat, then sends another.
Fsm
--backend fsm prints one module on standard output. It does not write a file. meet.muro is MeetFsm, and session ping is MeetFsm.Ping. init, send, recv, and done? step that end. A book that marks a party also has down. A book that does not mark a party emits no down. The host sends the message on its own transport. The wire form is the one this OTP section names: a nat is an integer, a bit is :b0 or :b1, unit is :tt, a pair is a tuple, a record is a map, a vector is a list, a choice is {:pick, :b0} or {:pick, :b1}. An evidence payload is still the nat alone, and the machine also checks the bound. The OTP image does not. down/1 takes a failure arm that binds no reason. down/2 takes one that does, and checks the reason the host supplies. The OTP image does not check that reason. Where the protocol has no failure arm, down is an error. A match on the reason binds the constructor’s fields. An arm the machine cannot resolve is not done. A keyed family that checks is one more child: new/0, arrive/4 (the state, the key, the constructor, and the creation index), resolved/2, withdraw/2, and check_trace/1. resolved drops an open instance. withdraw drops a held instance and the meeting does not run. The state keeps the live instances of each key. A repeat of a live instance is an error. A repeat of a forgotten instance is not caught. resolved of a forgotten id returns {:error, {:unknown, id}}. The family child has finish. :resolve drops the instance. :rerun keeps the row, with no bound, and check_trace then accepts a new session for that id. Each end of the meeting has finish too. When one family uses that end, the outcome is the same. When two families share it, the call is {:error, {:family, names, form}} and form is finish(family_state, id, session_state, step) on the family child. check_trace/1 also replays that end’s sends, receives, and down, a withdrawal, and reports an instance whose session finished and was never resolved. An unknown id is an error and does not raise. These checks are the emitted code. They are not an Agda proof. See State machines.
Node
--node writes <stem>_node.ex next to the file and prints that path. The book is checked first. A book that fails to check writes nothing. With no --backend, or with --backend elixir, that file is the only output. Any other backend together with --node is refused.
mix muro.emit examples/place.muro --node a
That writes examples/place_node.ex. The module is PlaceNode. The flag is a BEAM node name: it starts with a letter or _, and the rest is letters, digits, _, @, ., or -. Anything else is refused. a is the atom :a, and PlaceNode.node/0 returns it. Every cross in the file is sent to that node.
place away := node a is what the checker reads. away is the place, and a is the node in that declaration. The flag is what the generated call addresses. This example spells that node a in the declaration and in the flag.
place.muro has one cross, move cross local : away. It is the function PlaceNode.cross_local_at_away/1. local is the scheme and away is the place, and both names are in the function. A second cross of that scheme at that place is cross_local_at_away_2. A scheme or a place that is not a plain lowercase name, or that already contains _at_, is not joined that way: the function is the Elixir spelling of a length-prefixed pair, so two different pairs do not share a name. The name registered on the node is the scheme as an atom when that scheme is already an atom (:local). A hyphenated scheme uses the same Elixir spelling as a function. The message stays {:muro_read, scheme} with the source string.
cross_local_at_away takes a timeout in milliseconds. The default is 5000, so PlaceNode.cross_local_at_away() uses that. The destination is {:local, :a}: a process registered as :local on the node :a. That process handles {:muro_read, "local"}, the read of the scheme. The function monitors the destination, and then calls:
GenServer.call({:local, :a}, {:muro_read, "local"}, timeout)
The function returns whatever that process replies. If the name is not registered, the monitor reports :noproc and the function returns {:error, :noproc}. If the call exits, the function returns {:error, reason}. Each call looks the name up again. A process that later registers as :local is the one the next call reaches.
A stay writes no function. move stay local : home, and both reads of poly, are absent from place_node.ex. A file whose moves all stay still writes the module, with node/0 and no call.
A read cross is the same call. The scheme is the one the endpoint names, and the place is the one the reading names. The message is the read of that scheme. The payload stays on the session.
mix muro.emit examples/located.muro --node a
That writes examples/located_node.ex. The module is LocatedNode. read cross pong-away : ping-home at away is LocatedNode.cross_local_at_away/1, because ping-home names local. pong-done and left-open also read local at away, so they are cross_local_at_away_2 and cross_local_at_away_3. Each one monitors :local on :a and calls with {:muro_read, "local"}. read stay pong writes no function. A reading of poly writes no function either: poly stays at home and at away.
kept is a run definition in the same file. mix muro.emit examples/place.muro emits it. The place, the scheme, and the move are omitted there, as they are from every run emitter. mix muro.emit examples/located.muro emits kept the same way. The endpoint and the reading are omitted there.
The BEAM runs this call. The proof stops at the move.
Visibility
| Tag | Elixir |
|---|---|
run |
def |
run internal |
defp |
spec |
omitted |
evidence |
omitted |
data |
omitted as a type; constructors appear only as runtime tags inside run terms |
examples/internal_ok.muro: step → defp step; inc → def inc calling step.
How values look
| Muro | Elixir |
|---|---|
0 |
0 |
suc(n) |
n + 1, a non-negative integer |
tt |
:tt |
0-argument ctor (nil, nothing, leaf) |
atom (:nil, :nothing, :leaf) |
| n-argument ctor |
{:ctor, args…} |
left n / right t |
{:left, n} / {:right, t} |
(a, b) |
{a, b} |
let (a, b) = e in t, fst, snd |
({a, b} = e; t) |
run Stream |
Stream.unfold/2 |
addi / addt / packI |
Nx.add / Nx.stack / Nx.tensor |
rewrite emits as its body. refl would be :refl if it ever appeared in run; it should not.
A Nat is a non-negative integer of any size, the same integer on the wire, in a repr, and in an ExUnit suite. A closed numeral is that integer literal. A match on 0 and suc is a case on 0, and the suc arm rebinds the predecessor as the integer minus one.
A match on a Nat takes 0 or a positive integer. A negative integer, a float, or any other term raises CaseClauseError, so a host that passes something that is not a Nat gets an error, not a predecessor that keeps going down. A recursive run that is not a library operation still takes one call per unit of the value it recurses on: half of a billion is half a billion calls.
A run whose name, type, and body are exactly a library definition is emitted as the integer operation that definition computes: pred and plus from the prelude, max, min, and minus from std:le.muro, and compare from std:ord.muro. plus 1000000 3 is one addition. The function is guarded to take only non-negative integers and raises FunctionClauseError otherwise. A file that redefines one of those names, or a mutant of its body, is not that definition and keeps the emitted recursion.
That replacement is trusted: the emitted body is not the checked term. agda/Muro/NatPrim.agda proves under --safe that each operation, read over ℤ, equals a clause-for-clause transcription of its library definition at every natural number. The transcription is not checked against the .muro text, and Elixir integer arithmetic being ℤ arithmetic is assumed. test/muro_emit_nat_test.exs compares each operation with the emitted recursion as a regression test.
C, Rust, Zig, JavaScript, and Cortex-M keep their own Nat representation, described in each section above.
Failing functions
A run function that can fail returns a sum, and its constructors are the Elixir tags. Nothing in the kernel knows the {:ok, _} / {:error, _} convention; the constructor names do the work (examples/result.muro):
data Result (E : Type) (A : Type) : Type where
ok : A → Result E A
error : E → Result E A
def pred : run Π (n : Nat) → Result Unit Nat :=
λ (n : Nat) →
match n motive (λ _ → Result Unit Nat)
| 0 => error tt
| suc p => ok p
emits def pred(x0) returning {:error, :tt} or {:ok, x1}. A caller that wants a raising variant writes it in Elixir over the emitted function; emit never raises except for Empty.
Erased arguments
Erased binders are not parameters of the Elixir function.
def length : run Π (- A : Type) → Π (xs : List A) → Nat
becomes something like def length(xs). The type argument is gone. In Muro you still write length Nat ones2 (or length A as in a recursive call). The checker sees A. Emit does not.
A run definition with the name and live arity of a Kernel function or macro (length/1, max/2, min/2, div/2) is excluded from the module’s import Kernel, so the call means the definition: import Kernel, except: [max: 2].
A hyphen folds to _. If that fold is a function name (^[a-z_][A-Za-z0-9_]*$, no __, not reserved), it is the spelling: golden-silence is golden_silence, and foo_bar, fromMaybe, and muro_and stay. Anything else is muro__ plus Muro.Emit.Name.encode/1 of the source name: Bit is muro__Bit, and is muro__and, and ? and ! are escaped. Two source names in a book, including imported packages, that reach one host spelling are refused at check, and the message names both. Elixir, NIF, OTP, FSM, and ExUnit read that one map. A meeting uses the same spelling (window-wire is window_wire). A constructor atom that is already a valid atom stays (:Bit, :just, :nil); any other constructor uses this spelling, so is-on is :is_on. A module alias camelizes a snake name (pong is Pong, foo_bar is FooBar, grant-end is GrantEnd). Every other alias is M plus the function spelling (and is Mmuro__and). Two aliases that camelize to one name are A1b and A1b_2.
Functions as values
A run definition becomes an Elixir function with one parameter per live (non-erased) argument, and a function value is a curried closure: a variable applied to two arguments is f.(a).(b), and λ (x : A) → t is fn x -> t end. A reference to a definition is emitted by how many arguments it is given (examples/higher_order.muro):
-
As many as its type has Πs: a direct call,
plus(a, b). -
Fewer: a curried closure over the rest.
tabulate identpassesfn y -> ident(y) end;map (plus 2) xspassespluswith2bound once and the second argument open. An erased argument is dropped here too, solength Natis a one-argument closure. -
More: the call, then
.()for each extra argument, since the result is a function value.
A body with fewer λs than its type has Πs is applied to the binders it does not name: def adder : run Π (n : Nat) → Π (m : Nat) → Nat := plus emits def adder(x0, x1) calling plus(x0, x1).
The C backend has no closures. An unapplied lambda, a definition passed as a value, and a call of a local function are refused there (c:lambda). The JavaScript backend emits those as closures. A unary wrapper that only forwards its argument is the function it calls, so tabulate ident passes ident. map (plus 2) stays (m) => plus(n, m). The definition itself stays one function of its live arguments.
Host data
A repr states the host shape of a data type. mix muro.emit then writes decode_<type>/1, decode_<type>/2, and encode_<type>/2 in the same module as the run functions. Decode takes an Elixir term and returns {:ok, value, table} or {:error, {path, reason}}. decode_<type>/1 starts from an empty name table. decode_<type>/2 starts from the table the host passes. Encode takes (value, table) and returns the host term. There is no arity-1 encode. A book with no repr emits the same text as before. --backend fsm calls decode_<type>/1 for a payload that has a repr and drops the table. --backend js writes decode_<type> and encode_<type> in that module. Decode returns {ok: {value, table}} or {error: {path, reason}} and does not throw. One argument starts from an empty name table. Encode takes the value and the table and returns {ok: wire} or {error}. A book with no repr emits no codec. A session whose payload type has a repr is still omitted. The runs and the codecs are written. The stepper does not call the codecs. Rust, Zig, asm, OTP, and --node ignore a repr. C writes no codec. A session payload whose type has a repr is refused (c:session).
The vocabulary and the strictness rules are Host representations.
What emit is not
It does not type raw Elixir. A run emit omits spec and evidence. --backend otp and --node are separate files, one for a conformance and one for a cross, and neither file is a run term. It does not turn a Stream that is only evidence into Stream. It does not use Nx.Defn.
If you want a book in the test suite, parse/check/emit it from test/muro_check_test.exs. The canonical book Muro.Example.book/0 must stay in sync with examples/half_ok.muro and agda/Muro/Example.agda.
mix muro.emit prints a module. It does not choose a path under lib/, format with the project’s .formatter.exs, or record which book the file came from. Committed modules is that step.
ExUnit
--backend exunit prints one ExUnit module for the book’s closed equations, the same text as Muro.emit_exunit/3. The test module is the file stem plus Test (rounding.muro prints RoundingTest). The implementation it calls by default is the stem (Rounding). Skipped equations go to standard error, then a line N tests, M skipped. Standard output is only the module. --node with this backend is refused.
This backend and --backend pytest accept a file whose params are not supplied. They check them as assumptions. Elixir, C, Rust, Zig, JavaScript, assembly, OTP, and --node still refuse that file with param <name> is supplied by a file that imports this one.
--imports is valid with --backend exunit and --backend pytest. It also collects the closed equations of the files the book imports directly. With any other backend it is an error: --imports is only valid with --backend exunit or --backend pytest. Absent, the suite is this file only.
The tests call an implementation the host names. Closed equations as tests is the collection, the behaviour, the adapter, param libraries, imported equations, and the skip list. mix muro.gen writes the same suite when an entry sets kind: :exunit. imports: true on that entry is --imports.
Pytest
--backend pytest prints one pytest module for those same equations, the same text as Muro.emit_pytest/2. The implementation it calls by default is the file stem (rounding.muro calls rounding.round). --impl MODULE bakes another Python module into the file. MURO_IMPL_<STEM> selects a module when the tests run, and the file does not change. A skip is a pytest.mark.skip test. Skipped equations go to standard error, then a line N tests, M skipped. Standard output is only the module. --node with this backend is refused. mix muro.gen writes the file when an entry sets kind: :pytest.
Pytest is the value encoding, the identifier fold, and how the implementation is chosen.
Next: Closed equations as tests.
Source on GitHub
· fetched from murolang/muro manual/