muro-lang.dev / docs
Go
In brief: mix muro.emit path.muro --backend go writes <stem>.go next to the book and prints that path. The file is one package. It contains the session machines, one monitor per choreography, one dispatcher per keyed family, one per-key monitor per family of a choreography, and the book’s run functions and data declarations. The machines are the ones --backend fsm prints. The runs are the closed run image. A book with no session, no choreography, and no run is refused with <file> has no session to emit. A book of runs is the file on its own.
The file imports only the standard library. A session file imports errors and fmt, and sort when a family or a per-key monitor needs it. A run of Nat also imports math/big. A string length also imports unicode/utf8. It has no init function and no mutable package state. A refused step returns an error. A run returns the value and an error. It does not panic. The first line matches ^// Code generated .* DO NOT EDIT\.$, so go tools treat the file as generated.
mix muro.emit examples/ping.muro --backend go
mix muro.emit examples/ping.muro --backend go --package host
Muro.emit_go/2 writes the same file and returns {:ok, [path]}. mix muro.gen writes it when an entry sets kind: :go. The target ends with .go and names no module. The gen header sits above the generated line. Both name the book. The body is the emitter’s text, and it is not formatted by Mix.
Package and names
--package NAME is valid only with this backend. NAME matches ^[a-z][a-z0-9_]*$ and is not a Go keyword or a predeclared identifier. Anything else is go: package name. Absent, the package is the book stem: lowercased, a character outside [a-z0-9_] replaced by _, repeats collapsed, and a leading digit or an empty stem prefixed with p_. A keyword or a predeclared name gains _k. keyed-slots.muro is package keyed_slots. any.muro is package any_k.
Every package-level name the file will emit is claimed in one pass before the text is written, and the file is rendered from those spellings. A second claim of the same spelling is Name_2. The claim order is sessions, keyed families, choreography monitors, a family of a choreography, then the match functions, then the run image: data types, constructor structs, constructor functions, the runs, and an atom constructor after the runs. Within one of those, the type is claimed, and every other package-level spelling is derived from that claimed type. Step and String are methods. An exported run is CamelCase. run internal is that spelling with an unexported muro prefix, so step is muroStep. Nat, Unit, Pair, and Opt in a run are MuroNat, MuroUnit, MuroPair, and MuroOpt, and the session constructors Nat and Unit stay. A run named error, string, or unit beside a session is Error_2, String_2, or Unit_2.
An exported type is the source name in CamelCase, split on characters that are not letters or digits. An empty name is X. A name that starts with a digit is prefixed with X. Go keywords, predeclared identifiers, and the names this file defines (Send, Recv, Value, String, Error, the error types, the family phases, and the helpers) are in that set, so a session named Send is Send_2 and the event type stays Send. A session ping followed by ping-state keeps the type Ping and the state type PingState. The later session is the type PingState_2, the constructor NewPingState_2, and the state type PingState_2State. A session new-slots in a book with the family slots is the type NewSlots and the constructor NewNewSlots. The family constructor is NewSlots_2. A constructor parameter is claimed against that set, then against earlier parameters. A character outside letters, digits, and _ becomes _, so Nat is Nat_2, string and nil are string_2 and nil_2, and a-b followed by a_b is a_b then a_b_2.
What the file contains
A session is a struct. NewPing returns the value at its first step. A session with parameters returns (T, error). A negative argument is ArgumentError, and errors.Is matches ErrArgument. The zero value is not started: State is invalid, Expected is "start", and Step returns an error. Step is a method on the pointer. On error the value is unchanged. Done reports the end. Expected names the next event ("recv nat", "send nat", "send pick", "done").
Event is an interface with an unexported method. Only Send and Recv implement it. Each carries a Value. Constructors are Unit, Nat, Bit0, Bit1, Pick0, Pick1, Con, Pair, Record, and Vec. Record sorts fields by name. A value that does not match the protocol is refused by Step, and the value stays where it was. A quiet jump is not that refusal: when an actual of a jump to this same session does not produce a nat, Step returns nil and the state is stuck. A jump whose number of actuals is not the number of parameters sticks the same way. A book that marks a party also has Down. The reason is *Value, and nil is an arm that binds no reason. A failure arm of finish is done. A failure arm of leave is stop. Any other failure arm is refused before a file is written: go: failure arm continues the protocol. A book that does not mark a party emits no Down.
A choreography with no per-key family is one monitor value. NewPlan returns it. Step(from, to, label, v) takes the next message. A message with no payload takes Unit(). Choose(role, label) takes the next choice. Expected is "message from to label" or "choose role a|b".
A family of a choreography is a pointer. StepShared and ChooseShared take the shared preamble, once. Step and Choose then take one key. A key step during the preamble is refused, and Expected on that error starts with "shared ". SharedDone reports the preamble. Done(key) reports one key. Keys returns the keys that have stepped, sorted.
A keyed family is a pointer from NewSlots. The methods are Arrive, Resolved, Withdraw, WaitingOn, Snapshot, Skip, DropKey, SkipBelow, Revert, Rerun, Finish, View, Floor, Departed, and Live. They are the decisions Muro.Family.Step runs, including held while earlier unresolved, held while any unresolved, held while <kind> unresolved, held until <kind> resolved, a comma list, and a repeated held. Arrive returns the phase and the id. On error the id is -1 and the dispatcher is unchanged. Resolved and Withdraw return the rows that moved from held to open, sorted by creation index then id. WaitingOn returns the kind names and the ids that still block a held row. Snapshot returns every retained row in creation order as []SnapshotRow, sorted by ascending id. Phase on that row is open, held, resolved, or withdrawn. WaitingOn on the row is set only while the phase is held, and it is a SnapshotWait of Kinds and IDs. A nil receiver and a state the method cannot read are ErrBadState, and the dispatcher is unchanged. An empty dispatcher returns a non-nil empty slice. SkipBelow raises one floor for every key. An index at or below the floor has departed, including a first arrival. Departed(key) reports the packed prefix and the gaps. A missing key is prefix -1, no gaps, and false. A second arrival of a departed pair is ErrDeparted. Finish(id, sessionDone, outcome) resolves or reruns an open row after the host says the meeting session is done. It does not step that session. sessionDone == false is ErrUnfinished. OutcomeResolve and OutcomeRerun are the two outcomes.
Revert is always emitted. On a family marked may revert it puts a resolved row back to open when no open or resolved row of the same key holds it. An unmarked family returns ErrUnmarked and does not read the row. A kind marked , never reverted returns <Name>ErrOneWay before that hold check. The sentinel’s text is muro: one way, and it unwraps to ErrFamily. The row stays resolved. A family with no such kind emits neither the sentinel nor the check. may redeliver is a comment on the type. It is not a method. contract declarations are not checked in this file. The state machine’s external-contract lines stay on mix muro.check.
A family step that belongs to the family, not to a key, is a once step. released once has no hold: it is open from the start, and worker held until released resolved stays held, with WaitingOn naming released, until ResolveOnce resolves it. publish once, held until worker resolved for every key is held until the key set is closed and every member key has resolved worker. The ids of the steps are the constants RolloutOnceReleased, RolloutOncePublish, and so on, in declaration order, and rows are numbered after them. A once step is not a RolloutKind, so Arrive never takes one. The decisions are those of Muro.Family.Step. Arrival after both a departure and a close is ErrDeparted in Muro.Family.Step and in Go, and :closed in the --backend fsm dispatcher.
ResolveOnce(id) resolves an open once step and returns the rows that opened because of it, key by key in sorted order; the step is not in that list. Resolved(id) takes a step id too. A step that is held is ErrHeld, one that is resolved is ErrResolved, and an id that is not a step is ErrUnknown from ResolveOnce. A family with a held step also has CloseKeys, WaitingOnce, and a DropKey that returns the steps it opened. CloseKeys closes the key set and returns the steps that opened, which is every held step when the set is empty or every member has resolved its kind. A second call changes nothing, and there is no reopen. After the close, Arrive of a key that never arrived is ErrClosed, and a key that already arrived may still arrive. A key is a member from its first arrival until DropKey. DropKey of the last key that had not resolved a step’s kind opens the step. Once a held step is open or resolved the key set is frozen, and DropKey does nothing. WaitingOnce(id) returns whether the set is closed and the member keys, sorted, that have not resolved the kind; an open step is ErrOpened and a resolved one is ErrResolved. WaitingOn(id) of a held step returns the kind it waits on and no ids. A family with no held step keeps DropKey(key) error and has neither CloseKeys nor WaitingOnce. Snapshot lists each once step as a row with Once set, Key "once", Index 0, and the step name as Kind; a held one has WaitingOn.Closed and WaitingOn.Keys. Released carries Once the same way.
On a family marked may revert, Revert of a resolved once step with no hold returns ErrOpened while it is open, ErrHeldBy with the ids while a row of any key that waits for it is open or resolved, and <Name>ErrOneWay when it is marked , never reverted. Reverting a resolved row of the kind a held step waits on is ErrHeldBy while that step is open or resolved, with the step’s id first. A held once step does not revert: its id is ErrUnknown.
The kind is type SlotsKind uint8 with one constant per constructor, in declaration order. The first constructor is iota 0. More than 255 constructors and once steps combined is go: unsupported family. Phases of a live or retained row are PhaseOpen, PhaseHeld, and PhaseResolved. Snapshot spells withdrawn as a string. It is not one of those constants, and View does not return a withdrawn row.
A session state and a monitor state are uint8 as well. The session constants are invalid, one per action, done, stuck, and stop when a failure arm is leave. The monitor constants are invalid, one per interaction, and done. uint8 holds iota 0 through 255. More than 256 constants is refused before a file is written, and the count in the error is that total. The largest send chain is 253 actions. 254 actions is go: unsupported session (257). The largest message choreography is 254 interactions. 255 interactions is go: unsupported choreography (257).
Errors
IllegalTransitionError has Machine, State, Expected, and Event. Error() describes the refusal. Unwrap returns ErrIllegalTransition, so errors.Is and errors.As both match. A nil receiver and a zero value are that same error.
FamilyError has Code, Key, Index, ID, Kind, and IDs. Unwrap returns the sentinel, and that sentinel unwraps to ErrFamily. errors.Is(err, ErrDuplicate) and errors.Is(err, ErrFamily) both hold. The sentinels are ErrDuplicate, ErrDeparted, ErrUnknown, ErrHeld, ErrOpened, ErrResolved, ErrWithdrawn, ErrHeldBy, ErrLive, ErrKind, ErrBadState, ErrIndex, ErrUnmarked, ErrUnfinished, and ErrClosed. A field that does not apply is the zero of that field, and an unused id is -1.
An excerpt
examples/ping.muro begins:
// Code generated by muro 0.24.5. DO NOT EDIT.
// Package ping is a session, choreography, and keyed-family image.
// Callers own each value. One session, monitor, or dispatcher is not
// safe for concurrent use: synchronize, or give each goroutine its own value.
package ping
import (
"errors"
"fmt"
)
// ErrIllegalTransition is the sentinel for a refused step.
var ErrIllegalTransition = errors.New("muro: illegal transition")
// IllegalTransitionError is a refused step. Unwrap returns ErrIllegalTransition.
type IllegalTransitionError struct {
Machine string
State string
Expected string
Event string
}The session itself:
// Ping is one end of session ping.
// The zero value is not started: Step and Down report an illegal transition.
// Ping is not safe for concurrent use.
type Ping struct {
state PingState
ready bool
env map[string]Value
}
// PingState is the resting position of Ping.
type PingState uint8
const (
// PingStateInvalid is the zero Ping.
PingStateInvalid PingState = iota
// PingStateRecv1 is examples/ping.muro:5 session ping: first recv Nat.
PingStateRecv1
// PingStateSend1 is examples/ping.muro:5 session ping: first send Nat.
PingStateSend1
// PingStateDone is the end of the session.
PingStateDone
// PingStateStuck is a protocol position with no step.
PingStateStuck
)
// NewPing starts Ping at its first step.
func NewPing() Ping {
return Ping{state: PingStateRecv1, ready: true, env: map[string]Value{}}
}
// Step takes one send or receive. A refused step leaves the value unchanged.
func (m *Ping) Step(ev Event) error {
if m == nil || !m.ready {
return muroIllegal("Ping", "invalid", "start", muroEvent(ev))
}
switch ev := ev.(type) {
case Send:
return m.stepSend(ev.Value)
case Recv:
return m.stepRecv(ev.Value)
default:
return muroIllegal("Ping", m.State().String(), m.Expected(), muroEvent(ev))
}
}A host drives it:
m := NewPing()
if err := m.Step(Recv{Value: Nat(1)}); err != nil {
return err
}
if err := m.Step(Send{Value: Nat(1)}); err != nil {
return err
}
m.Done() is then true. A send at the first state returns *IllegalTransitionError and leaves m at PingStateRecv1.
Put the file in its own directory. The package clause is the import name.
go mod init example.com/ping
go vet ./...
gofmt -l .
go test ./...
gofmt -l prints nothing: the emitter writes the canonical form (tabs, aligned const blocks) and does not call gofmt, so two runs of the same book are the same bytes. go test -race needs cgo and a C compiler. The race detector is how a host checks the rule below.
Concurrency
A session, a monitor, and a dispatcher are not safe for concurrent use. The file has no mutex. Callers synchronize, or give each goroutine its own value. Two goroutines may each call NewSlots and Arrive on the value they own. Two goroutines that share one pointer take the lock themselves. go test -race on the live tests covers both arrangements. The mutex in that test is in the test file, not in the generated package.
What this backend refuses
The refusal is the whole file. Nothing is written.
| Reason | When |
|---|---|
<file> has no session to emit |
the book declares no session, no choreography, and no run |
go: repr payload |
a session payload type has a repr |
go: run case |
a case calls a run |
go: unsupported protocol |
a session jumps to a different session |
go: dual jump |
a jump the planner cannot place on one machine |
go: failure arm continues the protocol |
a may fail arm is neither finish nor leave |
go: unsupported payload |
a payload outside the values above |
go: unsupported family |
more than 255 constructors of the key and once steps together |
go: unsupported session (N) |
more than 256 session state constants |
go: unsupported choreography (N) |
more than 256 monitor state constants |
go: package name |
--package is not a legal package identifier |
go: lambda in <def> |
a run still has a function as a value |
go: stream in <def> |
a run is a stream, or consumes one |
go: machine in <def> |
a run uses F32, a tensor, addt, or packI |
go: erased in <def> |
a run reads an erased binder |
go: opaque in <def> |
a match needs a layout the image did not record |
go: unsupported in <def> |
a run the image does not lower, including a data type named Atom when the book also builds an atom |
| the state machine’s reason |
a protocol the planner already refuses (seen of a talk, an unguarded rec, a bound that is not a numeral) |
A meeting marked may fail is emitted when every failure arm is finish or leave. This backend does not answer c:mayfail.
Pure functions and data
A run is a function. Spec and evidence are omitted. run internal is unexported. A book that also has a session puts the runs after the machines, in one file. A book that is only runs is that file alone. A data declaration with no run is still <file> has no session to emit.
Nat is type MuroNat = *big.Int. The integer is non-negative and arbitrary precision, from math/big. A nil pointer or a negative integer is RunError with reason nat, and the argument is copied before arithmetic, so the function does not write the caller’s pointer. A Nat nested in a data field, a pair, or an Opt is checked at that same boundary. Nil or negative is RunError with reason nat. Unit is MuroUnit, an empty struct. Pair is MuroPair[A, B] with Fst and Snd. Opt is MuroOpt[T] with Ok and Val. The zero Opt is none. It is not a pointer, so none is not nil.
A data declaration is a sealed interface. The marker method is unexported, so a value from another package cannot implement it. Each constructor is a struct. Unnamed fields are F0, F1, in order. A named field keeps that name, exported. The constructor function returns the interface. A nil interface is RunError with reason tag. The interface is the same for an enumeration, an unboxed value, and a boxed declaration: a tag beside a bag of fields would admit a value no constructor built. A recursive field is the interface.
examples/tree.muro begins:
// Tree is data Tree, a sealed interface (boxed value).
type Tree interface {
isTree()
}
// TreeLeaf is the leaf constructor of Tree.
type TreeLeaf struct{}
func (TreeLeaf) isTree() {}
// Leaf builds the leaf constructor of Tree.
func Leaf() Tree {
return TreeLeaf{}
}
// TreeNode is the node constructor of Tree.
type TreeNode struct {
F0 Tree
F1 Tree
}
func (TreeNode) isTree() {}
// Node builds the node constructor of Tree.
func Node(p0 Tree, p1 Tree) Tree {
return TreeNode{F0: p0, F1: p1}
}
Size is func Size(t Tree) (MuroNat, error). nil is RunError.
A type parameter of a data declaration is a Go type parameter. Either[A, B] and Maybe[A] are that. A Type parameter of a run is any, so Π (A : Type) → Π (x : A) → A is func Id(A any, x any) (any, error). An index that is a Nat is not a Go type parameter.
U8, U32, U64, and I64 are uint8, uint32, uint64, and int64. WBool is bool. Wrapping add, sub, and mul use the bit pattern. Checked add, sub, mul, div, and rem return MuroOpt. Division by zero is none, and so is the quotient or the remainder of the I64 minimum and −1. / or % is not evaluated. A shift whose amount is nil, negative, or at least the width returns the saturated value and is not a host shift. toNat of a word is the unsigned residue, including I64 −1.
String is a Go string. A zero octet is allowed. strLen is the number of Unicode scalars. Slice and Bytes are []byte. A sub-slice past the end is nil. A byte past the end is none. The prefix before a byte is that prefix, or the whole slice when the byte is absent. The suffix after a byte is that suffix, or nil when the byte is absent. Concatenation copies. A combined length that does not fit in an int is nil. A fold walks a copy of the slice, so a capture of the original buffer keeps its header. An empty match returns RunError with reason empty.
Every run returns (T, error). RunError has Def and Reason. Unwrap returns ErrRun, so errors.Is(err, ErrRun) holds. Def is the Go function name.
n := big.NewInt(4)
h, err := Half(n)
Half is examples/half_ok.muro. h is 2. Half(nil) and Half of a negative integer are ErrRun, and they do not panic.
An atom the book builds is a sealed interface Atom, one empty struct per atom, when the book has no data declaration of that name. A data declaration named Atom together with an atom is go: unsupported in Atom.
repr codecs are not in this file. A session payload with a repr is still go: repr payload.
Checks
The unit tests read the text and need no go binary. The live tests compile the file. They replay the same traces the Elixir machines accept and refuse: illegal transitions that do not move, payload sessions, a parameterized constructor, a choreography monitor, a per-key monitor, every family rule above, and a seeded walk of forty steps. The run tests call the emitted functions on the same inputs the interpreter accepts, including Nat past the int64 range, words, strings, and slices. gofmt -l must print nothing. go vet must accept the package. go test runs the traces. When gcc or cc is on PATH, go test -race runs them again. When go version does not exit 0, or does not finish, the live tests skip with go is not available. The race half is skipped on its own when no C compiler is present, and go test still runs.
Those live tests are not on the CI runners yet. Adding Go there is a follow-up, and it needs a workflow change. A runner without go skips the live tests and runs the rest.
Source on GitHub
· fetched from murolang/muro manual/