Functions

Moth functions use named declarations rather than anonymous closures or general function values. A signature records each parameter's type and access mode, then lists every success and error return or the whole Never contract -> !.

Calls stay local and explicit. The source shows named arguments, mutable access and failure propagation where they occur.

Choose the explanation level: Function declarations

Function declarations

A function gives a reusable block of code a name.

greet |name String|:
    io.line([: Hello, [name]])
;

The function name comes first. Parameters live inside |...|.

Use || when there are no parameters:

say_hello ||:
    io.line("Hello")
;

Add an arrow when the function returns a value:

double |value I32| -> I32:
    return value * 2
;

Write -> ! when the function never returns:

fatal |message String| -> !:
    assert(false, message)
;

That spelling is a whole return contract, not a type. See Function declarations advanced for the full rules.

The colon opens the body. The semicolon closes it.

A source function forms a named top-level declaration.

greet |name String|:
    io.line([: Hello, [name]])
;

double |value I32| -> I32:
    return value * 2
;

Declaration shape

name |parameters|:
    body
;

name |parameters| -> ReturnType:
    body
;

name |parameters| -> !:
    body
;
  • The function name comes first.
  • Parameters are enclosed by |...|.
  • || declares a function with no parameters.
  • -> introduces the return contract: ordinary success and error slots, or the whole Never contract -> !.
  • Omit the arrow only when the function has no return slots at all.
  • A function with only an error slot still writes -> Error!.
  • -> ! is mutually exclusive with every success, optional and error slot.
  • Void is not written as a return type.
  • : opens the body and ; closes it. An inline body closes on the line containing its :. A multiline body closes with ; alone on its own line.
  • Function names use regular_snake_case.

Scope placement follows Blocks and statements.

Functions with required success values must return or otherwise terminate on every reachable path. Terminality is validated before HIR lowering.

The absence of an error slot does not make private numeric work infallible. Private functions infer and propagate implicit numeric failure within the same module without postfix ! at each internal call. Exported callables without an error slot must discharge it. See Returns and multiple values and Progress for the contract and current support.

Parameters and return slots use exact declared types. Body-local numeric inference never changes a signature or public interface. Numeric literals owns the permitted receiving contexts. Generic signature relationships follow the separate bounded rules in Generics.

Const functions

A const function declares that every call is executed by the compiler and never receives a runtime body.

double #|value I32| -> I32:
    return value * 2
;

label #= [: result [double(21)]]
  • The # between the name and parameter list marks required compile-time evaluation.
  • Every argument must be a compile-time constant.
  • Const functions admit immutable ordinary-value parameters and one ordinary success slot in V1. Mutable references, fallible return channels, receiver methods and recursive dependency cycles are rejected.
  • A call in an ordinary function is folded during compilation. A call that cannot be evaluated is a source error rather than a runtime fallback.
  • Invalid const operations, unresolved runtime arguments and nonterminating dependency cycles report the source call site.
  • A const function with no calls is still type-checked and checked for static eligibility, but its parameterised body does not execute.

Release builds additionally fold ordinary functions whose whole transitive body proves const-safe and whose call arguments are known constants. This is an optimisation only: a refused or budget-limited call remains a runtime call, and required const calls still report errors. Release budget advice is a Note, not a failure. It names the setting to raise for a configurable limit, and asks for a simpler call when a fixed compiler safety limit is hit.

Never return contract

A callable that never returns control normally declares one whole return contract:

fatal |message String| -> !:
    assert(false, message)
;

serve || -> !:
    loop true:
        io.line("ready")
    ;
;

The bare ! sits immediately after ->. It is not a type, a suffix on a type or a reserved keyword. It cannot mix with ordinary return slots:

-- Invalid: Never mixed with a success slot
bad || -> String, !:
;

-- Invalid: Never mixed with an error slot
bad || -> Error!, !:
;

-- Invalid: Never followed by another slot
bad || -> !, String:
;

-- Invalid: Never combined with `!` error syntax
bad || -> !!:
;

Keep T! as the final error slot of an ordinary return contract.

A -> ! body is valid only when every reachable path after known-Bool specialisation diverges. These exits do not satisfy Never:

  • falling off the end of the body
  • ordinary return, including a bare no-value return
  • return!
  • postfix ! or ? that returns an error or absence to the caller
  • a branch that can complete normally
  • a loop that can leave through a reachable break targeting that loop

Divergence is proved through false assertions, standalone Never calls, normalised-true loops with no reachable self-targeting break, lexical scopes, branches and exhaustive matches. A recursive -> ! group cannot use its own unvalidated contracts as proof. Collection and range loops stay conservatively finite.

An unannotated user function whose specialised body always diverges is rejected. Write -> ! when never returning is the intended contract, or write the ordinary return type the body is expected to produce later. An explicitly typed ordinary function may currently diverge without becoming Never to its callers. The compiler-owned entry is exempt.

Implicit built-in failure that would escape a -> ! body is a closed-boundary diagnostic. Handle it locally. A Never call has no error or optional value to propagate.

The contract is exact on every callable surface: functions, receiver methods, generics, traits, exports and binding-backed signatures. A body that happens to diverge does not match -> !, and -> ! does not satisfy an ordinary return contract. Changing a public callable between ordinary returns and Never is a public semantic change.

See Calls and access for standalone-only placement, Returns and multiple values for the distinction from no-value completion, and Progress for current proof coverage.

Generic functions

Declaration-site generic parameters appear after the function name.

identity type A |value A| -> A:
    return value
;

Generic inference and bounds are documented by Generics.

Function values

Source functions are named declarations and cannot currently be used as ordinary values. General closures, anonymous function values, generic function values and higher-order polymorphism are outside scope. A narrower future design for references to named, monomorphic, non-capturing functions remains an open design question and has no current syntax or implementation commitment.

Choose the explanation level: Parameters and defaults

Parameters and defaults

Parameters describe the values a function needs.

greet |name String, excited Bool|:
    if excited:
        io.line([: Hello, [name]!])
    ;
;

Each parameter has a name and a type.

A default makes a parameter optional at the call site:

describe |prefix String = "item", subject String| -> String:
    return [prefix, ": ", subject]
;

label = describe(subject = "apple")

The call supplies subject by name and keeps the default prefix.

Ordinary calls, including empty f(), keep their normal syntax. Directive calls share the same argument rules but reject an authored empty ().

Every ordinary function parameter has a name and an explicit exact value type or parameter capability contract.

describe |prefix String, subject String| -> String:
    return [prefix, ": ", subject]
;

Parameter forms

name Type
name ~Type
name Type = default
  • name Type declares a shared parameter.
  • name ~Type declares a mutable or exclusive parameter.
  • = default provides a value when the caller omits that slot.
  • Parameter names follow the no-shadowing rule.
  • Each parameter name must be unique in the signature.

Wire of T and the zero/one-input Route of ... forms are separate parameter contracts, not ordinary wrapper types or mutable access modes. They have no defaults and $ supplies no parameter mode. Their exact receiving and forwarding rules belong to the Wiring reference.

Directive calls share the ordinary argument parser and slot routing. Ordinary f() remains valid. Only directive syntax rejects an authored empty ().

Defaults

A default belongs to the declaration.

describe |prefix String = "item", subject String| -> String:
    return [prefix, ": ", subject]
;

A caller can omit a defaulted parameter.

Named arguments can skip an earlier default:

label = describe(subject = "apple")

A positional call cannot skip a slot in the middle. Use a named argument when the call needs to reach a later parameter.

Default value constraints

A parameter default must be a compile-time value.

Accepted:

DEFAULT_PREFIX #= "item"

describe |prefix String = DEFAULT_PREFIX, subject String| -> String:
    return [prefix, ": ", subject]
;

Rejected:

  • runtime bindings
  • runtime function calls
  • references to other parameters

Struct fields share the same = default syntax, but struct defaults have their own compile-time rule. Choice payload fields do not support defaults.

Pipes declare parameters or typed fields. Supplied values use MON syntax. An anonymous const record requires an initializer for every field and declares no constructable type. Its entries are values, not parameters or defaults. See Const records.

Declaration lists remain flat. Nesting a legal value expression in a default does not introduce a nested type declaration or make an anonymous record compatible with a named parameter type.

MON data boundary

Source parameter defaults above are unchanged. MON schema defaults are a separate serialised-data contract documented by reference: defaults are prevalidated data applied only at the exact missing field, a supplied none is validated as none and never replaced, and a supplied nested record is never deep-merged with a default. Only an explicit field default permits omission, and choice payload fields still have no defaults. That contract is Rust-only serialised-data documentation. See MON format and Options.

Choose the explanation level: Calls and access

Calls and access

Call a function by writing its name followed by arguments.

result = double(21)

Arguments are positional by default. They can also name their parameter:

label = describe(subject = "apple")

Positional arguments come first. Named arguments come afterward.

Mutable parameters need explicit access to an existing mutable value:

count ~= 1
increment(~count)
increment(value = ~count)

For a named argument, put ~ before the value. Fresh values and independent copies don't use ~:

increment(1)
increment(copy count)

Ordinary function calls keep their usual syntax, including empty f(). Directives share the call rules but reject an authored empty (); see Calls and access advanced.

A -> ! function can only be called as a statement. It cannot be assigned, passed as an argument or handled with !, ? or catch.

Function calls use positional arguments, named arguments or both.

render_card(title, body)
render_card(title = title, body = body)
render_card(title, body = body)

Argument routing

  • Positional arguments must come before the first named argument.
  • A positional argument is invalid after a named argument.
  • A named argument must match a real parameter name.
  • Each parameter may be supplied once.
  • Omitted defaulted parameters use their declared default.
  • Every non-defaulted parameter must receive an argument.
  • Extra positional arguments are invalid.
  • Argument values are checked against concrete parameter types. Eligible raw numeric origins can materialise at that exact receiver before fallback; already typed values still require exact compatibility.

Named arguments can skip earlier defaults.

User functions, struct constructors, choice payload constructors and source-authored receiver methods share this routing policy.

Host functions and compiler-owned builtin member calls are positional-only.

Implicit failure at calls

A private function without an error slot can infer and propagate checked numeric failure within the same module. Its internal callers need no postfix ! for that implicit failure; the enclosing handler or function contract delivers it. This does not remove postfix ! from explicit typed error propagation. Exported signatures stay closed and must discharge failure or declare a compatible error slot. See Returns and multiple values for the contract.

Never calls

A call whose declared contract is -> ! is valid only as a standalone statement:

fatal |message String| -> !:
    assert(false, message)
;

fatal("unreachable")

It may appear wherever an ordinary executable statement is legal, including branches, loops, lexical scopes and root runtime work.

It is invalid in every value-consuming position:

-- Invalid: Never call used as a value
value String = fatal("x")
return fatal("x")
consume(fatal("x"))
if fatal("x"):
    io.line("unreachable")
;

The same restriction applies inside arguments, operators, constructors, casts, templates, collections, maps, conditions and assertion arguments.

A Never call cannot be followed by postfix !, postfix ?, catch or member continuation. It has no success, error or optional value to handle.

A standalone Never call may complete one branch of a block-form value producer because that branch diverges rather than producing a value. The inline then/else form remains invalid because it places the call in a value slot. See Value-producing if.

Never calls use the ordinary argument grammar.

Shared MON syntax

MON syntax names the shared parenthesised argument and value-construction notation. The accepted record and directive integrations use one argument parser with context-specific policies.

Calls route supplied values into a declared signature. Anonymous records require named fields and have no callee signature or omitted defaults. Sharing syntax does not enable record spreading, structural conversion or new runtime uses of const records.

Directives use the same ordinary call parser, parameter-slot router and default validation as functions. Ordinary f() remains valid. A directive's entry syntax rejects an authored empty (), even when every parameter has a default. Directive values retain their compile-time and specialised category rules.

Shared parameters

A shared parameter receives an ordinary argument without ~.

show |value String|:
    io.line(value)
;

show("hello")

Passing ~value to a shared parameter is invalid.

Mutable parameters

An existing mutable place needs explicit ~ at the call site.

increment |value ~I32|:
    ~value += 1
;

count ~= 1
increment(~count)
increment(value = ~count)
increment(copy count)

Passing an existing place without ~ to a mutable parameter is invalid. An immutable place can't grant mutable access. For named arguments, put ~ before the value, not the parameter name.

A fresh rvalue can satisfy a mutable parameter without source ~:

increment(1)

Literals, templates, constructor calls, computed values and legal copy expressions are fresh. Writing ~ on them is invalid because ~ is place-only access syntax. See Progress for target support.

Binding mutability and call-site access are separate. See Mutable bindings.

Choose the explanation level: Returns and multiple values

Returns and multiple values

Use return to send a value back to the caller.

double |value I32| -> I32:
    return value * 2
;

A function can return more than one success value:

pair || -> String, I32:
    return "Priya", 2
;

name, count = pair()

The number of receiving names must match the number of returned success values.

Prefix a receiving name with ~ to update an existing mutable binding. Leave new receiving names unmarked, for example ~count, message = next().

A function with no success values may fall through. That is not the same as -> !, which means the function never returns at all.

Functions that can fail add one final error return marked with !. The Errors page explains how to propagate or recover from that path.

return produces the success values declared by a function.

double |value I32| -> I32:
    return value * 2
;

Success returns

  • Return values must match the declared success-slot count.
  • Each return value must be compatible with its corresponding slot type.
  • A function with required success values must return or otherwise terminate on every reachable path.
  • A function with no success slots may reach the end of its body.
  • return with no values can leave a no-success function early.
  • Void is not an explicit return-slot type.
  • Ordinary no-value completion is not Never. A function that omits -> may fall through. A function declared -> ! cannot.

Return slots are exact receivers for eligible numeric origins in the function body. They cannot retag an already concrete operation or infer named operands backwards. Completed function signatures and public interfaces contain no pending numeric identity.

Never versus ordinary returns

Three contracts are distinct:

  • Omit -> for ordinary no-success completion. The function may reach the end of its body or use a bare return.
  • Write an ordinary return type, including a temporary placeholder such as -> String, when callers should still see that type. The current body may diverge without becoming Never to those callers.
  • Write -> ! only when the callable never returns control normally.
greet |name String|:
    io.line([: Hello, [name]])
;

load_name || -> String:
    assert(false, "not implemented")
;

fatal |message String| -> !:
    assert(false, message)
;

Only the explicit -> ! contract propagates divergence across a call. Callers of load_name still see an ordinary String result. See Function declarations for body validation and Calls and access for placement.

Multiple success values

A function may declare and return more than one success value.

pair || -> String, I32:
    return "Priya", 2
;

name, count = pair()

The receiving multi-bind must match the success arity.

Each target independently declares a new binding or updates an existing place. An update requires a leading ~ on that target:

next || -> I32, String:
    return 1, "ready"
;

count ~= 0
~count, message = next()

An unmarked target must name a new binding. A prefixed target must name an existing mutable binding. New mutable targets retain the explicit-type form, such as count ~I32, message String = next().

The producer runs once and all incoming results are read before any existing target is written. Updates through mutable aliases write through to their referents. These receiving rules also apply to value-producing if, match, catch and propagated multiple-result calls.

Multi-bind targets may continue on a following line only after a comma:

name,
    count = pair()

A comma promises another target, so a trailing comma before = is invalid. This is the same continuation rule used by delimiter-free dependency selections. Delimited collections and call arguments keep their own list grammar.

Multi-bind targets are runtime bindings. A # compile-time marker is invalid on every target, new or existing, so name #, count = pair() and name #String, count = pair() are rejected.

Multiple return values are not a user-visible tuple value. A normal single-target declaration cannot receive a multi-return call.

Value-producing if, full matches and catch blocks can also satisfy multi-value receiving sites when every producing path has the required arity.

Error slot shape

A function signature may contain at most one error-channel slot marked with !.

That slot must be last.

load |id String| -> String, Error!:
    if id is "":
        return! Error("Missing id")
    ;

    return "value"
;

return!, postfix propagation and catch are documented by Errors, options and assertions.

Checked numeric failure is implicit built-in failure, not an undeclared custom error slot. Private functions without an error slot infer and propagate it within the same module, without postfix ! at each internal call. Built-in Error! materialises that failure. A custom E! function must recover locally or map it explicitly.

Exported callables have closed error contracts. An exported callable without an error slot must discharge implicit failure or receive a compiler diagnostic. Traits and generic conformance cannot secretly widen that signature. The compiler-owned entry has built-in Error!; compatible top-level postfix ! is legal, while custom errors still need explicit recovery.

Return contract

Return slots contain types and channels only. Source code has no borrowed, owned, move or parameter-alias return annotation.

Returning an existing value follows ordinary shared-reference semantics. The compiler infers freshness and alias effects from validated bodies and calls. Public interfaces preserve those inferred relationships. External bindings may declare equivalent alias behaviour because their foreign bodies are unavailable.

Binding freshness and allocation identity

Every function result enters a fresh caller binding. This does not imply a fresh allocation. Returning an existing record, collection, map, string allocation, opaque handle or projection preserves its allocation identity and lifetime owner. The result binding never points at the callee's parameter or local binding slot.

Reassigning one binding does not rebind another binding that received the same allocation through a return. The allocation remains alive while any legal alias retains it.

Ordinary return does not copy. Use copy when the caller needs an independent result graph.

Inferred alias relationships govern borrow and lifetime validation without changing the source type.

External alias metadata describes whether a foreign result aliases an argument allocation. It does not expose binding references to source code and does not allow host code to return a Moth binding cell.

Fallible and multiple returns

Fallible success values may alias a parameter allocation. Multiple return values may alias parameters or each other. Each returned value enters its own caller binding, defined only on the successful path. The separate error channel defines no success value on failure. Any physical result carrier belongs to the target ABI and proves neither fresh allocations nor disjoint results. Runtime lowering preserves those allocation relationships.