Casts

cast converts a value for an immediate concrete typed destination. Its target does not infer the source type, and constructor-like forms such as I32(value) do not convert. Fallible casts follow ordinary error delivery; catch handles a selected expression locally. See Progress for current compiler and backend support.

Choose the explanation level: Cast syntax

Cast syntax

cast converts a value to the type required by its immediate typed destination:

count U64 = cast 42
label String = cast count

The destination must already give a concrete type. An untyped binding cannot supply one:

-- INVALID: no immediate typed destination
invalid = cast source

Use catch to handle a fallible conversion and any failure while evaluating its operand:

count I32 = cast text catch then 0

There is no cast-specific propagation spelling. A fallible cast follows the ordinary implicit or typed error route. Postfix ! still applies to ordinary fallible calls. See Cast syntax for target boundaries and source inference barriers.

cast expression converts a value to the type required by an immediate concrete receiving boundary. Moth adds no target annotation after the expression and no constructor-like numeric conversion.

octet U8 = 42
count U64 = cast octet
ratio F32 = cast count
price Dec2 = cast count

The receiving declarations supply each target. The U8-to-U64 conversion is infallible. U64-to-F32 may round but cannot overflow its finite range. Integer-to-Dec2 preserves the integer exactly at that scale.

Forms

value Target = cast expression

value Target = cast expression catch:
    then fallback
;

value Target = cast expression catch |err|:
    then fallback
;

There is no cast-specific propagation spelling. A fallible conversion uses ordinary failure delivery: an eligible catch, a private function's existing inferred failure route or a compatible builtin Error! slot. A custom E! does not automatically receive implicit built-in failure. Postfix ! remains available for ordinary fallible calls, not casts.

The removed cast! spelling diagnoses. Use plain cast and the ordinary failure route instead.

catch protects operand evaluation and the conversion. It can handle a fallible cast and other actual compatible failures in the selected expression. An infallible cast can also qualify for an authored safety catch; this eligibility does not claim that failure exists. A handler cannot legalise an unsupported source-target pair.

Target source

The cast target must come from its immediate concrete receiver, such as:

  • an annotated declaration or assignment
  • an explicit return slot
  • a concrete function parameter
  • a struct or choice field
  • a default value
  • a typed collection or map entry
  • a compiler-owned typed assertion argument
  • a then arm received by an explicitly typed value-producing block

An unresolved generic parameter is not a target. A generic field supplies a target only after its expected result fixes the parameter. Generic inference does not look through a cast.

These positions do not supply a cast target:

  • conditions and loop conditions
  • template interpolation
  • operator operands
  • expression statements
  • untyped declarations

An explicit target never chooses or immediately defaults the source:

value = 1
take_u32(cast value)
take_i64(value)

The independent I64 receiver resolves value as I64; the U32 cast destination does not. The cast then follows the complete I64-to-U32 conversion policy. An untyped declaration such as converted = cast source has no target and remains invalid.

Removed conversion constructors

Type names do not act as conversion functions:

-- INVALID: type names are not conversion functions
I32(value)
U8(value)
F16(value)
String(value)

Error(...) remains a constructor:

err = Error("Missing number", 200)

Use cast when converting to Error rather than constructing one:

err Error = cast "Missing number"

See Cast targets and Fallible casts for conversion policy and failure delivery. The Progress matrix owns current compiler and backend support: Progress.

Choose the explanation level: Cast targets

Cast targets

Builtin cast targets include eleven fixed numeric types:

  • I8, I16, I32, I64
  • U8, U16, U32, U64
  • F16, F32, F64

Byte, Dec and Dec0 through Dec256 remain separate targets. Bool, String, Char and Error also have builtin conversion policies.

Same-type casts are invalid. Byte remains distinct from U8, and no cast silently changes one into the other.

The target comes from an immediate typed destination such as an annotation, return slot, concrete parameter, field or typed collection entry. An unresolved generic slot and a distant later use cannot supply it.

Not every source-target pair can convert. Numeric pairs follow their complete types, not a value the compiler happens to know. See Cast targets for exactness, rounding and failure rules.

cast expression needs a target from its immediate concrete receiving boundary. The target does not choose the source type. See Cast syntax for the boundary rules.

Builtin targets

The eleven fixed numeric targets are:

  • Integers: I8, I16, I32, I64, U8, U16, U32, U64
  • Binary floats: F16, F32, F64

Builtin conversion policies also cover Byte, Dec, Dec0, Dec1 through Dec256, Bool, String, Char and Error. A target name being valid does not make every source-target pair valid.

Fixed numeric conversions

Fallibility follows the complete source and target types, not a known value:

  • Fixed integer-to-integer conversion preserves the value. It is infallible when the complete source range fits the target and fallible otherwise.
  • Fixed integer-to-F32 or F64 conversion is infallible and may round. Conversion goes directly to the destination precision.
  • Fixed integer-to-F16 is infallible only when the complete source range fits the finite F16 range. Otherwise it is fallible.
  • Binary-float precision widening is infallible. Narrowing is fallible because a rounded result may become non-finite. Round directly to the destination, nearest with ties to even. Precision loss alone succeeds.
  • Binary-float-to-integer conversion is fallible. Truncate towards zero, then check the target range. -0.5 truncates to zero and can convert to an unsigned target; -1.0 fails.

For example, U8 -> U16 is infallible, U16 -> U8 is fallible and F64 -> F16 is a direct narrowing conversion, never an F64 -> F32 -> F16 chain. U64 -> F32 converts directly without an intermediate binary64 rounding step.

For the complete U64 value 9007199791611905, direct conversion to F32 produces bits 0x5a000001. An intermediate F64 conversion would collapse the value to 0x5a000000.

Integer-to-Dec and scale widening are exact and infallible. Scale narrowing and Dec-to-integer conversions are exact or fail: removed fractional digits must be zero and the full integer value must fit its target. Dec does not convert directly to or from a binary float.

Byte and U8 convert infallibly in both directions. Other numeric conversions involving Byte compose through U8. Byte remains distinct from U8; no receiving boundary silently changes one into the other.

Byte has no direct conversion to Bool or Char.

Text and other builtin conversions

  • String parses the complete numeric grammar for fixed integers, binary floats, Byte and Dec targets. These conversions can fail.
  • Every numeric type formats to String infallibly using its canonical text. Byte composes through U8.
  • String -> Bool trims surrounding whitespace and accepts only lowercase true or false. It can fail.
  • String -> Char requires exactly one Unicode scalar and can fail.
  • Char -> I32 returns the Unicode scalar code point. I32 -> Char can fail if the value is not a Unicode scalar.
  • Bool -> String and Char -> String are infallible.
  • String -> Error creates an error message with code 0. Error -> String returns only the message. Both are infallible.

Same-type casts are invalid. No cast acts as an identity conversion.

No other source-target pair follows from this list. In particular, Dec and binary floats have no implicit mixing or direct cast pair.

Exactness and numeric text

A cast does not promise universal exactness. Integer-to-integer conversions preserve values. Binary-float conversions round to nearest, ties-to-even. Binary-float-to-integer conversions truncate towards zero before the range check. Decimal scale narrowing and decimal-to-integer conversions require exactness and never round.

Numeric text consumes the whole string. Parsing rejects surrounding whitespace, unary +, uppercase exponent markers, malformed separators or exponents, NaN and infinity spellings. Unsigned integer targets also reject a leading minus, including -0. A grammar-valid float spelling still fails if its rounded result becomes non-finite.

Binary-float formatting normalises negative zero to 0 and uses lowercase exponents when exponential notation is needed. Decimal formatting trims fractional trailing zeroes, uses a leading zero before fractions and never emits exponent notation or negative zero. Unsigned integer formatting uses base ten and writes zero as 0.

No modulo, wrapping or saturating conversion exists.

Explicit casts retain these checks inside any future fast-math scope. Such a scope cannot relax conversion range, exactness or finite-result rules.

Optional receiving contexts

A T? receiver casts to inner T, then applies ordinary optional wrapping. The recovery handler also produces T; it cannot use then none. Optional source values never unwrap automatically.

parse_optional |text String| -> I32?:
    value I32 = cast text catch:
        return none
    ;
    return value
;

The Progress matrix owns current compiler and backend support: Progress.

Choose the explanation level: Fallible casts

Fallible casts

Some conversions fail. Text may not contain a valid number, an integer may not fit its target and a rounded binary-float result may not stay finite.

Use catch when this expression needs a local fallback:

count I32 = cast text catch then 0

The handler protects the conversion and evaluation of its operand:

narrow |left U32, right U32| -> U8:
    value U8 = cast left + right catch then 0
    return value
;

This catches U32 addition overflow and failure to convert the result to U8. A conversion failure follows the ordinary implicit or typed error path when no local handler catches it. A custom error slot never receives built-in failure without explicit mapping.

Precision loss alone does not fail binary-float narrowing. The conversion rounds directly to the destination and fails only if that rounded result is non-finite. Binary-float-to-integer conversion truncates towards zero, then checks the target range.

A catch cannot legalise an unsupported conversion or statically invalid numeric work. See Fallible casts for evidence and compatibility rules.

Fallible casts use the same plain cast expression as infallible casts. Their actual failure follows ordinary implicit or typed error delivery.

Ordinary failure delivery

An invalid value for a supported conversion produces recoverable failure. A private function can carry implicit failure through its existing local failure route. A compatible builtin Error! slot can return it. A custom E! slot does not automatically convert builtin failure.

parse_count |text String| -> I32, Error!:
    return cast text
;

A source-authored fallible evidence method exposes its declared Error! result. The caller still writes plain cast. Postfix ! remains for ordinary fallible calls and does not attach to a cast.

Local recovery

Use catch to recover a fallible conversion:

count I32 = cast text catch:
    then 0
;

other_count I32 = cast text catch |err|:
    io.line(err.message)
    then 0
;

The handler produces the success values required by the receiving site or leaves through return or return!. It protects both operand evaluation and conversion:

narrow |left U32, right U32| -> U8:
    value U8 = cast left + right catch then 0
    return value
;

This catches U32 addition overflow and failure to convert its result to U8. The addition still computes in its own selected domain.

Implicit failure and compatible builtin Error! outcomes can share a handler. A bound error has type Error. Existing typed Error values keep their message, code and identity, including code 0. A custom typed error cannot share a handler with implicit builtin failure or another distinct error type. Compatible typed calls inside the protected expression need no per-call postfix marker.

Expression-wide scope

catch protects the complete selected expression, including arithmetic, receivers, arguments, nested calls and cast operands. Parentheses do not shrink an outer handler:

amount = load_amount(left * right + offset) catch then 0

The expression evaluates once in ordinary source order. The first failure skips later protected work and enters the handler. Earlier mutations and IO remain visible. A catch is not a transaction, and failure in its handler goes outwards rather than re-entering it.

A catch on a compound assignment's right-hand expression protects only that expression. The later compound arithmetic and any checked conversion back remain separate failure points. The store commits only after every check succeeds.

Cast evidence and static failures

Evidence follows the complete source-target pair, not a value the compiler happens to know. A conversion that can fail for that type pair follows ordinary failure delivery even when this particular value proves safe. A compiler proof may remove a runtime check but cannot change the evidence class.

An authored cast can qualify a safety catch even when the conversion is infallible. That eligibility does not fabricate an error source. A catch cannot legalise an unsupported pair, missing evidence or statically invalid numeric operation. Known failures remain diagnostics, even with a catch or a builtin Error! slot.

An optional T? receiver casts or recovers inner T, then wraps the result. The handler produces T, so then none remains invalid. Optional source values do not unwrap automatically.

See Cast evidence, Cast targets and Catch and recovery. The Progress matrix owns current compiler and backend support: Progress.

Choose the explanation level: Cast evidence

Cast evidence

The compiler owns cast evidence. A nominal type can add source evidence for one of the supported target families by defining the required method and declaring explicit conformance:

Label = |
    text String,
|

to_string |this Label| -> String:
    return this.text
;

Label must CASTABLE_TO_STRING
value String = cast Label("docs")

Fifteen source-authored target families have infallible and fallible evidence: the eleven fixed numeric types plus Bool, String, Char and Error. Fallible evidence returns the target with builtin Error!; conversion uses ordinary failure handling and the same plain cast syntax. For one target, infallible and fallible evidence cannot coexist.

Builtin conversion evidence also covers Byte and Dec, but Moth defines no source-authored traits for them. See Cast evidence for the complete trait signatures and conversion rules.

Compiler-owned static traits prove source evidence for explicit casts. The compiler also registers builtin evidence for its supported source-target policies.

Source-authored target families

Moth defines an infallible and a fallible evidence trait for each of fifteen targets: the eleven fixed numeric types, Bool, String, Char and Error. Each infallible trait requires a method returning its target. Each fallible trait requires a try_to_* method returning the target and builtin Error!.

The Core cast traits reference owns the complete fixed-target inventory and method signatures. A source implementation uses an ordinary lowercase this receiver with its concrete type.

Builtin evidence

Builtin evidence follows the complete conversion policies, including the fixed numeric targets, Byte and the Dec family. A known value, folded result, proven range or optimiser fact never changes the evidence class. A safe value cannot make a fallible source-target pair infallible.

Byte and Dec retain their builtin conversion policies but gain no source-authored evidence families.

Source-authored evidence

A same-file nominal struct, choice or aligned generic nominal constructor can provide evidence for one supported target. It must define the required receiver method and declare explicit conformance:

Label = |
    text String,
|

to_string |this Label| -> String:
    return this.text
;

Label must CASTABLE_TO_STRING

label = Label("hello")
text String = cast label

Fallible evidence declares its actual typed route:

try_to_i32 |this Label| -> I32, Error!:
    value I32 = cast this.text
    return value
;

Label must TRY_CASTABLE_TO_I32

parsed I32 = cast Label("42") catch then 0

The cast uses the ordinary failure rules. Builtin conversion failures enter implicit failure. A fallible source method exposes its declared Error! outcome. An eligible catch or compatible function boundary handles the actual failure; the cast syntax does not select a separate propagation route.

Contract

  • Core cast traits resolve without dependency clauses.
  • They cannot be redeclared, imported, exported, aliased or shadowed.
  • Traits are static contracts, not value types.
  • Matching method shape alone is not evidence. Explicit conformance is required.
  • Same-file nominal types and aligned generic nominal instances may provide source evidence.
  • Infallible and fallible evidence for the same source type and target are mutually exclusive.
  • Evidence resolves before HIR and follows the complete static source and target types.
  • Infallible evidence implementations cannot acquire an inferred failure contract.
  • The traits prove source evidence only. They add no user-defined target types or general conversion framework.

Outside cast design scope

  • user-defined target types
  • generic cast target parameters
  • external opaque cast targets
  • generic cast traits
  • broad return-type-directed conversion
  • conversion search through an intermediate target
  • implicit conversion selected from distant context

See Cast targets for builtin conversion exactness and Trait incompatibility for conflicting trait implementations.