#Prelude

    The prelude package re-exports commonly used types, traits, and functions from the standard library so they are available without explicit imports.

    #Re-exported Types

    Core types available in every MoonBit program:

    • Array, ArrayView, MutArrayView, UninitializedArray — array types
    • Map — ordered map
    • Set — ordered set
    • BigInt — arbitrary-precision integers
    • Iter, Iter2 — iterators
    • Json — JSON values
    • StringBuilder — efficient string building
    • Hasher — hash computation
    • Ref — mutable reference cell
    • Regex — regular expressions
    • Repr — debug representation
    • Failure, InspectError, SnapshotError — error types
    • SourceLoc, ArgsLoc — source location info

    ///|
    test "Set constructor from prelude" {
    let set = Set([1, 2, 3, 4])
    inspect(set.length(), content="4")
    inspect(set.contains(3), content="true")
    }

    #Re-exported Traits

    • Eq, Compare, Hash — equality, ordering, hashing
    • Show, Debug — display and debug output
    • Default — default values
    • ToJson, FromJson — JSON serialization
    • Logger — logging interface
    • Add, Sub, Mul, Div, Mod, Neg — arithmetic
    • Shl, Shr, BitAnd, BitOr, BitXOr — bitwise operations

    #Re-exported Functions

    • println, abort, panic, fail — output and error handling
    • inspect, debug_inspect, debug, to_repr — debugging
    • @test.assert_eq, @test.assert_not_eq, assert_true, assert_false, debug_assert — assertions
    • ignore, physical_equal — utilities
    • json_inspect — JSON-based snapshot testing

    #Re-exported Constants

    • null — JSON null value

    Add

    types implementing this trait can use the + operator

    ArgsLoc

    Represents a type for storing argument locations in source code. It is an array of optional source locations, where each element corresponds to an argument's location in the source code. Used internally by the compiler for error reporting and debugging purposes.

    Array

    An Array is a collection of values that supports random access and can grow in size.

    ArrayView

    An ArrayView represents a view into a section of an array without copying the data. It stores its own start offset and length when it is created, so iteration over a view keeps using those bounds even if the underlying array is later structurally modified.

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr[1:4] // Creates a view of elements at indices 1,2,3
    @test.assert_eq(view[0], 2)
    @test.assert_eq(view.length(), 3)
    }

    BigInt

    A big integer represented as an array of Int.

    BitAnd

    types implementing this trait can use the & operator

    BitOr

    types implementing this trait can use the | operator

    BitXOr

    types implementing this trait can use the ^ operator

    Buffer

    Extensible buffer.

    It provides accumulative concatenation of bytes in linear time. The capacity of buffer will automatically expand as necessary.

    Note: StringBuilder is recommended for string concatenation in favor of Buffer, since it is optimized for all targets.

    Usage

    let buf = Buffer(size_hint=100)
    buf.write_string_utf16le("Tes")
    buf.write_char_utf16le('t')
    inspect(
    buf.contents(),
    content=(

    #|b"T\x00e\x00s\x00t\x00"

    ),
    )

    Compare

    Trait for types whose elements are ordered

    The return value of [compare] is:
    • zero, if the two arguments are equal
    • negative, if the first argument is smaller
    • positive, if the first argument is greater

    Debug

    Trait for types that can be converted to human-readable debugging info.

    Default

    Trait for types with a default value

    Div

    types implementing this trait can use the / operator

    Trait for types whose elements can test for equality

    Failure

    Represents a generic test failure type used primarily in test assertions and validations.

    Since this is a type definition using suberror syntax, it creates an error type Failure that wraps a String value containing the failure message.

    Parameters:

    • message : A string describing the nature of the failure.

    Example:

    test {
    let err : Failure = Failure("Test assertion failed")
    match err {
    Failure(msg) => inspect(msg, content="Test assertion failed")
    }
    @json.json_inspect(err, content=["Failure", "Test assertion failed"])
    }

    FromJson

    Trait for types that can be converted from Json

    Hash

    Trait for types that can be hashed

    The hash method should return a hash value for the type, which is used in hash tables and other data structures. The hash_combine method is used to combine the hash of the current value with another hash value, typically used to hash composite types.

    When two values are equal according to the Eq trait, they should produce the same hash value.

    The hash method does not need to be implemented if hash_combine is implemented, When implemented separately, hash does not need to produce a hash value that is consistent with hash_combine.

    Hasher

    Represents a hasher that implements the xxHash32 algorithm. The hasher maintains a mutable accumulator that is updated with each value added to the hash computation.

    This struct provides methods for combining different types of values into a single hash value, making it suitable for implementing hash functions for custom types.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_int(42)
    hasher.combine_string("hello")
    inspect(hasher.finalize(), content="860601284")
    }

    InspectError

    Represents an error type used by the inspect function to indicate failures in value inspection. Contains a string message describing the nature of the inspection failure.

    Returns a type constructor that creates an error type from a string message.

    Example:

    test {
    let x : Int = 42
    inspect(x, content="42") // Raises InspectError with detailed failure message
    }

    Iter

    External iterator type. Iterator[X] is a mutable type: iterators internally maintain mutable state to advance iteration. All read operations on Iterator will advance the iterator, and would give different result when called multiple times.

    Iter2

    This type is used for for _, _ in .. loop (for .. in loop with two loop variables), and should not be used directly in general.

    Iterator

    using @moonbitlang/core/builtin { type Iter as Iterator }

    Type Iterator.

    Iterator2

    using @moonbitlang/core/builtin { type Iter2 as Iterator2 }

    Type Iterator2.

    Json

    JSON value type used by core serialization APIs.

    Example:

    test {
    let value : Json = Json::array([Json::number(1.0), Json::null()])
    inspect(value.stringify(), content="[1,null]")
    }

    Lazy

    A memoized thunk: the first call to force runs the thunk and caches the result; later calls return the cached value without re-running it.

    Construct one with Lazy(thunk) (deferred) or ready(value) (already evaluated). For fallible work, wrap the result in a Result value inside the thunk — failure as data is the recommended shape; see the rationale below.

    Why force is non-raising / non-async

    force has signature (Self[A]) -> A — no raise?, no async. That is a deliberate choice given how MoonBit surfaces effects in signatures:

    • No raise. A raising thunk would make force raise too, which would then leak into every consumer that touches a lazy cell — and any data structure built on top (lazy lists, lazy trees, memoized graph nodes) would inherit the effect at every traversal point. Memoizing the failure also forces a choice between "cache the exception and re-raise on every retry" (OCaml-style) and "retry on each force" (Rust-style); both are defensible but neither is obviously right. The recommended pattern for a fallible deferred computation is to make the failure data: Lazy(() => try? f()) produces a Lazy[Result[A, Error]], and the consumer handles the result at the call site it controls.

    • No async. Async memoization additionally needs an in-flight state to handle two coroutines racing to force the same cell, which would pull a concurrency primitive into a type whose only job is to delay a value. The right tool for an async deferred value is the language's promise/future type (which already gives "compute once, await many"), not a thunk wrapper.

    Concurrency

    Lazy[A] is not thread-safe. Sharing one across threads requires external synchronization.

    Logger

    Trait for append-only text sinks used by Show implementations.

    A logger receives formatted output without requiring callers to allocate a complete String first.

    Map

    Mutable linked hash map that maintains the order of insertion, not thread safe.

    Example

    test {
    let map = { 3: "three", 8: "eight", 1: "one" }
    @test.assert_eq(map.get(2), None)
    @test.assert_eq(map.get(3), Some("three"))
    map.set(3, "updated")
    @test.assert_eq(map.get(3), Some("updated"))
    }

    Mod

    types implementing this trait can use the % operator

    Mul

    types implementing this trait can use the * operator

    MutArrayView

    A MutArrayView represents a view into a section of an array without copying the data. The view provides read-write access to elements of the underlying array.

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr.mut_view(start=1, end=4) // Creates a view of elements at indices 1,2,3
    @test.assert_eq(view[0], 2)
    @test.assert_eq(view.length(), 3)
    }

    Neg

    types implementing this trait can use the unary - operator

    Ref

    using @moonbitlang/core/ref { type Ref }

    A simple mutable reference type that allows you to store and modify a value of any type.

    test {
    let x = @ref.Ref(42)
    @test.assert_eq(x.val, 42)
    x.val = 100
    @test.assert_eq(x.val, 100)
    }

    Regex

    A compiled regular expression for string-oriented matching.

    Repr

    Direct structural representation for debugging/diffing/pretty-printing.

    Set

    using @moonbitlang/core/set { type Set }

    Mutable linked hash set that maintains the order of insertion, not thread safe.

    Example

    test {
    let set = @set.Set(["three", "eight", "one"])
    @test.assert_eq(set.contains("two"), false)
    @test.assert_eq(set.contains("three"), true)
    set.add("three") // no effect since it already exists
    set.add("two")
    @test.assert_eq(set.contains("two"), true)
    }

    Shl

    types implementing this trait can use the << operator

    Show

    Trait for types that can be converted to String

    Shr

    types implementing this trait can use the >> operator

    SnapshotError

    Represents an error that occurs during snapshot testing. Contains a string message describing the error.

    Used internally by the test driver to handle snapshot-related errors. Not intended for direct use by end users.

    Example:

    test {
    let err : SnapshotError = SnapshotError("failed to load snapshot")
    match err {
    SnapshotError(msg) => @test.assert_eq(msg, "failed to load snapshot")
    }
    }

    SourceLoc

    Represents a source code location in a MoonBit program, containing information about the file path, line number, and column number. Used internally by the compiler for error reporting and debugging purposes.

    This type is public to all packages but its internal representation is opaque. Users cannot construct values of this type directly; they are automatically created by the compiler when needed. TODO: can not make a dummy loc

    StringBuilder

    Sub

    types implementing this trait can use the - operator

    ToJson

    Trait for types that can be converted to Json

    UninitializedArray

    abort

    fn[T] abort(_ : String) -> T

    assert_eq

    #callsite(autofill(loc))
    fn[T : Eq +
    Debug
    ] assert_eq(a : T, b : T, msg? : String, loc~ : SourceLoc) -> Unit raise

    Assert two values are equal for debugging/tests.

    This is the preferred test assertion for new code, especially for types that implement Debug but not Show.

    assert_false

    #callsite(autofill(loc))
    fn assert_false(x : Bool, msg? : StringView, loc~ : SourceLoc) -> Unit raise

    Tests whether a boolean condition is false, throwing an error if the condition is true.

    Parameters:

    • condition : The boolean condition to test.
    • location : The source location where the assertion is made. Used in error messages.

    Throws a Failure error if the condition is true. The error message includes the source location and the value that was expected to be false.

    Example:

    test {
    assert_false(false)
    assert_false(1 > 2)
    }

    assert_not_eq

    #callsite(autofill(loc))
    fn[T : Eq +
    Debug
    ] assert_not_eq(a : T, b : T, msg? : String, loc~ : SourceLoc) -> Unit raise

    Assert two values are not equal using @debug.Debug output for diagnostics.

    assert_true

    #callsite(autofill(loc))
    fn assert_true(x : Bool, msg? : StringView, loc~ : SourceLoc) -> Unit raise

    Asserts that the given boolean value is true. Throws an error with source location information if the assertion fails.

    Parameters:

    • condition : The boolean value to be checked.
    • location : The source location where the assertion is made. Defaults to the current location.

    Throws a Failure error with a descriptive message including the source location if the condition is false.

    Example:

    test {
    assert_true(true)
    }

    compare

    fn[A : Compare + Eq] compare(x : A, y : A) -> Int

    Three-way comparison of two values, returning a negative integer, zero, or a positive integer when x is less than, equal to, or greater than y.

    This is the free-function form of the Compare::compare trait method, symmetric with hash. Being a plain function, it can also be passed as a function value, e.g. array.sort_by(compare).

    test {
    inspect(compare(1, 2).is_neg(), content="true")
    inspect(compare("abc", "abc"), content="0")
    }

    debug

    fn[T :
    Debug
    ] debug(x : T) -> Unit

    Print a value in human-readable format to standard output.

    debug_assert

    fn debug_assert(x : () -> Bool) -> Unit

    Asserts that a condition is true in debug mode.

    The condition is provided as a thunk and is evaluated only when assertions are enabled. If the condition evaluates to false, this function do panic.

    In release mode, debug_assert is a no-op and does not evaluate the thunk.

    Parameters:

    • x : A thunk that computes the condition to check.

    Panic in debug mode when x() returns false.

    debug_inspect

    #callsite(autofill(args_loc, loc))
    fn debug_inspect(obj : &
    Debug
    , content? : String, loc~ : SourceLoc, args_loc~ : ArgsLoc) -> Unit raise InspectError

    Checks that the structural representation (Repr) of an object matches the expected content. Used in test blocks to ensure API results are as expected, and stores a pretty-printed string for comparison.

    Parameters:
    • obj: The object to inspect. Must implement the Debug trait.
    • content: The expected string representation of the object. Defaults to an empty string if not provided.
    • loc: Source code location information for error reporting. Automatically provided by the compiler.
    • args_loc: Location information for function arguments in the source code. Automatically provided by the compiler.

    Raises an InspectError if the actual Repr does not match the expected content.

    Example:

    test {
    @debug.debug_inspect(42, content="42")
    @debug.debug_inspect('c', content="'c'")
    @debug.debug_inspect(
    "hello",
    content=(
    #|"hello"
    ),
    )
    @debug.debug_inspect(
    ([1, 2, 3, 4], "string", Some(3.14)),
    content=(
    #|([1, 2, 3, 4], "string", Some(3.14))
    ),
    )
    }

    dump

    #callsite(autofill(loc))
    #deprecated("for debugging only, not for production")
    fn[T :
    Debug
    ] dump(t : T, name? : String, loc~ : SourceLoc) -> T

    Prints and returns the value of a given expression for quick and dirty debugging. This could also be useful to print some logs to trace the progress. For example, you can put dump(()) in each line, the execution will print the line number when it reaches that line.

    fail

    #callsite(autofill(loc))
    fn[T] fail(msg : StringView, loc~ : SourceLoc) -> T raise Failure

    Raises a Failure error with a given message and source location.

    Parameters:

    • message : A string containing the error message to be included in the failure.
    • location : The source code location where the failure occurred. Automatically provided by the compiler when not specified.

    Returns a value of type T wrapped in a Failure error type.

    Throws an error of type Failure with a message that includes both the source location and the provided error message.

    hash

    fn[T : Hash] hash(value : T) -> Int

    Compute the hash of value.

    This is the free-function form of the Hash::hash trait method, symmetric with @json.to_json. Prefer it over the promoted value.hash() method.

    test {
    inspect(hash(42) == hash(42), content="true")
    }

    ignore

    fn[T] ignore(t : T) -> Unit

    Evaluates an expression and discards its result. This is useful when you want to execute an expression for its side effects but don't care about its return value, or when you want to explicitly indicate that a value is intentionally unused.

    Parameters:

    • value : The value to be ignored. Can be of any type.

    Example:

    test {
    let x = 42
    ignore(x) // Explicitly ignore the value
    let mut sum = 0
    ignore(1, 2, 3.each(x => sum x)) // Ignore the Unit return value of each()
    inspect(sum, content="6")
    }

    inspect

    #callsite(autofill(args_loc, loc))
    fn inspect(obj : &Show, content? : String, loc~ : SourceLoc, args_loc~ : ArgsLoc) -> Unit raise InspectError

    Tests if the string representation of an object matches the expected content. Used primarily in test cases to verify the correctness of Show implementations and program outputs.

    Parameters:

    • object : The object to be inspected. Must implement the Show trait.
    • content : The expected string representation of the object. Defaults to an empty string.
    • location : Source code location information for error reporting. Automatically provided by the compiler.
    • arguments_location : Location information for function arguments in source code. Automatically provided by the compiler.

    Throws an InspectError if the actual string representation of the object does not match the expected content. The error message includes detailed information about the mismatch, including source location and both expected and actual values.

    Example:

    test {
    inspect(42, content="42")
    inspect("hello", content="hello")
    debug_inspect([1, 2, 3], content="[1, 2, 3]")
    }

    json_inspect

    #callsite(autofill(args_loc, loc))
    fn json_inspect(obj : &ToJson, content? : Json, loc~ : SourceLoc, args_loc~ : ArgsLoc) -> Unit raise InspectError

    Inspect JSON value with snapshot-friendly formatting.

    not

    #deprecated("Use !expr instead")
    fn not(x : Bool) -> Bool

    Performs logical negation on a boolean value.

    Parameters:

    • value : The boolean value to negate.

    Returns the logical NOT of the input value: true if the input is false, and false if the input is true.

    null

    let null : Json

    Numeric constant null.

    panic

    fn[T] panic() -> T

    Raise a panic with no payload.

    This function never returns.

    physical_equal

    fn[T] physical_equal(a : T, b : T) -> Bool

    Tests whether two values are physically equal.

    This function is intended only for performance optimizations. Do not depend on its result for program semantics.

    NOTE: The result of physical_equal may not be consistent across different backends and/or different compiler optimization settings.

    Parameters:

    • first : The first value to compare.
    • second : The second value to compare.
    • T : The type parameter representing the type of values being compared.

    Returns a backend- and optimization-dependent result indicating whether the two values are physically equal.

    Example:

    test {
    let arr1 = [1, 2, 3]
    let arr2 = arr1
    let arr3 = [1, 2, 3]
    inspect(physical_equal(arr1, arr2), content="true") // Same object
    inspect(physical_equal(arr1, arr3), content="false") // Different objects with same content
    }

    println

    fn[T : Show] println(input : T) -> Unit

    Prints any value that implements the Show trait to the standard output, followed by a newline.

    Parameters:

    • value : The value to be printed. Must implement the Show trait.

    Example:

    test {
    if false {
    println(42)
    println("Hello, World!")
    }
    }

    repr

    fn[T :
    Debug
    ] repr(x : T) -> String

    Convert a value to its debug string representation. Equivalent to Repr(x).to_string(), but spelled in one step.

    Also exported under the shorter name repr (re-exported from prelude, so it is callable without import). The two names refer to the same function; pick whichever reads better at the call site.

    Note: this is the debug rendering, which differs from T::to_string (the Show rendering) for some types — most visibly, strings and chars are quoted and escaped here. Use @debug.to_string / repr for developer-facing output (logs, snapshots, error messages), and the Show to_string for user-facing output.

    Examples

    test {
    let str = @debug.to_string([1, 2, 3])
    @test.assert_eq(str, "[1, 2, 3]")
    // Same function under a shorter name.
    @test.assert_eq(repr("hi"), "\"hi\"")
    }

    tap

    #deprecated("use `value |> x => { ... ; x} instead")
    fn[T] tap(value : T, f : (T) -> Unit raise) -> T raise

    Applies a function to a value and returns the original value.

    Parameters

    • value: The value to pass to the function.
    • f: The function to apply to the value.

    Returns

    The original value, unchanged.

    then

    #deprecated("use `value |> (x) => {...}` operator instead")
    fn[T, R] then(value : T, f : (T) -> R raise?) -> R raise?

    Applies a function to a value and returns the result of the function.

    Parameters

    • value: The value to pass to the function.
    • f: The function to apply to the value.

    Returns

    The result of applying the function to the value.

    Examples

    test {
    let x = 5
    let result = x |> n => { n * 2 }
    @test.assert_eq(result, 10)
    }

    test {
    try {
    let _ : Unit = 5 |> x => { fail(x.to_string()) }
    } catch {
    Failure(_) => ()
    } noraise {
    _ => fail("expected failure")
    }
    }

    to_repr

    #deprecated("Use `Repr(x)` instead")
    fn[Self :
    Debug
    ] to_repr(_ : Self) ->
    Repr

    Source Files