Wiring

Wiring describes parameter contracts for binding identity and choice constructors. It does not create callbacks, subscriptions or a UI runtime.

A Wire preserves binding identity. A Route captures choice-constructor arguments for later completion. Neither introduces callbacks, subscriptions or implicit event delivery. See Wiring reference for the complete contracts.

Choose the explanation level: Introduction and detailed reference

Introduction and detailed reference

Wiring adds two parameter contracts. Wire and Route compile and run on the JS/HTML target. HTML-Wasm supports Wire arguments and rejects reachable route formation with a target diagnostic.

The word before of chooses the meaning of the following specification. These fragments show the syntax, not complete declarations:

Box of String
value Wire of String
submit Route of AppMessage

Box of String is an ordinary generic type application. Wire of String and Route of AppMessage describe contracts on function parameters. They are not runtime wrapper types, general values or constructor expressions.

Several Moth declarations use pipe-delimited lists, but their positions keep different contracts:

show |value String| -> String:
    return value
;

Point = |
    x I32,
    y I32,
|

Status ::
    Ready,
    Failed | message String |,
;

Function parameters receive call arguments. Struct fields describe named runtime value storage. Choice payloads describe immutable data carried by one variant. Similar list shapes do not make these positions interchangeable: Wire and Route contracts are parameters only, never fields or payloads.

Use the Functions, Structs, Choices and Generics references for those existing contracts. The detailed Wiring reference defines Wire and Route syntax, edge cases and the future channel boundary.

The receiving type must be immediate. The same boundary rule applies to ordinary generic calls, optional values and casts:

empty type Item || -> {Item}:
    return {}
;

items {I32} = empty()
maybe_name String? = none
wide I64 = cast 1

empty() needs a concrete collection type, none needs an optional type, and cast gets its target from the annotated receiving type. A later use cannot fill in missing evidence, and an outer function parameter does not infer a nested generic call. Annotate an intermediate value when needed. Wiring adds no general higher-order inference or retry rule. See Generic inference, Options and Casts.

Wiring: parameter contracts and constructor routes

This canonical reference owns the accepted Wiring syntax and observable semantics. It complements the ordinary function, generic, choice and binding references. docs/compiler-design-overview.md owns compiler-stage representation and handoffs.

Terminology and scope

A wire preserves a binding instance's continuing identity. A constructor route describes how future input completes a known choice constructor. A message remains an ordinary choice value. A channel transports ordinary values between async activities under its separately defined contract.

A route supplies no destination. Constructing a message, delivering it and sending it through a channel remain different operations. Wiring introduces parameter capabilities without general closures, source-visible reference types or a prescribed rendering architecture.

Head-directed of

The head before of determines the specification that follows:

Head

Specification

Meaning

User generic nominal, such as Box

Existing concrete type arguments

An ordinary specialised semantic type, such as Box of String

Wire

One underlying value type

A binding-identity parameter contract, such as Wire of String

Route

An output, or one input followed by -> and an output

A constructor-route parameter contract

Channel

One carried value type

The future channel construction contract described below

Wire and Route are compiler-owned heads under the ordinary reserved-name and collision policy. User declarations cannot override them or register new of grammars. Generic arity, inference, alias and nested-application rules remain unchanged. This syntax adds no explicit generic call arguments, higher-kinded types, type values or arbitrary inline nesting.

Use a named ordinary concrete alias when an underlying type needs a nested specialisation that the generic grammar rejects. A capability is not an ordinary type argument: Box of Wire of T does not create a wire container, and a route cannot become a collection element by applying of.

Parameter position and shared pipe shape

Wire and Route are parameter contracts. A pipe-delimited list does not imply a shared meaning across declarations:

show |value String| -> String:
    return value
;

Point = |
    x I32,
    y I32,
|

Status ::
    Ready,
    Failed | message String |,
;

Function parameters receive call arguments. Struct fields describe named runtime storage. Choice payloads describe immutable variant data. Wire and Route contracts are valid only on function parameters; they do not change field, payload, local, collection, alias or return-slot types. See the function, struct and choice references for those ordinary position contracts.

Wires

A source function parameter may require Wire of T:

read_name |value Wire of String| -> String:
    return value
;

forward_name |value Wire of String| -> String:
    return read_name(value)
;

name ~= "Priya"
label = forward_name(name)

The immediate receiving parameter chooses between an ordinary value read and identity forwarding. An ordinary T parameter reads the current value through normal access rules. A compatible Wire of T parameter preserves the same binding identity. Neither operation supplies exclusive mutation authority.

Eligible arguments

  • A named mutable or immutable local can acquire identity when a wire-receiving call demands it. No special declaration or call-site marker is needed.
  • An existing wire parameter can forward unchanged to a compatible wire parameter.
  • A field projection, collection lookup, literal, constructor call, function call, copy or computed expression cannot directly satisfy a V1 wire parameter. A #= constant is compile-time data, not a runtime binding, so it cannot either.
  • An ordinary value parameter does not preserve its caller's identity, so it cannot supply a wire. Inspecting that function's body cannot infer a wire contract for it.

Compatibility means the same underlying semantic type. A wire never applies an optional, numeric or other coercion, because the receiver would then read a converted value rather than the binding itself. Ordinary aliases of the underlying type name the same type.

Wiring an immutable local leaves it immutable. A mutable receiver or parameter still needs the ordinary exclusive authority. A wire supplies none.

Binding identity and reads

Identity belongs to the binding instance, not its current contents, allocation address or source position. Reassigning an eligible mutable local preserves that binding's identity. Repeated function calls or loop executions create distinct local instances wherever ordinary binding semantics do so.

Creating an ordinary local from a wire reads its value. Returning T read from a wire returns an ordinary value. Neither preserves a wire capability implicitly, and neither performs a deep copy. Aggregate reads can still create ordinary aliases under the existing access and lifetime rules. Use copy where an independent copy is required and the ordinary copy contract permits it.

Wire identity is not an active long-lived value borrow. Actual reads and captured values remain subject to borrow validation. Identity metadata cannot prove that storage outlives a consumer or legalise an escape.

There is no Wire() value constructor, wire(...) operation, <value>, <>value or $ wiring marker. Persistent observation, source-change callbacks, UI ownership and cross-task retention require separate contracts.

Constructor routes

The route contract allows zero or one future input:

on_click Route of FormMessage
on_input Route of String -> FormMessage
messages Route of EditorMessage -> AppMessage

Route of Message has zero future inputs. Route of Input -> Message has one. Multi-input route grammar remains unspecified. The route's arrow belongs to that parameter only. A function's ordinary return arrow follows the closing parameter list and keeps its existing meaning.

Immediate constructor context

Only an immediate route-receiving parameter permits a direct choice constructor to leave payload fields for future input:

FormMessage ::
    NameChanged | value String |,
    Submit,
;

TodoMessage ::
    Rename | id I32, value String |,
    Delete | id I32 |,
;

todo_id = 42

Expected contract

Argument

Future construction

Route of FormMessage

FormMessage::Submit

Construct the unit variant with no future payload

Route of String -> FormMessage

FormMessage::NameChanged

Future String supplies the sole payload field

Route of String -> TodoMessage

TodoMessage::Rename(todo_id)

Capture the ID now and fill the trailing String later

Route of TodoMessage

TodoMessage::Delete(todo_id)

Capture the ID now with no future payload

Captured arguments fill a contiguous leading payload prefix. Future input fills the remaining trailing fields in declaration order. Partial routes permit no holes, named omissions or arbitrary reordering. A fully supplied zero-input constructor can use ordinary complete-constructor argument rules, including legal named arguments.

The immediate receiving parameter is what permits a direct constructor to be partial. Outside that boundary, ordinary construction still requires every field:

on_rename |route Route of String -> TodoMessage| -> String:
    return "route received"
;

on_delete |route Route of TodoMessage| -> String:
    return "route received"
;

todo_id = 42
on_rename(TodoMessage::Rename(todo_id))
on_delete(TodoMessage::Delete(todo_id))

-- INVALID outside a Route receiving parameter: String is still missing.
message = TodoMessage::Rename(todo_id)

The root argument is a direct choice variant path/application or an unchanged compatible route parameter. Captures are ordinary expressions evaluated once when the route forms, in normal argument order and with normal failure and ownership rules. The route retains their resulting values, not executable expressions to rerun at a later event. Runtime captures remain runtime data even when the route signature and constructor are statically known.

Outside that receiving boundary, ordinary constructors still require all payload fields. message = TodoMessage::Rename(todo_id) lacks the String field and is invalid. A zero-input route using that same incomplete constructor is also invalid, since it has no future input to supply the missing field. No |>, angle-bracket or route expression form changes these rules.

Type identity and forwarding

Route contracts require exact input and output semantic types. Messages remain ordinary nominal choices without a Message base type or trait. The contract adds no variance, callable-trait solver or higher-order inference.

An ordinary generic helper can accept Route of String -> Message. A supplied constructor establishes the concrete choice output through existing immediate generic inference. It does not become a first-class function, and no distant body inspection supplies missing inference evidence.

A compatible route parameter forwards unchanged. For a choice variant declared with leading id I32 and trailing message EditorMessage, AppMessage::Editor(editor_id) can satisfy Route of EditorMessage -> AppMessage. This describes child-message lifting. Composing it with an input-to-child route is a separate design question, with no V1 application or composition syntax.

Messages remain ordinary choice values consumed by ordinary update functions. This self-contained message-handling example receives an ordinary choice value and does not use Wire or Route:

TodoMessage ::
    Rename | id I32, text String |,
    Delete | id I32 |,
;

update |state String, message TodoMessage| -> String:
    return if message is:
        Rename(id, text) => then text
        Delete(id) => then state
    ;
;

One child-to-parent Route can be forwarded through another compatible Route parameter. The partial parent constructor captures its leading editor_id; the future EditorMessage fills the remaining field:

EditorMessage ::
    Changed | value String |,
;

AppMessage ::
    Editor | editor_id I32, message EditorMessage |,
;

receive_editor |on_message Route of EditorMessage -> AppMessage| -> String:
    return "route received"
;

forward_editor |on_message Route of EditorMessage -> AppMessage| -> String:
    return receive_editor(on_message)
;

forward_editor(AppMessage::Editor(7))

Capability positions and lifetimes

Wire and Route contracts annotate parameters only. They do not annotate ordinary locals, fields, choice payloads, collection/map elements, capability aliases, defaults or return slots. Ordinary aliases may name their underlying value types under the existing alias contract.

A route cannot be stored, returned, compared, serialised or sent through a channel. A function name, closure, arithmetic expression or arbitrary block cannot replace a direct constructor argument. Routes have no general invocation or composition operation and introduce no implicit send or event registration.

Actual reads and retained captures obey ordinary alias, copy, access and lifetime-topology rules. Identity forwarding does not grant mutation, change allocation ownership or excuse a retained reference outliving its source. V1 introduces no external persistent consumer. Any later observer or event consumer needs its own explicit retention and lifecycle contract. Host garbage collection does not establish that a source escape is legal.

Plain, Wire and Route parameters remain distinct through exports, imports and generic specialisation. Matching underlying types never permit a module boundary to turn a wire into a snapshot or a route into an already constructed message.

Templates and runtime consumers

Templates produce ordinary String values. Returning, passing or assigning one carries no hidden wire, route, subscription or rerender recipe. Composition, control flow, slots, wrappers, formatting, folding and fragment insertion keep their ordinary contracts. Structural resource and site-root pieces retain their independent meaning until output placement supplies concrete characters.

The foundation covers synchronous reads, identity/route forwarding and captured constructor facts. A target can execute those operations only with faithful lowering. A reachable unsupported runtime capability receives a structured target diagnostic before lowering. Frontend acceptance alone does not promise executable UI behaviour.

Automatic observation, derived-state graphs, change handlers, two-way binding, live templates, route invocation, event queues, schedulers, mount lifecycles, rendering policy and channel bridges lie outside this foundation and require separate accepted contracts.

Channel boundary

The accepted channel construction form is:

reader, writer Channel of AppMessage = Channel()

The annotation supplies the carried type. Channel() receives that information from the immediate receiving contract, not a runtime type argument. The two results belong to one channel, reader first and writer second. They do not represent two independent channels or two bidirectional endpoints.

Explicit send transfers an independent graph under the async memory contract. Wire identity is not channel data, and route formation performs no hidden send. The channel construction form settles no endpoint-parameter grammar, buffering, cancellation, close, selection, suspension or host-event ingress rules.

Async operations, >>, <<, spawn, yield and structured $async: scopes belong to separate language contracts. Channel construction requires the initializer shown above.

Choose the explanation level: Wires

Wires

A Wire parameter asks the caller to preserve the identity of one named local binding. No special marker is written on the declaration or argument.

read_name |value Wire of String| -> String:
    return value
;

forward_name |value Wire of String| -> String:
    return read_name(value)
;

replace_name |value ~String, replacement String|:
    ~value = copy replacement
;

current_name ~= "Priya"
label = read_name(current_name)
~current_name = "Rob"
replace_name(~current_name, "Emmy")

The receiving parameter determines the use. Passing current_name to an ordinary String parameter reads its current value. Passing it to another compatible Wire parameter forwards the same binding identity. A Wire grants no mutation permission: replace_name has an ordinary exclusive parameter, so the call supplies ~current_name. By contrast, current_name ~= "Priya" declares a mutable binding and later ~current_name = "Rob" reassigns it. The binding declaration and exclusive call argument have different jobs.

The identity belongs to this binding instance, not its current text. Reassigning the mutable local keeps the same identity; a later function call or loop iteration has its own local instance. A temporary expression, literal, field or computed value cannot supply Wire identity directly.

#= does not declare a Wire or another runtime binding. A fully folded record stored in a named constant is compile-time data, not a runtime type declaration:

labels #= (
    first = "Priya",
    second = "Rob",
)

Read the ordinary value contract in Const records and the full binding-identity rules in the detailed Wiring reference.

See the Wires section of the detailed Wiring reference above.
Choose the explanation level: Routes

Routes

A Route parameter describes a known choice constructor and the payload it will receive later. Routes are parameter contracts, not callable values.

TodoMessage ::
    Rename | id I32, text String |,
    Delete | id I32 |,
;

offer_rename |on_rename Route of String -> TodoMessage| -> String:
    return "Rename route received"
;

offer_delete |on_delete Route of TodoMessage| -> String:
    return "Delete route received"
;

todo_id = 42
offer_rename(TodoMessage::Rename(todo_id))
offer_delete(TodoMessage::Delete(todo_id))

The first route has one future input, String; todo_id is captured now as the leading payload field. The second route has no future input and captures the complete Delete payload now. The receiving parameter is the immediate context that permits a constructor to leave fields for later input. An ordinary choice construction outside that context must provide every field.

Rows can use the same zero-input shape to retain their own item identity:

make_row_delete_offer |id I32| -> String:
    return offer_delete(TodoMessage::Delete(id))
;

Each call forms a route with that row's id already captured. A row loop can pass its current id to make_row_delete_offer; the example does not invoke the route, register an event or provide a UI callback. Those runtime operations are outside the accepted foundation.

Choice values still describe application state changes in the ordinary way. This self-contained message-handling example receives an ordinary choice value and does not use Wire or Route:

TodoMessage ::
    Rename | id I32, text String |,
    Delete | id I32 |,
;

update |state String, message TodoMessage| -> String:
    return if message is:
        Rename(id, text) => then text
        Delete(id) => then state
    ;
;

A child message can be lifted into one parent choice constructor by capturing a leading field:

EditorMessage ::
    Changed | value String |,
;

AppMessage ::
    Editor | editor_id I32, message EditorMessage |,
;

receive_editor_route |on_message Route of EditorMessage -> AppMessage| -> String:
    return "Route received"
;

forward_editor |on_message Route of EditorMessage -> AppMessage| -> String:
    return receive_editor_route(on_message)
;

forward_editor(AppMessage::Editor(7))

This uses one Route. It does not compose routes or call one from another. A compatible Route parameter can be forwarded unchanged; route invocation and composition remain unsupported.

See the Constructor routes section of the detailed Wiring reference above.
Choose the explanation level: Scope and channels

Scope and channels

Wiring contracts stay at function parameters. They cannot be stored in locals, struct fields, choice payloads, collections, aliases, defaults or return slots. An ordinary message remains a choice value.

Templates also remain ordinary String values. Composition, slots, wrappers, formatting and fragment insertion do not attach hidden Wire identity, Route application, subscriptions or rerender work.

Function bodies, branches and loops use statement blocks. A colon opens each block and a semicolon closes it rather than ending an individual statement. Statements run in source order until control flow exits or redirects the block, and each nested block creates a child scope. Moth has no general bare block for grouping statements.

greet |name String| -> String:
    if name is "Priya":
        return [: Hello, [name]!]
    ;

    return [: Hello, [name].]
;

The first semicolon closes the if block and the last closes the function. Inside each `

...

` template, square brackets build a String and the colon separates the template head from its body. That colon does not open a statement block. See the Blocks and statements reference and Template head and body.

Channel construction

reader, writer Channel of AppMessage = Channel()

The annotation supplies the carried type. reader and writer are directional endpoints of one channel. Channel transport, scheduling and cancellation are separate from Wiring. See Wiring reference for details.

See Capability positions and lifetimes and Channel boundary in the detailed Wiring reference above.