Sign in

    moonwren

    A Wren-compatible scripting language implementation in MoonBit

    wren
    interpreter
    scripting
    language
    Download zip
    Author
    Version
    0.9.0
    License
    Apache-2.0
    Last updated
    2 hours ago
    Downloads
    72

    #MoonWren

    MoonWren is a Wren 0.4.0-compatible scripting language implementation written in MoonBit. It is designed as an embeddable interpreter with a small public API, a standalone command-line runner, and behavior-focused compatibility tests.

    The project is under active development. The current milestone covers source locations, lexical analysis, primitive expressions, variables, lexical block scope, assignment, conditionals, while loops, protocol-based for loops, method and getter calls, captured program output, the core class model, universal toString, range metadata getters, multiline functions with lexical closures, early return, classes, constructors, instances, fields, methods, getters, and this, inheritance, method overriding, super, class relationship checks, static members, and structured break/continue control flow. Core values include mutable List and Map collections, Unicode-aware String operations, negative indexes, range slices, MapEntry iteration, eager sequence aggregations, and composable lazy map/where/skip/take pipelines. Named modules, explicit imports, loader callbacks, module caching, cross-module stack traces, multi-file CLI execution, cooperative Fiber values, host-bound foreign methods, and host-backed foreign classes are also available. Fibers preserve block and loop state across suspension and can suspend through functions, methods, callbacks, constructors, and imported modules. Runtime class and method attributes, raw strings, cyclic modules, and the complete 32-bit numeric operator surface are supported as well. A persistent embedding VM retains script state across host calls and provides transactional module reload, strong host handles, configurable resource limits, host cancellation, and explicit full-heap reachability collection. An optional stack-bytecode backend, instruction profiler/trace, transactional REPL session, verified module bundles, sandboxed filesystem loader, and browser playground support runtime development and production embedding without replacing the compatible tree-walking execution path. Resumable host tasks, live statement debugging, and portable cyclic state snapshots cover long-running service and tool hosts. The official Wren 0.4 random and meta optional modules are built in and do not require a host loader.

    #Installation

    Add the published package to a MoonBit project:

    moon add wdgodghl/moonwren@0.8.0

    Then import wdgodghl/moonwren from the consuming package's moon.pkg and use the library as @moonwren. The optional root-confined filesystem loader is in wdgodghl/moonwren/loaders; capability-limited script I/O is in wdgodghl/moonwren/host.

    #Goals

    • implement the language runtime primarily in MoonBit;
    • keep the interpreter portable across MoonBit targets;
    • provide useful diagnostics with source locations;
    • make embedding scripts straightforward through a small API;
    • track compatibility explicitly instead of silently accepting unsupported syntax.

    The compatibility endpoint is the official Wren 0.4.0 release at tag commit 4a18fc489f9ea3d253b20dd40f4cdad0d6bb40eb. It includes byte-accurate String behavior (including invalid UTF-8) and Fiber suspension through arbitrary Wren calls and callbacks. The precise definition of done, exclusions, and official input/output comparison cases are recorded in docs/wren-0.4-conformance.md.

    #Optional Wren modules

    random implements the Wren 0.4 Random API, including deterministic numeric and sequence seeds, uniform numbers, sampling, and in-place shuffling. meta compiles or evaluates source in the importing module and can enumerate its visible variables:

    import "random" for Random import "meta" for Meta var random = Random.new(2026) System.print(random.sample(["moon", "wren", "bit"])) System.print(Meta.compileExpression("20 + 22").call())

    #Development

    The project requires MoonBit 0.10.14 or newer.

    moon check moon test moon run cmd/main moon run cmd/runtime_tools_demo moon run cmd/benchmark --target native ./tools/build-web-demo.ps1 ./tools/check-conformance.ps1 ./tools/check-official-suite.ps1 -WrenRoot /path/to/wren-0.4.0

    Running the command without arguments executes the bundled summation example and prints 55. Use --eval to execute a source string directly:

    moon run cmd/main -- --eval "var value = 40\nSystem.print(value + 2)"

    Functions are values and capture surrounding variables by reference:

    moon run cmd/main -- --eval "var count = 0\nvar next = Fn.new { count = count + 1 }\nSystem.print(next.call())\nSystem.print(next.call())"

    Function bodies may contain declarations and control flow. A return exits through nested blocks and loops, while a bare return produces null:

    var makeCounter = Fn.new { var count = 0 return Fn.new { count = count + 1 return count } } var counter = makeCounter.call() System.print(counter.call()) // 1 System.print(counter.call()) // 2

    Classes combine persistent instance fields with constructor, method, and getter dispatch:

    class Point { construct new(x, y) { _x = x _y = y } move(dx, dy) { _x = _x + dx _y = _y + dy } sum { return _x + _y } } var point = Point.new(10, 20) point.move(5, 7) System.print(point.sum) // 42

    The complete version is available in examples/classes.wren.

    Subclass lookup supports inherited methods and getters, explicit superclass constructor calls, overriding, and super dispatch:

    class NamedPoint is Point { construct new(x, y) { super(x, y) } sum { return super.sum + 2 } } var point = NamedPoint.new(19, 21) System.print(point.sum) // 42 System.print(point is Point) // true

    See examples/inheritance.wren for a complete multi-level example.

    Static methods and getters share class-owned __fields and support dynamic this plus declaring-class super dispatch. As in Wren 0.4.0, static methods are not inherited by subclasses. See examples/static_members.wren.

    Both while and range for loops support break and continue. Loop control can cross nested blocks and conditionals, but a called function or method cannot accidentally break or continue its caller's loop. See examples/loop_control.wren.

    Lists and maps are mutable reference values. Lists support positive and negative indexes, range slices, construction and filling, add, addAll, insert, remove, removeAt, contains, indexOf, swap, sort, concatenation, repetition, clear, count, and stable for iteration. Maps accept immutable keys and provide indexed lookup and update, containsKey, remove, clear, count, snapshot keys and values views, and entry iteration:

    var scores = {"Ada": 38, "Lin": 40} scores["Ada"] = scores["Ada"] + 4 var values = [scores["Ada"], scores["Lin"]] values.add(0) var total = 0 for (value in values) total = total + value System.print(total) // 82

    See examples/collections.wren for a complete example including nested collections and removal.

    Strings use Wren's UTF-8 byte-offset rules, including range slicing and operations that preserve invalid bytes created by String.fromByte. The checked-in Wren 0.4.0 differential suite locks these behaviors down. Core methods include contains, startsWith, endsWith, indexOf, split, replace, trimming, UTF-8 byte views, and code-point views. Num provides parsing, constants, predicates, rounding, trigonometry, logarithms, powers, and clamping. Any class can participate in a for loop by implementing iterate(iterator) and iteratorValue(iterator). See examples/iterables.wren.

    Every built-in iterable supports all, any, contains, count, each, join, and seeded or unseeded reduce. Transformations are lazy and can be composed before materializing with toList; short-circuiting operations only consume as much input as needed:

    var selected = (1..20).where(Fn.new { |n| n % 2 == 0 }) selected = selected.map(Fn.new { |n| n * n }).skip(2).take(3) System.print(selected.toList) // [36, 64, 100]

    See examples/core_library.wren for a runnable tour of the expanded core library.

    Fibers retain their local environment between calls and exchange values at cooperative suspension points. Errors can either propagate through call or be captured through try:

    var worker = Fiber.new { |request| System.print(request) var response = Fiber.yield("waiting") return response } System.print(worker.call("start")) // waiting System.print(worker.call("done")) // done

    See examples/fibers.wren for calls, transfers, nested control flow, completion state, and captured aborts. Worker-to-worker transfer chains preserve each suspended continuation until control returns to it.

    Multi-file programs use explicit imports. The CLI resolves relative module names from the importing file, automatically adds .wren when omitted, and executes every canonical module once:

    import "math" for Calculator System.print(Calculator.double(21))

    moon run cmd/main -- examples/modules/main.wren

    See examples/modules for the complete project.

    For deployments, verified_module_loader rejects traversal names and verifies each bundled source before execution. encode_module_archive and decode_module_archive provide a deterministic, versioned, length-delimited archive with per-module integrity checks. The wdgodghl/moonwren/loaders package adds a filesystem loader confined to one canonical root with extension and source-size policies. FileModuleWatcher::poll supplies verified modules and only the names changed since its last successful poll, ready to feed into transactional reload_module.

    The library API exposes the same pipeline:

    match @moonwren.run("var answer = 6 * 7\nanswer\n") {
    ProgramCompleted(value, output) => {
    for line in output {
    println(line)
    }
    println("result: \{value.to_text()}")
    }
    ProgramFailed(diagnostics, _) =>
    for diagnostic in diagnostics {
    println(diagnostic.render("example.wren"))
    }
    }

    System.print output is returned as an array of lines instead of being written directly by the library. Embedders can route those lines to a console, log, editor pane, or another host-provided destination. ProgramRunResult::deliver is a convenience adapter for separate output and diagnostic callbacks.

    For long-lived applications, Vm owns a persistent runtime. The host can load root modules, capture values, call Wren functions and methods, read getters, and retain returned runtime values across later calls:

    let vm = Vm::new(VmLimits::standard(100000), loader, [], [])
    ignore(vm.interpret(
    "main",
    "var count = 40\nvar next = Fn.new { count = count + 1 }\n",
    ))

    match vm.capture("main", "next") {
    VmHandleCreated(next) => {
    ignore(vm.call(next, [])) // 41
    ignore(vm.call(next, [])) // 42
    }
    VmHandleFailed(issue) => println(issue.message)
    }
    vm.close()

    Repeated calls can cache lookup intent with bind_method and call_bound. Typed host collection operations (list_snapshot, list_set, list_add, map_snapshot, map_get, map_set, and map_remove) avoid reaching into runtime identities directly. has_module and has_variable support cheap host capability checks.

    Long-running hosts can turn a Wren Fiber into a retained asynchronous task. The script yields a request descriptor, the host performs I/O without entering the VM, and a later event-loop turn resumes the exact suspended continuation:

    let fiber = match vm.capture("main", "worker") {
    VmHandleCreated(handle) => handle
    VmHandleFailed(issue) => abort(issue.message)
    }
    let task = match vm.new_async_task(fiber) {
    VmAsyncTaskCreated(task) => task
    VmAsyncTaskCreateFailed(issue) => abort(issue.message)
    }
    match vm.start_async(task, None) {
    VmAsyncYielded(request, _) =>
    ignore(vm.resume_async(task, request, Value::string("host response")))
    _ => ()
    }

    Each request is one-shot and bound to its task and VM generation. The task owns strong roots for both its Fiber and current request; cancel_async releases them. This cooperative design preserves Wren semantics and never re-enters a running VM from a foreign callback.

    For multiple concurrent Fibers, VmScheduler consumes the built-in timer, task, and scheduler module protocols. It supports virtual-time sleeps, child spawning, Task.await, ordered Task.all, first-completion Task.race, host requests, cancellation, task limits, and retained results. Virtual time keeps tests deterministic; a real event loop calls advance from its monotonic timer and deliver when an I/O result arrives. Run the complete example with:

    moon run cmd/scheduler_demo

    The scheduler never performs I/O itself. Any yielded value that is not one of its reserved request maps is surfaced as VmSchedulerExternalRequest, keeping networking, databases, and UI work under host control.

    Scripts that genuinely need local data can opt into the separate host package. HostModuleKit installs moon/io and moon/env with a per-VM policy: a single filesystem root, independent read/write grants, UTF-8 byte limits, and an explicit environment-value allowlist. The default policy grants nothing, and no process or network module exists. See docs/host-capabilities.md for the security model or run moon run cmd/host_demo for a complete example.

    attach_debugger observes the live interpreter immediately before statements execute. Source breakpoints and pause-on-entry can return DebugContinue, DebugStepInto, DebugStepOver, DebugStepOut, or DebugTerminate. Each DebugSnapshot includes the source span, call depth, and visible variables. The hook is synchronous so a desktop or terminal frontend may wait for a user command, but it must not re-enter the same VM.

    save_state(module, names) exports selected globals to an integrity-checked MWS1 archive. restore_state validates the complete archive before changing bindings. Null, Boolean, Num, String (including arbitrary bytes), Range, List, and Map values are supported; shared references and cycles are preserved. Functions, Fibers, classes, instances, iterators, and foreign objects are rejected because their identities cannot be moved safely between runtimes.

    Automatic collection runs only between host operations, never midway through a Wren call. Configure its minimum object count and growth percentage with configure_automatic_gc(VmGcPolicy::new(...)), inspect the last pass through last_automatic_gc, or disable it for latency-sensitive hosts. System.gc() requests a safe collection at the next host boundary. collect_garbage traces the complete runtime heap: instances, closures, classes, lists, maps, sequence views, iterators, map entries, and Fibers. Its statistics report total reachable and reclaimed objects as well as foreign finalizers. Host-owned resources can use HostObjectTable[T], whose generation-checked handles reject stale identifiers after a slot is reused.

    The optional hybrid bytecode backend accepts the complete MoonWren Wren 0.4 surface. Procedural control flow, collections, subscripts, properties, and calls lower to stack instructions; classes, closures, modules, Fibers, and structured loop control currently lower to explicit semantic instructions executed against the same environment and resource limits. This makes compiled programs deployable without a syntax-dependent fallback decision while keeping the optimization boundary measurable through semantic_fallbacks. The Wren 0.4-compatible interpreter remains the default:

    match compile_bytecode("var n = 6\n n * 7\n") {
    BytecodeCompiled(program) => {
    let profile = profile_bytecode(program, 10000)
    let trace = trace_bytecode(program, 10000)
    let listing = disassemble_bytecode(program)
    let debugger = BytecodeTraceDebugger::new(trace, [1])
    ignore(debugger.step())
    ignore(debugger.continue_execution())
    }
    BytecodeCompileFailed(issues) => println(issues[0].message)
    }

    BytecodeTraceDebugger remains useful for deterministic trace replay, while the Vm live debugger observes real interpreter state and can control the running operation. ReplSession retains accepted declarations by deterministic replay and rolls back rejected submissions. Value::as_bool, as_number, as_string, and as_range provide checked conversions at the host boundary.

    Development tools are described in docs/tooling.md, including deterministic differential fuzzing against official Wren, repeatable performance baselines, bytecode inspection, and the local/shareable browser playground. The manual Playground Pages workflow can deploy the static build to GitHub Pages after Pages is enabled for the repository.

    Production module graphs can be packaged as deterministic, signed MWDS1 deployment bundles. Bundles cryptographically bind the Wren target, compiler ABI, entry module, capability declaration, sources, and compiled metadata with SHA-256; caller-supplied sign/verify callbacks support Ed25519 or managed keys. See docs/deployment-bundles.md.

    Editor integrations can reuse LanguageServer for diagnostics, symbols, completion, hover, definition, references, and rename edits. A DebugAdapterSession connects breakpoints and DAP-style step commands to the live VM debugger and exposes real variable snapshots. The transport-neutral integration contract is documented in docs/editor-tooling.md.

    The generated ES module under web/ now doubles as a browser and Node.js SDK. It exposes structured evaluation results, configurable step limits, TypeScript types, and an optional Worker entrypoint; CI runs the SDK directly in Node. See docs/javascript-sdk.md and examples/node-sdk.mjs.

    Portable moon/json, moon/base64, moon/url, moon/uuid, and scheduler- mediated moon/http modules cover common embedding data paths. HTTP yields an inspectable host request and never grants direct network access; filesystem and environment modules remain explicitly capability-gated. See docs/standard-modules.md.

    VmPool adds bounded multi-tenant execution with opaque leases, per-tenant concurrency limits, stale-token rejection, fault invalidation, VM rotation, and an isolated mode that resets every released runtime. See docs/vm-pool.md.

    Asynchronous executions can be recorded and replayed through deterministic MWR1 transcripts. Virtual time, host responses, cancellation and observable events are verified against a workload digest, with first-divergence reporting for regression reproduction. See docs/deterministic-replay.md.

    Hot reload now also supports atomic multi-module replacement, import dependency ordering, complete MWS1 collection-graph migration, host schema transforms, and rollback that preserves old handles on every failure. See docs/hot-reload.md.

    ObservedVm provides bounded per-operation telemetry and subscriber callbacks, including evaluator, resource, foreign-call, call-depth and GC measurements. Histories export to Prometheus text or Chrome/Perfetto Trace JSON without capturing script source or host values. See docs/observability.md.

    reload_module builds a candidate runtime, reloads every retained root module, and commits only after the whole graph succeeds. Selected primitive globals can be migrated by name. A successful reload starts a new generation and invalidates old handles; a failed reload leaves the current runtime and handles untouched. See docs/embedding.md and run the complete examples with moon run cmd/vm_demo and moon run cmd/runtime_tools_demo.

    Embedders can provide modules from memory, a database, an archive, or another source through run_with_loader. run_modules is a convenience API for a fixed in-memory collection:

    let modules = [
    ModuleSource::new("main", "import \"answer\" for value\nvalue\n"),
    ModuleSource::new("answer", "var value = 42\n"),
    ]
    let result = run_modules("main", modules, 100000)

    Wren classes may declare foreign instance methods, static methods, and getters. run_with_foreign_methods binds those declarations to typed MoonBit callbacks; callbacks receive the receiver and argument array, then return either a Wren value or a structured host failure. run_with_foreign_bindings additionally binds foreign class declarations. The host allocator returns an opaque integer handle, handle-aware instance methods operate on it, and the finalizer releases it once when the interpreter run shuts down. See docs/embedding.md and examples/foreign_methods.wren or examples/foreign_classes.wren.

    #Project status

    MoonWren now passes all 779 runnable language and core-library cases in the official Wren 0.4.0 test tree; the remaining 22 files are marked skip or nontest by that upstream suite. The method dispatcher supports constructor signatures, overloaded instance methods by arity, user-defined getters, setters, operators and subscripts, core class metadata and constructors, captured System.print/write output, and the standard from, to, min, max, and isInclusive range properties. Collection and String subscripts produce structured invalid-index and bounds diagnostics, and Map keys are checked before lookup or mutation. Inherited lookup advances from each method's declaring class, so multi-level super calls remain correct. See docs/compatibility.md for the completed source-language feature matrix and the explicitly excluded C ABI, VM layout, and garbage-collector timing details.

    Persistent VM operations enforce configurable statement, call-depth, captured output, loaded-module, runtime-object, and source-size limits. A host callback can also cancel work at interpreter checkpoints. These controls turn unbounded loops, runaway recursion, output floods, module fan-out, and allocation spikes into structured diagnostics instead of allowing them to consume host resources. Diagnostics retain their defining module and accumulate function, instance, static-method, and import frames while unwinding.

    The implementation pipeline and package boundaries are documented in docs/architecture.md.

    #License and references

    MoonWren is licensed under Apache-2.0. The implementation uses the public Wren language documentation as a behavioral reference. See NOTICE for attribution and project-boundary details.

    AttributeDecl

    pub(all) struct AttributeDecl {
    group : String?
    key : String
    value : Value
    } derive(Eq,
    Debug
    )

    One runtime attribute attached to a class or method declaration.

    AttributeDecl::equal

    AttributeDecl::not_equal

    fn AttributeDecl::not_equal(x : AttributeDecl, y : AttributeDecl) -> Bool

    BinaryOperator

    pub(all) enum BinaryOperator {
    Add
    Subtract
    Multiply
    Divide
    Remainder
    EqualTo
    NotEqualTo
    LessThan
    LessThanOrEqual
    GreaterThan
    GreaterThanOrEqual
    LogicalAnd
    LogicalOr
    BitwiseAnd
    BitwiseOr
    BitwiseXor
    ShiftLeft
    ShiftRight
    InclusiveRange
    ExclusiveRange
    IsType
    } derive(Eq,
    Debug
    )

    BinaryOperator::equal

    BinaryOperator::not_equal

    fn BinaryOperator::not_equal(x : BinaryOperator, y : BinaryOperator) -> Bool

    Binding

    pub(all) struct Binding {
    name : String
    value :
    Ref
    [Value]
    }

    BytecodeCompileResult

    pub(all) enum BytecodeCompileResult {
    BytecodeCompiled(BytecodeProgram)
    BytecodeCompileFailed(Array[Diagnostic])
    }

    BytecodeDebugResult

    pub(all) enum BytecodeDebugResult {
    DebuggerPaused(BytecodeTraceEvent)
    DebuggerFinished(BytecodeRunResult)
    }

    Result of advancing a captured bytecode execution trace.

    BytecodeInstruction

    pub(all) struct BytecodeInstruction {
    op : BytecodeOp
    span : SourceSpan
    } derive(Eq,
    Debug
    )

    BytecodeInstruction::equal

    BytecodeInstruction::not_equal

    BytecodeOp

    pub(all) enum BytecodeOp {
    PushConstant(Int)
    LoadName(String)
    DefineName(String)
    StoreName(String)
    Duplicate
    Pop
    EnterScope
    ExitScope
    UnaryOp(UnaryOperator)
    BinaryOp(BinaryOperator)
    BuildList(Int)
    BuildMap(Int)
    GetSubscript
    SetSubscript
    GetProperty(String)
    SetProperty(String)
    InvokeMethod(String, Int)
    EvaluateSemantic(Expr)
    ExecuteSemantic(Stmt)
    Jump(Int)
    JumpIfFalse(Int)
    JumpIfFalseKeep(Int)
    JumpIfTrueKeep(Int)
    SetLast
    ReturnValue
    ReturnLast
    } derive(Eq,
    Debug
    )

    One operation executed by the optional stack-based bytecode backend.

    BytecodeOp::equal

    fn BytecodeOp::equal(BytecodeOp, BytecodeOp) -> Bool

    BytecodeOp::not_equal

    fn BytecodeOp::not_equal(x : BytecodeOp, y : BytecodeOp) -> Bool

    BytecodeProfile

    pub(all) struct BytecodeProfile {
    result : BytecodeRunResult
    executed_instructions : Int
    max_stack_depth : Int
    loads : Int
    stores : Int
    branches : Int
    arithmetic_operations : Int
    calls : Int
    semantic_fallbacks : Int
    }

    Dynamic counters collected by the bytecode profiler.

    BytecodeProgram

    pub(all) struct BytecodeProgram {
    source_name : String
    constants : Array[Value]
    instructions : Array[BytecodeInstruction]
    }

    Immutable compiled program. Frequently used procedural operations lower to native stack instructions; object/module/Fiber constructs use semantic escape instructions so every supported Wren construct remains executable.

    BytecodeRunResult

    pub(all) enum BytecodeRunResult {
    BytecodeCompleted(Value, Int)
    BytecodeFailed(Diagnostic, Int)
    }

    BytecodeTrace

    pub(all) struct BytecodeTrace {
    result : BytecodeRunResult
    events : Array[BytecodeTraceEvent]
    }

    BytecodeTraceDebugger

    pub struct BytecodeTraceDebugger {
    trace : BytecodeTrace
    breakpoints : Array[Int]
    cursor : Int
    }

    Deterministic debugger cursor over a bytecode trace. It is intentionally a replay debugger: execution is captured once, then frontends can single-step or continue between source-line breakpoints without changing program state.

    BytecodeTraceDebugger::continue_execution

    Advance until the next event whose source line is a configured breakpoint. If no later breakpoint is hit, return the program's final result.

    BytecodeTraceDebugger::event_count

    fn BytecodeTraceDebugger::event_count(self : BytecodeTraceDebugger) -> Int

    BytecodeTraceDebugger::new

    fn BytecodeTraceDebugger::new(trace : BytecodeTrace, breakpoints : Array[Int]) -> BytecodeTraceDebugger

    BytecodeTraceDebugger::position

    fn BytecodeTraceDebugger::position(self : BytecodeTraceDebugger) -> Int

    BytecodeTraceDebugger::reset

    BytecodeTraceDebugger::step

    BytecodeTraceEvent

    pub(all) struct BytecodeTraceEvent {
    instruction_pointer : Int
    step : Int
    stack_depth : Int
    instruction : BytecodeInstruction
    }

    One executed instruction captured for debugger frontends.

    CallFrame

    pub(all) struct CallFrame {
    callable : String
    source_name : String
    span : SourceSpan
    } derive(Eq,
    Debug
    )

    One caller location retained while an error unwinds through the runtime.

    CallFrame::equal

    fn CallFrame::equal(CallFrame, CallFrame) -> Bool

    CallFrame::new

    fn CallFrame::new(callable : String, source_name : String, span : SourceSpan) -> CallFrame

    CallFrame::not_equal

    fn CallFrame::not_equal(x : CallFrame, y : CallFrame) -> Bool

    CompiledModuleMetadata

    pub(all) struct CompiledModuleMetadata {
    name : String
    source_sha256 : String
    instruction_count : Int
    semantic_instruction_count : Int
    } derive(Eq,
    Debug
    )

    Metadata for one source that was validated by the hybrid compiler before packaging. It deliberately describes, rather than serializes, the current in-memory instruction format so bundles remain portable across targets.

    CompiledModuleMetadata::equal

    CompiledModuleMetadata::not_equal

    CoreClass

    pub(all) enum CoreClass {
    ObjectClass
    BoolClass
    ClassClass
    FiberClass
    FnClass
    ListClass
    MapClass
    MapEntryClass
    MapKeySequenceClass
    MapValueSequenceClass
    NullClass
    NumClass
    RangeClass
    SequenceClass
    StringClass
    StringByteSequenceClass
    StringCodePointSequenceClass
    } derive(Eq,
    Debug
    )

    Runtime values available before object and class support is introduced.

    CoreClass::equal

    fn CoreClass::equal(CoreClass, CoreClass) -> Bool

    CoreClass::name

    fn CoreClass::name(self : CoreClass) -> String

    CoreClass::not_equal

    fn CoreClass::not_equal(x : CoreClass, y : CoreClass) -> Bool

    DebugAdapterSession

    pub(all) struct DebugAdapterSession {
    breakpoints : Array[DebugBreakpoint]
    commands : Array[DebugCommand]
    snapshots : Array[DebugSnapshot]
    pause_on_entry : Bool
    }

    Transport-neutral Debug Adapter Protocol session backed by MoonWren's live debugger. Frontends queue commands before execution; every real stop is retained as a DAP-style snapshot.

    DebugAdapterSession::attach

    fn DebugAdapterSession::attach(self : DebugAdapterSession, vm : Vm) -> Bool

    DebugAdapterSession::clear_stops

    fn DebugAdapterSession::clear_stops(self : DebugAdapterSession) -> Unit

    DebugAdapterSession::detach

    fn DebugAdapterSession::detach(self : DebugAdapterSession, vm : Vm) -> Bool

    DebugAdapterSession::enqueue

    fn DebugAdapterSession::enqueue(self : DebugAdapterSession, command : DebugCommand) -> Unit

    DebugAdapterSession::new

    DebugAdapterSession::set_breakpoints

    fn DebugAdapterSession::set_breakpoints(self : DebugAdapterSession, source_name : String, lines : Array[Int]) -> Array[DebugBreakpoint]

    DebugAdapterSession::set_pause_on_entry

    fn DebugAdapterSession::set_pause_on_entry(self : DebugAdapterSession, enabled : Bool) -> Unit

    DebugAdapterSession::stops

    DebugBreakpoint

    pub(all) struct DebugBreakpoint {
    source_name : String
    line : Int
    }

    A source breakpoint for the live tree-walking interpreter.

    DebugBreakpoint::new

    fn DebugBreakpoint::new(source_name : String, line : Int) -> DebugBreakpoint

    DebugCommand

    pub(all) enum DebugCommand {
    DebugContinue
    DebugStepInto
    DebugStepOver
    DebugStepOut
    DebugTerminate
    }

    The command returned synchronously by a live debugger hook.

    DebugSnapshot

    pub(all) struct DebugSnapshot {
    source_name : String
    span : SourceSpan
    call_depth : Int
    variables : Array[DebugVariable]
    }

    Live state captured immediately before a statement executes.

    DebugVariable

    pub(all) struct DebugVariable {
    name : String
    value : Value
    }

    One visible variable copied at a debugger stop.

    DeploymentBundleResult

    pub(all) enum DeploymentBundleResult {
    DeploymentBundleReady(SignedDeploymentBundle)
    DeploymentBundleFailed(String)
    }

    DeploymentManifest

    pub(all) struct DeploymentManifest {
    format_version : Int
    wren_version : String
    compiler_abi : String
    entry_module : String
    capabilities : Array[String]
    compiled_modules : Array[CompiledModuleMetadata]
    }

    Diagnostic

    pub(all) struct Diagnostic {
    phase : DiagnosticPhase
    code : DiagnosticCode
    message : String
    span : SourceSpan
    source_name : String
    frames : Array[CallFrame]
    }

    Structured interpreter diagnostic carrying an actionable source span.

    Diagnostic::new

    fn Diagnostic::new(phase : DiagnosticPhase, code : DiagnosticCode, message : String, span : SourceSpan) -> Diagnostic

    Diagnostic::render

    fn Diagnostic::render(self : Diagnostic, source_name : String) -> String

    Diagnostic::with_frame

    fn Diagnostic::with_frame(self : Diagnostic, frame : CallFrame) -> Diagnostic

    Diagnostic::with_source

    fn Diagnostic::with_source(self : Diagnostic, source_name : String) -> Diagnostic

    DiagnosticCode

    pub(all) enum DiagnosticCode {
    UnexpectedCharacter
    UnterminatedString
    UnterminatedComment
    InvalidEscape
    InvalidNumber
    UnexpectedToken
    ExpectedExpression
    ExpectedToken
    DuplicateVariable
    DuplicateMethod
    InvalidSuperclass
    UndefinedVariable
    UndefinedMethod
    InvalidArity
    InvalidOperand
    InvalidIndex
    IndexOutOfBounds
    InvalidMapKey
    ModuleNotFound
    CircularImport
    UndefinedExport
    DivisionByZero
    ExecutionLimit
    CallStackLimit
    ReturnOutsideFunction
    BreakOutsideLoop
    ContinueOutsideLoop
    ForeignBindingMissing
    ForeignClassBindingMissing
    ForeignObjectAllocationFailed
    ForeignCallFailed
    InvalidFiberState
    FiberAborted
    DebugTerminated
    UnsupportedFeature
    } derive(Eq,
    Debug
    )

    Stable category for programmatic handling of failures.

    DiagnosticCode::equal

    DiagnosticCode::not_equal

    fn DiagnosticCode::not_equal(x : DiagnosticCode, y : DiagnosticCode) -> Bool

    DiagnosticPhase

    pub(all) enum DiagnosticPhase {
    Scan
    Parse
    Resolve
    Runtime
    } derive(Eq,
    Debug
    )

    Phase that reported a diagnostic.

    DiagnosticPhase::equal

    DiagnosticPhase::not_equal

    fn DiagnosticPhase::not_equal(x : DiagnosticPhase, y : DiagnosticPhase) -> Bool

    Environment

    pub struct Environment {
    scopes : Array[Scope]
    }

    Stack of lexical scopes used by the interpreter and embedding API.

    Environment::assign

    fn Environment::assign(self : Environment, name : String, value : Value) -> Bool

    Replace the nearest visible binding. Returns false when the name is absent.

    Environment::bind

    fn Environment::bind(self : Environment, name : String, value : Value) -> Bool

    Define a name in the innermost scope. Returns false for a duplicate.

    Environment::capture

    fn Environment::capture(self : Environment) -> Environment

    Snapshot visible scopes while retaining shared variable cells.

    Environment::depth

    fn Environment::depth(self : Environment) -> Int

    Environment::get

    fn Environment::get(self : Environment, name : String) -> Value?

    Environment::new

    Environment::pop_scope

    fn Environment::pop_scope(self : Environment) -> Bool

    Environment::push_scope

    fn Environment::push_scope(self : Environment) -> Unit

    EvaluationResult

    pub(all) enum EvaluationResult {
    EvaluationSucceeded(Value)
    EvaluationFailed(Diagnostic)
    }

    Expr

    pub(all) enum Expr {
    Literal(Value, SourceSpan)
    Variable(String, SourceSpan)
    Assign(String, Expr, SourceSpan)
    FieldGet(String, SourceSpan)
    FieldAssign(String, Expr, SourceSpan)
    StaticFieldGet(String, SourceSpan)
    StaticFieldAssign(String, Expr, SourceSpan)
    ListLiteral(Array[Expr], SourceSpan)
    MapLiteral(Array[MapEntryExpr], SourceSpan)
    SubscriptGet(Expr, Expr, SourceSpan)
    SubscriptSet(Expr, Expr, Expr, SourceSpan)
    PropertyGet(Expr, String, SourceSpan)
    PropertySet(Expr, String, Expr, SourceSpan)
    MethodCall(Expr, String, Array[Expr], SourceSpan)
    SuperConstructorCall(Array[Expr], SourceSpan)
    FunctionLiteral(Array[String], Array[Stmt], SourceSpan)
    FiberCallResume(Int, Value, Value?, SourceSpan)
    FiberSequenceResume(Int, Value, Value, Value, Int, String, Value, Int, SourceSpan)
    Unary(UnaryOperator, Expr, SourceSpan)
    Binary(Expr, BinaryOperator, Expr, SourceSpan)
    Conditional(Expr, Expr, Expr, SourceSpan)
    Grouping(Expr, SourceSpan)
    } derive(Eq,
    Debug
    )

    Expression tree retained independently from the parser and evaluator.

    Expr::equal

    fn Expr::equal(Expr, Expr) -> Bool

    Expr::not_equal

    fn Expr::not_equal(x : Expr, y : Expr) -> Bool

    Expr::span

    fn Expr::span(self : Expr) -> SourceSpan

    Expr::to_repr

    ExpressionParseResult

    pub(all) enum ExpressionParseResult {
    ExpressionParsed(Expr)
    ExpressionParseFailed(Array[Diagnostic])
    }

    ForeignAllocationResult

    pub(all) enum ForeignAllocationResult {
    ForeignAllocationSucceeded(Int)
    ForeignAllocationFailed(String)
    }

    Result returned while allocating the host-owned state of a foreign object. The integer is an opaque handle chosen and managed by the embedding host.

    ForeignCallContext

    pub struct ForeignCallContext {
    receiver : Value
    arguments : Array[Value]
    }

    Arguments visible to a context-aware foreign method. The context is valid only for the duration of its callback and cannot re-enter the VM.

    ForeignCallContext::argument

    fn ForeignCallContext::argument(self : ForeignCallContext, index : Int) -> Value?

    ForeignCallContext::argument_count

    fn ForeignCallContext::argument_count(self : ForeignCallContext) -> Int

    ForeignCallContext::arguments

    ForeignCallContext::receiver

    ForeignCallResult

    pub(all) enum ForeignCallResult {
    ForeignCallSucceeded(Value)
    ForeignCallFailed(String)
    }

    Result produced by a MoonBit callback that implements a Wren foreign method.

    ForeignClassBinding

    pub struct ForeignClassBinding {
    module_name : String
    class_name : String
    allocate : (Array[Value]) -> ForeignAllocationResult
    finalize : (Int) -> Unit
    }

    Host lifecycle callbacks associated with one Wren foreign class.

    ForeignClassBinding::new

    fn ForeignClassBinding::new(module_name : String, class_name : String, allocate : (Array[Value]) -> ForeignAllocationResult, finalize : (Int) -> Unit) -> ForeignClassBinding

    ForeignContextResult

    pub(all) enum ForeignContextResult {
    ForeignContextReturned(ForeignOwnedValue)
    ForeignContextAborted(String)
    }

    ForeignMethodBinding

    pub struct ForeignMethodBinding {
    module_name : String
    class_name : String
    is_static : Bool
    signature : String
    callback : (Value, Array[Value]) -> ForeignCallResult?
    handle_callback : (Int, Array[Value]) -> ForeignCallResult?
    context_callback : (ForeignCallContext) -> ForeignContextResult?
    handle_context_callback : (Int, ForeignCallContext) -> ForeignContextResult?
    }

    One host implementation identified using Wren's binding tuple.

    ForeignMethodBinding::new

    fn ForeignMethodBinding::new(module_name : String, class_name : String, is_static : Bool, signature : String, callback : (Value, Array[Value]) -> ForeignCallResult) -> ForeignMethodBinding

    ForeignMethodBinding::new_context

    fn ForeignMethodBinding::new_context(module_name : String, class_name : String, is_static : Bool, signature : String, callback : (ForeignCallContext) -> ForeignContextResult) -> ForeignMethodBinding

    Bind a method through the richer VM-independent context API. The callback may return nested Lists and Maps, arbitrary String bytes, or pass through an existing argument value without depending on private runtime identifiers.

    ForeignMethodBinding::new_context_for_foreign_class

    fn ForeignMethodBinding::new_context_for_foreign_class(module_name : String, class_name : String, signature : String, callback : (Int, ForeignCallContext) -> ForeignContextResult) -> ForeignMethodBinding

    Context-aware variant for an instance of a foreign class.

    ForeignMethodBinding::new_for_foreign_class

    fn ForeignMethodBinding::new_for_foreign_class(module_name : String, class_name : String, signature : String, callback : (Int, Array[Value]) -> ForeignCallResult) -> ForeignMethodBinding

    Bind an instance method that receives the opaque handle allocated for a foreign class instead of the Wren receiver value.

    ForeignOwnedMapEntry

    pub(all) struct ForeignOwnedMapEntry {
    key : ForeignOwnedValue
    value : ForeignOwnedValue
    }

    ForeignOwnedMapEntry::new

    ForeignOwnedValue

    pub(all) enum ForeignOwnedValue {
    ForeignNull
    ForeignBool(Bool)
    ForeignNumber(Double)
    ForeignString(String)
    ForeignBytes(Array[Int])
    ForeignRange(Double, Double, Bool)
    ForeignList(Array[ForeignOwnedValue])
    ForeignMap(Array[ForeignOwnedMapEntry])
    ForeignExisting(Value)
    }

    Runtime-independent value tree returned by a context-aware foreign method. Lists and maps are materialized inside the receiving VM after the callback returns, so host packages never need access to runtime object identifiers.

    HostObjectHandle

    pub(all) struct HostObjectHandle {
    slot : Int
    generation : Int
    } derive(Eq,
    Debug
    )

    A generation-checked handle for host-owned objects referenced by foreign Wren instances. It prevents stale identifiers from observing reused slots.

    HostObjectHandle::equal

    HostObjectHandle::not_equal

    fn HostObjectHandle::not_equal(x : HostObjectHandle, y : HostObjectHandle) -> Bool

    HostObjectSlot

    pub struct HostObjectSlot[T] {
    value : T?
    generation : Int
    }

    HostObjectTable

    pub struct HostObjectTable[T] {
    slots : Array[HostObjectSlot[T]]
    }

    Small host-side arena useful when implementing ForeignClassBinding.

    HostObjectTable::get

    fn[T] HostObjectTable::get(self : HostObjectTable[T], handle : HostObjectHandle) -> T?

    HostObjectTable::insert

    fn[T] HostObjectTable::insert(self : HostObjectTable[T], value : T) -> HostObjectHandle

    HostObjectTable::live_count

    fn[T] HostObjectTable::live_count(self : HostObjectTable[T]) -> Int

    HostObjectTable::new

    fn[T] HostObjectTable::new() -> HostObjectTable[T]

    HostObjectTable::release

    fn[T] HostObjectTable::release(self : HostObjectTable[T], handle : HostObjectHandle) -> Bool

    ImportBinding

    pub(all) struct ImportBinding {
    name : String
    local_name : String
    } derive(Eq,
    Debug
    )

    One explicitly imported top-level name and its optional local alias.

    ImportBinding::equal

    ImportBinding::not_equal

    fn ImportBinding::not_equal(x : ImportBinding, y : ImportBinding) -> Bool

    LanguageDocument

    pub(all) struct LanguageDocument {
    source_name : String
    source : String
    tokens : Array[Token]
    statements : Array[Stmt]
    diagnostics : Array[Diagnostic]
    symbols : Array[LanguageSymbol]
    }

    Parsed editor document used by the reusable LSP service core.

    LanguageDocument::completions

    fn LanguageDocument::completions(self : LanguageDocument, prefix : String) -> Array[String]

    LanguageDocument::definition

    fn LanguageDocument::definition(self : LanguageDocument, offset : Int) -> LanguageLocation?

    LanguageDocument::hover

    fn LanguageDocument::hover(self : LanguageDocument, offset : Int) -> LanguageHover?

    LanguageDocument::new

    fn LanguageDocument::new(source_name : String, source : String) -> LanguageDocument

    LanguageDocument::references

    fn LanguageDocument::references(self : LanguageDocument, offset : Int) -> Array[LanguageLocation]

    LanguageDocument::rename

    fn LanguageDocument::rename(self : LanguageDocument, offset : Int, new_name : String) -> Array[LanguageTextEdit]?

    LanguageDocument::token_at

    fn LanguageDocument::token_at(self : LanguageDocument, offset : Int) -> Token?

    LanguageHover

    pub(all) struct LanguageHover {
    title : String
    detail : String
    span : SourceSpan
    } derive(Eq,
    Debug
    )

    LanguageHover::equal

    LanguageHover::not_equal

    fn LanguageHover::not_equal(x : LanguageHover, y : LanguageHover) -> Bool

    LanguageLocation

    pub(all) struct LanguageLocation {
    source_name : String
    span : SourceSpan
    } derive(Eq,
    Debug
    )

    LanguageLocation::equal

    LanguageLocation::not_equal

    fn LanguageLocation::not_equal(x : LanguageLocation, y : LanguageLocation) -> Bool

    LanguageServer

    pub(all) struct LanguageServer {
    documents : Map[String, LanguageDocument]
    }

    Stateful document registry that can be embedded behind an LSP transport.

    LanguageServer::close

    fn LanguageServer::close(self : LanguageServer, source_name : String) -> Bool

    LanguageServer::document

    fn LanguageServer::document(self : LanguageServer, source_name : String) -> LanguageDocument?

    LanguageServer::new

    LanguageServer::open

    fn LanguageServer::open(self : LanguageServer, source_name : String, source : String) -> Array[Diagnostic]

    LanguageSymbol

    pub(all) struct LanguageSymbol {
    name : String
    kind : LanguageSymbolKind
    span : SourceSpan
    container : String?
    } derive(Eq,
    Debug
    )

    LanguageSymbol::equal

    LanguageSymbol::not_equal

    fn LanguageSymbol::not_equal(x : LanguageSymbol, y : LanguageSymbol) -> Bool

    LanguageSymbolKind

    pub(all) enum LanguageSymbolKind {
    SymbolVariable
    SymbolClass
    SymbolMethod
    SymbolParameter
    SymbolImport
    } derive(Eq,
    Debug
    )

    LanguageSymbolKind::equal

    LanguageSymbolKind::not_equal

    LanguageTextEdit

    pub(all) struct LanguageTextEdit {
    source_name : String
    span : SourceSpan
    replacement : String
    } derive(Eq,
    Debug
    )

    LanguageTextEdit::equal

    LanguageTextEdit::not_equal

    fn LanguageTextEdit::not_equal(x : LanguageTextEdit, y : LanguageTextEdit) -> Bool

    MapEntryExpr

    pub(all) struct MapEntryExpr {
    key : Expr
    value : Expr
    } derive(Eq,
    Debug
    )

    One key-value expression pair retained by a map literal.

    MapEntryExpr::equal

    MapEntryExpr::not_equal

    fn MapEntryExpr::not_equal(x : MapEntryExpr, y : MapEntryExpr) -> Bool

    MethodDecl

    pub(all) struct MethodDecl {
    name : String
    parameters : Array[String]
    body : Array[Stmt]
    is_constructor : Bool
    is_getter : Bool
    is_static : Bool
    is_foreign : Bool
    attributes : Array[AttributeDecl]
    span : SourceSpan
    } derive(Eq,
    Debug
    )

    One instance method, getter, or constructor declared in a class body.

    MethodDecl::equal

    fn MethodDecl::equal(MethodDecl, MethodDecl) -> Bool

    MethodDecl::not_equal

    fn MethodDecl::not_equal(x : MethodDecl, y : MethodDecl) -> Bool

    ModuleArchiveResult

    pub(all) enum ModuleArchiveResult {
    ModuleArchiveDecoded(Array[VerifiedModule])
    ModuleArchiveFailed(String)
    }

    Result of decoding a deterministic MoonWren module archive.

    ModuleLoadResult

    pub(all) enum ModuleLoadResult {
    ModuleLoaded(String, String)
    ModuleLoadFailed(String)
    } derive(Eq,
    Debug
    )

    Result returned by an embedding application's module loader.

    ModuleLoadResult::equal

    ModuleLoadResult::not_equal

    fn ModuleLoadResult::not_equal(x : ModuleLoadResult, y : ModuleLoadResult) -> Bool

    ModuleSnapshot

    pub(all) struct ModuleSnapshot {
    names : Array[String]
    checksums : Array[String]
    }

    Content snapshot used by polling file watchers and hot-reload hosts.

    ModuleSnapshot::changes

    fn ModuleSnapshot::changes(self : ModuleSnapshot, newer : ModuleSnapshot) -> Array[String]

    Return added, changed and removed names between two snapshots.

    ModuleSnapshot::from_modules

    fn ModuleSnapshot::from_modules(modules : Array[VerifiedModule]) -> ModuleSnapshot

    ModuleSource

    pub(all) struct ModuleSource {
    name : String
    source : String
    } derive(Eq,
    Debug
    )

    Named source used by the in-memory multi-module convenience API.

    ModuleSource::equal

    ModuleSource::new

    fn ModuleSource::new(name : String, source : String) -> ModuleSource

    ModuleSource::not_equal

    fn ModuleSource::not_equal(x : ModuleSource, y : ModuleSource) -> Bool

    ObservedVm

    pub struct ObservedVm {
    vm : Vm
    history_limit : Int
    history : Array[VmTelemetry]
    observers : Array[(VmTelemetry) -> Unit]
    next_operation_id : Int
    }

    ObservedVm::call

    fn ObservedVm::call(self : ObservedVm, handle : VmHandle, arguments : Array[Value]) -> ProgramRunResult

    ObservedVm::capture

    fn ObservedVm::capture(self : ObservedVm, module_name : String, variable : String) -> VmHandleResult

    ObservedVm::close

    fn ObservedVm::close(self : ObservedVm) -> Unit

    ObservedVm::history

    fn ObservedVm::history(self : ObservedVm) -> Array[VmTelemetry]

    ObservedVm::interpret

    fn ObservedVm::interpret(self : ObservedVm, source_name : String, source : String) -> ProgramRunResult

    ObservedVm::new

    fn ObservedVm::new(vm : Vm, history_limit : Int) -> ObservedVm

    ObservedVm::read

    fn ObservedVm::read(self : ObservedVm, module_name : String, variable : String) -> ProgramRunResult

    ObservedVm::release

    fn ObservedVm::release(self : ObservedVm, handle : VmHandle) -> Bool

    ObservedVm::reload_modules

    fn ObservedVm::reload_modules(self : ObservedVm, replacements : Array[ModuleSource], preserve : Array[ReloadStateSelection]) -> ProgramRunResult

    ObservedVm::subscribe

    fn ObservedVm::subscribe(self : ObservedVm, observer : (VmTelemetry) -> Unit) -> Unit

    ObservedVm::underlying

    fn ObservedVm::underlying(self : ObservedVm) -> Vm

    ProgramParseResult

    pub(all) enum ProgramParseResult {
    ProgramParsed(Array[Stmt])
    ProgramParseFailed(Array[Diagnostic])
    }

    ProgramRunResult

    pub(all) enum ProgramRunResult {
    ProgramCompleted(Value, Array[String])
    ProgramFailed(Array[Diagnostic], Array[String])
    }

    ProgramRunResult::deliver

    fn ProgramRunResult::deliver(self : ProgramRunResult, write : (String) -> Unit, report : (Diagnostic) -> Unit) -> ProgramRunResult

    Deliver captured output and diagnostics through host callbacks while retaining the ordinary result for further inspection.

    ReloadStateArchive

    pub(all) struct ReloadStateArchive {
    module_name : String
    archive : String
    }

    ReloadStateSelection

    pub(all) struct ReloadStateSelection {
    module_name : String
    globals : Array[String]
    }

    ReloadStateSelection::new

    fn ReloadStateSelection::new(module_name : String, globals : Array[String]) -> ReloadStateSelection

    ReplResult

    pub(all) enum ReplResult {
    ReplAccepted(Value, Array[String])
    ReplRejected(Array[Diagnostic])
    }

    ReplSession

    pub struct ReplSession {
    history : String
    prior_output_lines : Int
    max_steps : Int
    }

    A deterministic incremental console. Accepted submissions are replayed as one program, so declarations and assignments remain visible while failed submissions leave the session unchanged.

    ReplSession::new

    fn ReplSession::new(max_steps : Int) -> ReplSession

    ReplSession::reset

    fn ReplSession::reset(self : ReplSession) -> Unit

    ReplSession::source

    fn ReplSession::source(self : ReplSession) -> String

    ReplSession::submit

    fn ReplSession::submit(self : ReplSession, source : String) -> ReplResult

    ScanResult

    pub(all) struct ScanResult {
    tokens : Array[Token]
    diagnostics : Array[Diagnostic]
    }

    Tokens and recoverable diagnostics produced from one source string.

    ScanResult::is_success

    fn ScanResult::is_success(self : ScanResult) -> Bool

    ScheduledTaskEntry

    pub struct ScheduledTaskEntry {
    identifier : Int
    task : VmAsyncTask
    status : VmScheduledTaskStatus
    request : VmAsyncRequest?
    response : Value?
    wake_at : Double
    joined : Array[Int]
    race : Bool
    result : Value
    result_root : VmHandle?
    issues : Array[Diagnostic]
    pending_output : Array[String]
    }

    SchedulerReplayDecodeResult

    pub(all) enum SchedulerReplayDecodeResult {
    SchedulerReplayDecoded(SchedulerReplayLog)
    SchedulerReplayDecodeFailed(String)
    }

    SchedulerReplayEvent

    pub(all) enum SchedulerReplayEvent {
    ReplayAdvance(Double)
    ReplayDeliver(Int, ForeignOwnedValue)
    ReplayCancel(Int)
    ReplayObserve(String)
    }

    SchedulerReplayLog

    pub(all) struct SchedulerReplayLog {
    workload_digest : String
    events : Array[SchedulerReplayEvent]
    }

    SchedulerReplayResult

    pub(all) enum SchedulerReplayResult {
    SchedulerReplayCompleted(Int)
    SchedulerReplayDiverged(Int, String, String)
    SchedulerReplayInvalid(String)
    }

    Scope

    type Scope

    SignedDeploymentBundle

    pub(all) struct SignedDeploymentBundle {
    manifest : DeploymentManifest
    modules : Array[VerifiedModule]
    payload_sha256 : String
    key_id : String
    signature : String
    }

    SourcePosition

    pub(all) struct SourcePosition {
    offset : Int
    line : Int
    column : Int
    } derive(Eq,
    Debug
    )

    A one-based location in a source file.

    SourcePosition::equal

    SourcePosition::not_equal

    fn SourcePosition::not_equal(x : SourcePosition, y : SourcePosition) -> Bool

    SourcePosition::start

    SourceSpan

    pub(all) struct SourceSpan {
    start : SourcePosition
    end : SourcePosition
    } derive(Eq,
    Debug
    )

    Half-open source range. start is inclusive and end is exclusive.

    SourceSpan::column

    fn SourceSpan::column(self : SourceSpan) -> Int

    SourceSpan::empty

    fn SourceSpan::empty() -> SourceSpan

    SourceSpan::equal

    fn SourceSpan::equal(SourceSpan, SourceSpan) -> Bool

    SourceSpan::length

    fn SourceSpan::length(self : SourceSpan) -> Int

    SourceSpan::line

    fn SourceSpan::line(self : SourceSpan) -> Int

    SourceSpan::merge

    fn SourceSpan::merge(first : SourceSpan, second : SourceSpan) -> SourceSpan

    SourceSpan::not_equal

    fn SourceSpan::not_equal(x : SourceSpan, y : SourceSpan) -> Bool

    Stmt

    pub(all) enum Stmt {
    ExpressionStatement(Expr, SourceSpan)
    VariableStatement(String, Expr?, SourceSpan)
    BlockStatement(Array[Stmt], SourceSpan)
    IfStatement(Expr, Stmt, Stmt?, SourceSpan)
    WhileStatement(Expr, Stmt, SourceSpan)
    ForStatement(String, Expr, Stmt, SourceSpan)
    ReturnStatement(Expr?, SourceSpan)
    BreakStatement(SourceSpan)
    ContinueStatement(SourceSpan)
    ImportStatement(String, Array[ImportBinding], SourceSpan)
    ClassStatement(String, Expr?, Array[MethodDecl], Array[AttributeDecl], Bool, SourceSpan)
    } derive(Eq,
    Debug
    )

    Statements for the first executable subset of the language.

    Stmt::equal

    fn Stmt::equal(Stmt, Stmt) -> Bool

    Stmt::not_equal

    fn Stmt::not_equal(x : Stmt, y : Stmt) -> Bool

    Stmt::span

    fn Stmt::span(self : Stmt) -> SourceSpan

    Stmt::to_repr

    Token

    pub(all) struct Token {
    kind : TokenKind
    lexeme : String
    span : SourceSpan
    }

    A token retains its original source spelling for diagnostics and parsing.

    Token::is_keyword

    fn Token::is_keyword(self : Token) -> Bool

    Token::new

    fn Token::new(kind : TokenKind, lexeme : String, span : SourceSpan) -> Token

    TokenKind

    pub(all) enum TokenKind {
    LeftParen
    RightParen
    LeftBrace
    RightBrace
    LeftBracket
    RightBracket
    Colon
    Comma
    Dot
    DotDot
    DotDotDot
    Minus
    Plus
    Slash
    Star
    Percent
    Pipe
    PipePipe
    Ampersand
    AmpersandAmpersand
    Caret
    Tilde
    Question
    Hash
    Bang
    BangEqual
    Equal
    EqualEqual
    Less
    LessEqual
    LessLess
    Greater
    GreaterEqual
    GreaterGreater
    Newline
    Identifier
    Field
    StaticField
    Number
    StringLiteral
    BreakKeyword
    ClassKeyword
    ConstructKeyword
    ContinueKeyword
    ElseKeyword
    FalseKeyword
    ForKeyword
    ForeignKeyword
    IfKeyword
    ImportKeyword
    AsKeyword
    InKeyword
    IsKeyword
    NullKeyword
    ReturnKeyword
    StaticKeyword
    SuperKeyword
    ThisKeyword
    TrueKeyword
    VarKeyword
    WhileKeyword
    Eof
    } derive(Eq,
    Debug
    )

    All punctuation, operators, literals, and reserved words recognized by Wren.

    TokenKind::equal

    fn TokenKind::equal(TokenKind, TokenKind) -> Bool

    TokenKind::not_equal

    fn TokenKind::not_equal(x : TokenKind, y : TokenKind) -> Bool

    UnaryOperator

    pub(all) enum UnaryOperator {
    Negate
    LogicalNot
    BitwiseNot
    } derive(Eq,
    Debug
    )

    UnaryOperator::equal

    UnaryOperator::not_equal

    fn UnaryOperator::not_equal(x : UnaryOperator, y : UnaryOperator) -> Bool

    Value

    pub(all) enum Value {
    NullValue
    BoolValue(Bool)
    NumberValue(Double)
    StringValue(String)
    RawStringValue(Array[Int])
    RangeValue(Double, Double, Bool)
    ListValue(Int)
    MapValue(Int)
    SequenceValue(Int)
    FunctionValue(Int)
    FiberValue(Int)
    ClassValue(Int)
    MetaClassValue(String)
    ClassAttributesValue(Int, Int)
    InstanceValue(Int)
    SuperValue(Int, Int, String, Bool)
    SuperClassValue(Int, Int)
    CoreClassValue(CoreClass)
    IteratorValue(Int)
    MapEntryValue(Int)
    SystemValue
    } derive(Eq,
    Debug
    )

    Value::as_bool

    fn Value::as_bool(self : Value) -> ValueConversionResult[Bool]

    Value::as_number

    fn Value::as_number(self : Value) -> ValueConversionResult[Double]

    Value::as_range

    fn Value::as_range(self : Value) -> ValueConversionResult[(Double, Double, Bool)]

    Value::as_string

    fn Value::as_string(self : Value) -> ValueConversionResult[String]

    Value::bool

    fn Value::bool(value : Bool) -> Value

    Value::equal

    fn Value::equal(Value, Value) -> Bool

    Value::is_truthy

    fn Value::is_truthy(self : Value) -> Bool

    Wren considers false and null falsey; every other value is truthy.

    Value::not_equal

    fn Value::not_equal(x : Value, y : Value) -> Bool

    Value::null

    fn Value::null() -> Value

    Value::number

    fn Value::number(value : Double) -> Value

    Value::range

    fn Value::range(from : Double, to : Double, inclusive : Bool) -> Value

    Value::string

    fn Value::string(value : String) -> Value

    Value::to_repr

    Value::to_text

    fn Value::to_text(self : Value) -> String

    Convert a primitive value to its Wren-facing textual representation.

    Value::type_name

    fn Value::type_name(self : Value) -> String

    ValueConversionResult

    pub(all) enum ValueConversionResult[T] {
    ValueConverted(T)
    ValueConversionFailed(String, String)
    }

    Result of converting a dynamically typed Wren value at the host boundary.

    VerifiedModule

    pub(all) struct VerifiedModule {
    name : String
    source : String
    checksum : String
    }

    One integrity-checked source in an in-memory deployment bundle.

    VerifiedModule::new

    fn VerifiedModule::new(name : String, source : String) -> VerifiedModule

    pub struct Vm {
    identity : Int
    context_identifier : Int
    sources : Array[ModuleSource]
    roots : Array[String]
    handles : Array[VmHandleEntry]
    generation : Int
    closed : Bool
    limits : VmLimits
    fallback_loader : (String, String) -> ModuleLoadResult
    foreign_methods : Array[ForeignMethodBinding]
    foreign_classes : Array[ForeignClassBinding]
    should_cancel : () -> Bool
    automatic_gc : Bool
    gc_minimum_objects : Int
    gc_growth_percent : Int
    next_gc_objects : Int
    last_gc_stats : VmGcStats?
    }

    A long-lived Wren runtime. Modules, globals, classes, closures, Fibers and foreign objects remain alive across host calls until close or a successful transactional reload replaces the runtime generation.

    Vm::attach_debugger

    fn Vm::attach_debugger(self : Vm, breakpoints : Array[DebugBreakpoint], pause_on_entry : Bool, hook : (DebugSnapshot) -> DebugCommand) -> Bool

    Attach a synchronous live debugger to this VM. The hook executes before a statement and may inspect current variables and select the next stop mode. A hook used by a UI may block while waiting for user input, but must not re-enter the same VM.

    Vm::bind_method

    fn Vm::bind_method(self : Vm, receiver : VmHandle, method_name : String, arity : Int) -> VmMethodHandleResult

    Vm::call

    fn Vm::call(self : Vm, handle : VmHandle, arguments : Array[Value]) -> ProgramRunResult

    Call a captured Wren function from MoonBit.

    Vm::call_bound

    fn Vm::call_bound(self : Vm, bound : VmMethodHandle, arguments : Array[Value]) -> ProgramRunResult

    Vm::call_method

    fn Vm::call_method(self : Vm, handle : VmHandle, method_name : String, arguments : Array[Value]) -> ProgramRunResult

    Call a method or getter on a captured Wren value from MoonBit.

    Vm::cancel_async

    fn Vm::cancel_async(self : Vm, task : VmAsyncTask) -> Bool

    Cancel a task and release all VM roots owned by it.

    Vm::capture

    fn Vm::capture(self : Vm, module_name : String, variable : String) -> VmHandleResult

    Create a strong host root for a module variable.

    Vm::close

    fn Vm::close(self : Vm) -> Unit

    Finalize remaining foreign instances and permanently close the VM.

    Vm::collect_garbage

    fn Vm::collect_garbage(self : Vm) -> VmGcStats

    Trace VM roots and release unreachable instances. Suspended opaque continuations conservatively retain instances until the Fiber resumes.

    Vm::configure_automatic_gc

    fn Vm::configure_automatic_gc(self : Vm, policy : VmGcPolicy) -> Bool

    Enable automatic collection between host operations. Invalid policies are rejected without changing the active configuration.

    Vm::detach_debugger

    fn Vm::detach_debugger(self : Vm) -> Bool

    Vm::disable_automatic_gc

    fn Vm::disable_automatic_gc(self : Vm) -> Unit

    Vm::get

    fn Vm::get(self : Vm, handle : VmHandle, property_name : String) -> ProgramRunResult

    Read a Wren getter or built-in property from a captured value.

    Vm::has_module

    fn Vm::has_module(self : Vm, module_name : String) -> Bool

    Vm::has_variable

    fn Vm::has_variable(self : Vm, module_name : String, variable : String) -> Bool

    Vm::interpret

    fn Vm::interpret(self : Vm, source_name : String, source : String) -> ProgramRunResult

    Interpret and retain one named root module. Reusing an existing name is an explicit reload operation so accidental cache hits cannot hide new source.

    Vm::last_automatic_gc

    fn Vm::last_automatic_gc(self : Vm) -> VmGcStats?

    Vm::list_add

    fn Vm::list_add(self : Vm, handle : VmHandle, value : Value) -> VmHostResult[Unit]

    Vm::list_set

    fn Vm::list_set(self : Vm, handle : VmHandle, index : Int, value : Value) -> VmHostResult[Unit]

    Vm::list_snapshot

    fn Vm::list_snapshot(self : Vm, handle : VmHandle) -> VmHostResult[Array[Value]]

    Vm::map_get

    fn Vm::map_get(self : Vm, handle : VmHandle, key : Value) -> VmHostResult[Value?]

    Vm::map_remove

    fn Vm::map_remove(self : Vm, handle : VmHandle, key : Value) -> VmHostResult[Value?]

    Vm::map_set

    fn Vm::map_set(self : Vm, handle : VmHandle, key : Value, value : Value) -> VmHostResult[Unit]

    Vm::map_snapshot

    fn Vm::map_snapshot(self : Vm, handle : VmHandle) -> VmHostResult[Array[VmMapEntry]]

    Vm::new

    fn Vm::new(limits : VmLimits, loader : (String, String) -> ModuleLoadResult, foreign_methods : Array[ForeignMethodBinding], foreign_classes : Array[ForeignClassBinding]) -> Vm

    Vm::new_async_task

    fn Vm::new_async_task(self : Vm, fiber : VmHandle) -> VmAsyncTaskResult

    Retain a captured Fiber as a resumable host task.

    Vm::new_cancellable

    fn Vm::new_cancellable(limits : VmLimits, loader : (String, String) -> ModuleLoadResult, foreign_methods : Array[ForeignMethodBinding], foreign_classes : Array[ForeignClassBinding], should_cancel : () -> Bool) -> Vm

    Vm::new_scheduler

    fn Vm::new_scheduler(self : Vm, max_tasks : Int) -> VmScheduler

    Create a scheduler with virtual time starting at zero.

    Vm::read

    fn Vm::read(self : Vm, module_name : String, variable : String) -> ProgramRunResult

    Read a module variable without creating a strong host root. Runtime-backed values should be passed to retain before an explicit collection pass.

    Vm::release

    fn Vm::release(self : Vm, handle : VmHandle) -> Bool

    Release a strong host root. Released and pre-reload handles cannot be used.

    Vm::reload_module

    fn Vm::reload_module(self : Vm, module_name : String, source : String, preserve : Array[String]) -> ProgramRunResult

    Transactionally rebuild the VM from its root modules using a replacement source. Selected primitive globals are migrated after the replacement module initializes and before dependent roots execute. A failed rebuild leaves the current VM and all handles unchanged.

    Vm::reload_modules

    fn Vm::reload_modules(self : Vm, replacements : Array[ModuleSource], preserve : Array[ReloadStateSelection]) -> ProgramRunResult

    Atomically replace multiple modules and preserve complete selected state graphs without transforming the MWS1 archives.

    Vm::reload_modules_with_migration

    fn Vm::reload_modules_with_migration(self : Vm, replacements : Array[ModuleSource], preserve : Array[ReloadStateSelection], migrate : (ReloadStateArchive) -> Result[String, String]) -> ProgramRunResult

    Atomically replace several modules and migrate full MWS1 state graphs. The migration callback may validate or transform each archive before it enters the candidate runtime. No old runtime state changes until all replacements, migrations, dependent roots, and limits succeed.

    Vm::restore_state

    fn Vm::restore_state(self : Vm, archive : String) -> VmStateRestoreResult

    Restore an MWS1 archive into its named loaded module. All names and graph records are validated before any module binding is changed.

    Vm::resume_async

    fn Vm::resume_async(self : Vm, task : VmAsyncTask, request : VmAsyncRequest, response : Value) -> VmAsyncRunResult

    Resume a suspended task with the result of its yielded host request.

    Vm::retain

    fn Vm::retain(self : Vm, value : Value) -> VmHandleResult

    Retain a value returned by a VM call as a strong host root. Values that refer to runtime objects must be retained before the next explicit GC pass.

    Vm::save_state

    fn Vm::save_state(self : Vm, module_name : String, names : Array[String]) -> VmStateSaveResult

    Export selected globals. Primitive values, ranges, Strings (including raw bytes), Lists and Maps are portable; graph identity and cycles are kept.

    Vm::start_async

    fn Vm::start_async(self : Vm, task : VmAsyncTask, initial : Value?) -> VmAsyncRunResult

    Start a task. initial is delivered as the optional first Fiber argument.

    VmAsyncRequest

    pub struct VmAsyncRequest {
    vm_identity : Int
    generation : Int
    task_handle : Int
    sequence : Int
    value : Value
    }

    A single yielded host request. Requests are one-shot: only the matching task and sequence can consume them.

    VmAsyncRequest::sequence

    fn VmAsyncRequest::sequence(self : VmAsyncRequest) -> Int

    VmAsyncRequest::value

    fn VmAsyncRequest::value(self : VmAsyncRequest) -> Value

    VmAsyncRunResult

    pub(all) enum VmAsyncRunResult {
    VmAsyncYielded(VmAsyncRequest, Array[String])
    VmAsyncCompleted(Value, Array[String])
    VmAsyncFailed(Array[Diagnostic], Array[String])
    }

    VmAsyncTask

    pub struct VmAsyncTask {
    vm_identity : Int
    generation : Int
    fiber : VmHandle
    sequence : Int
    started : Bool
    waiting : Bool
    finished : Bool
    cancelled : Bool
    request_root : VmHandle?
    }

    A host-owned, resumable Wren Fiber. The task retains the Fiber while it is suspended, so unrelated VM operations and garbage collections are safe.

    VmAsyncTaskResult

    pub(all) enum VmAsyncTaskResult {
    VmAsyncTaskCreated(VmAsyncTask)
    VmAsyncTaskCreateFailed(Diagnostic)
    }

    VmGcPolicy

    pub(all) struct VmGcPolicy {
    minimum_objects : Int
    growth_percent : Int
    }

    Automatic collection policy evaluated between host operations. Collection never interrupts a running Wren call, so temporary host return values remain valid until the next VM operation unless retained with a handle.

    VmGcPolicy::new

    fn VmGcPolicy::new(minimum_objects : Int, growth_percent : Int) -> VmGcPolicy

    VmGcStats

    pub(all) struct VmGcStats {
    before_objects : Int
    reachable_objects : Int
    reclaimed_objects : Int
    before_instances : Int
    reachable_instances : Int
    reclaimed_instances : Int
    finalized_foreign_instances : Int
    }

    Summary returned by a persistent VM garbage-collection pass.

    VmHandle

    pub struct VmHandle {
    vm_identity : Int
    identifier : Int
    generation : Int
    }

    An opaque strong root owned by a persistent VM.

    VmHandleEntry

    pub struct VmHandleEntry {
    value : Value
    generation : Int
    alive : Bool
    }

    Internal strong-root entry retained by a Vm.

    VmHandleResult

    pub(all) enum VmHandleResult {
    VmHandleCreated(VmHandle)
    VmHandleFailed(Diagnostic)
    }

    VmHostResult

    pub(all) enum VmHostResult[T] {
    VmHostSucceeded(T)
    VmHostFailed(Diagnostic)
    }

    Typed result returned by host-side inspection and mutation helpers.

    VmLimits

    pub(all) struct VmLimits {
    max_steps : Int
    max_call_depth : Int
    max_output_characters : Int
    max_modules : Int
    max_objects : Int
    max_source_characters : Int
    }

    Per-operation resource limits for a persistent Vm.

    VmLimits::new

    fn VmLimits::new(max_steps : Int, max_call_depth : Int, max_output_characters : Int, max_modules : Int, max_objects : Int, max_source_characters : Int) -> VmLimits

    VmLimits::standard

    fn VmLimits::standard(max_steps : Int) -> VmLimits

    Limits suitable for ordinary embedded scripts.

    VmMapEntry

    pub(all) struct VmMapEntry {
    key : Value
    value : Value
    }

    VmMethodHandle

    pub struct VmMethodHandle {
    vm_identity : Int
    generation : Int
    receiver : VmHandle
    method_name : String
    arity : Int
    }

    Cached receiver, method name, and arity for repeated host calls.

    VmMethodHandleResult

    pub(all) enum VmMethodHandleResult {
    VmMethodHandleCreated(VmMethodHandle)
    VmMethodHandleFailed(Diagnostic)
    }

    VmPool

    pub struct VmPool {
    identity : Int
    config : VmPoolConfig
    factory : () -> Vm
    entries : Array[VmPoolEntry]
    closed : Bool
    next_token : Int
    created : Int
    recycled : Int
    acquisitions : Int
    rejections : Int
    }

    Bounded VM pool with per-tenant concurrency controls and optional reset on every release. The isolated configuration is the safe default for mutually untrusted tenants.

    VmPool::acquire

    fn VmPool::acquire(self : VmPool, tenant : String) -> VmPoolAcquireResult

    VmPool::close

    fn VmPool::close(self : VmPool) -> Unit

    VmPool::invalidate

    fn VmPool::invalidate(self : VmPool, lease : VmPoolLease) -> Bool

    Release and unconditionally destroy the leased VM after a runtime failure or suspected tenant contamination.

    VmPool::new

    fn VmPool::new(config : VmPoolConfig, factory : () -> Vm) -> VmPool

    VmPool::release

    fn VmPool::release(self : VmPool, lease : VmPoolLease) -> Bool

    Release a healthy lease. Isolated pools immediately replace its VM; reusable pools replace it at the configured use limit.

    VmPool::stats

    fn VmPool::stats(self : VmPool) -> VmPoolStats

    VmPool::with_vm

    fn[T] VmPool::with_vm(self : VmPool, lease : VmPoolLease, operation : (Vm) -> T) -> VmPoolUseResult[T]

    Execute one host operation against a validated lease. The callback should not retain the VM after it returns.

    VmPoolAcquireResult

    pub(all) enum VmPoolAcquireResult {
    VmPoolAcquired(VmPoolLease)
    VmPoolExhausted(String)
    }

    VmPoolConfig

    pub(all) struct VmPoolConfig {
    size : Int
    max_uses_per_vm : Int
    max_leases_per_tenant : Int
    reset_on_release : Bool
    }

    VmPoolConfig::isolated

    fn VmPoolConfig::isolated(size : Int, max_leases_per_tenant : Int) -> VmPoolConfig

    VmPoolConfig::new

    fn VmPoolConfig::new(size : Int, max_uses_per_vm : Int, max_leases_per_tenant : Int, reset_on_release : Bool) -> VmPoolConfig

    VmPoolEntry

    pub struct VmPoolEntry {
    vm : Vm
    busy : Bool
    token : Int
    uses : Int
    tenant : String?
    }

    VmPoolLease

    pub struct VmPoolLease {
    pool_identity : Int
    entry_index : Int
    token : Int
    tenant : String
    }

    VmPoolStats

    pub(all) struct VmPoolStats {
    capacity : Int
    active : Int
    created : Int
    recycled : Int
    acquisitions : Int
    rejections : Int
    }

    VmPoolUseResult

    pub(all) enum VmPoolUseResult[T] {
    VmPoolUsed(T)
    VmPoolLeaseRejected(String)
    }

    VmScheduledTaskStatus

    pub(all) enum VmScheduledTaskStatus {
    ScheduledReady
    ScheduledWaitingForHost
    ScheduledSleeping
    ScheduledJoining
    ScheduledCompleted
    ScheduledFailed
    ScheduledCancelled
    } derive(Eq,
    Debug
    )

    Observable state of one task managed by VmScheduler.

    VmScheduledTaskStatus::equal

    VmScheduledTaskStatus::not_equal

    VmScheduler

    pub struct VmScheduler {
    vm : Vm
    entries : Array[ScheduledTaskEntry]
    now_milliseconds : Double
    max_tasks : Int
    closed : Bool
    }

    Deterministic cooperative task scheduler layered over the resumable Fiber bridge. Time advances only when the host calls advance, making tests and embedded event-loop integration reproducible.

    VmScheduler::advance

    fn VmScheduler::advance(self : VmScheduler, milliseconds : Double) -> Bool

    Advance virtual monotonic time and make due sleepers runnable.

    VmScheduler::cancel

    fn VmScheduler::cancel(self : VmScheduler, task_identifier : Int) -> Bool

    VmScheduler::close

    fn VmScheduler::close(self : VmScheduler) -> Unit

    Cancel unfinished work and release all retained task results.

    VmScheduler::deliver

    fn VmScheduler::deliver(self : VmScheduler, task_identifier : Int, response : Value) -> Bool

    Supply the result of an arbitrary host request yielded by a task.

    VmScheduler::deliver_owned

    fn VmScheduler::deliver_owned(self : VmScheduler, task_identifier : Int, response : ForeignOwnedValue) -> Bool

    Materialize host-owned recursive data inside this scheduler's VM and deliver it to a suspended task.

    VmScheduler::now

    fn VmScheduler::now(self : VmScheduler) -> Double

    VmScheduler::poll

    Run until one task completes, fails, yields a host request, or no task is currently runnable. Call again after resume or advance.

    VmScheduler::snapshot_request

    fn VmScheduler::snapshot_request(self : VmScheduler, request : VmAsyncRequest) -> ForeignOwnedValue?

    Copy an external request into host-owned recursive data. This makes HTTP and other structured yielded requests inspectable without exposing VM-local collection identifiers. Unsupported runtime objects and excessive nesting return None.

    VmScheduler::spawn

    fn VmScheduler::spawn(self : VmScheduler, callable : VmHandle) -> VmSchedulerSpawnResult

    Add a retained Fiber or zero-argument function to the scheduler.

    VmScheduler::status

    fn VmScheduler::status(self : VmScheduler, task_identifier : Int) -> VmScheduledTaskStatus?

    VmSchedulerEvent

    pub(all) enum VmSchedulerEvent {
    VmSchedulerIdle
    VmSchedulerExternalRequest(Int, VmAsyncRequest, Array[String])
    VmSchedulerTaskCompleted(Int, Value, Array[String])
    VmSchedulerTaskFailed(Int, Array[Diagnostic], Array[String])
    }

    One externally visible scheduler transition. Timer, spawn and join requests are consumed internally; arbitrary yielded values are returned to the host.

    VmSchedulerRecorder

    pub struct VmSchedulerRecorder {
    scheduler : VmScheduler
    workload_digest : String
    events : Array[SchedulerReplayEvent]
    }

    VmSchedulerRecorder::advance

    fn VmSchedulerRecorder::advance(self : VmSchedulerRecorder, milliseconds : Double) -> Bool

    VmSchedulerRecorder::cancel

    fn VmSchedulerRecorder::cancel(self : VmSchedulerRecorder, task_identifier : Int) -> Bool

    VmSchedulerRecorder::deliver

    fn VmSchedulerRecorder::deliver(self : VmSchedulerRecorder, task_identifier : Int, response : ForeignOwnedValue) -> Bool

    VmSchedulerRecorder::log

    VmSchedulerRecorder::new

    fn VmSchedulerRecorder::new(scheduler : VmScheduler, workload_digest : String) -> VmSchedulerRecorder

    VmSchedulerRecorder::poll

    VmSchedulerSpawnResult

    pub(all) enum VmSchedulerSpawnResult {
    VmSchedulerSpawned(Int)
    VmSchedulerSpawnFailed(Diagnostic)
    }

    Result of adding a Fiber or zero-argument function to a scheduler.

    VmStateRestoreResult

    pub(all) enum VmStateRestoreResult {
    VmStateRestored(Int)
    VmStateRestoreFailed(Diagnostic)
    }

    Result of atomically restoring globals from a portable state archive.

    VmStateSaveResult

    pub(all) enum VmStateSaveResult {
    VmStateSaved(String)
    VmStateSaveFailed(Diagnostic)
    }

    Result of exporting selected module globals to a portable MWS1 archive.

    VmTelemetry

    pub(all) struct VmTelemetry {
    operation_id : Int
    operation : String
    source_name : String
    succeeded : Bool
    diagnostic_count : Int
    steps : Int
    duration_milliseconds : Double
    output_lines : Int
    output_characters : Int
    loaded_modules : Int
    allocated_objects : Int
    live_fibers : Int
    foreign_calls : Int
    peak_call_depth : Int
    last_gc_reclaimed_objects : Int
    }

    build_signed_deployment_bundle

    fn build_signed_deployment_bundle(entry_module : String, modules : Array[VerifiedModule], capabilities : Array[String], compiler_abi : String, key_id : String, signer : (String) -> String) -> DeploymentBundleResult

    Validate every module with the compiler, canonicalize capabilities, and create a signed deployment bundle. signer receives the canonical payload SHA-256 and may use Ed25519, a hardware key, or a remote signing service.

    compile_bytecode

    fn compile_bytecode(source : String) -> BytecodeCompileResult

    Compile one anonymous source through the complete hybrid bytecode backend.

    compile_module_bytecode

    fn compile_module_bytecode(source_name : String, source : String) -> BytecodeCompileResult

    Compile a named module through the complete hybrid bytecode backend.

    decode_module_archive

    fn decode_module_archive(archive : String) -> ModuleArchiveResult

    Decode an MWA1 archive and reject malformed lengths, unsafe or duplicate module names, trailing data, and checksum mismatches.

    decode_scheduler_replay_log

    fn decode_scheduler_replay_log(encoded : String) -> SchedulerReplayDecodeResult

    decode_signed_deployment_bundle

    fn decode_signed_deployment_bundle(encoded : String) -> DeploymentBundleResult

    Decode and integrity-check MWDS1. Signature trust is intentionally a separate verification step so the host selects keys.

    deployment_bundle_loader

    fn deployment_bundle_loader(bundle : SignedDeploymentBundle) -> ((String, String) -> ModuleLoadResult)

    disassemble_bytecode

    fn disassemble_bytecode(program : BytecodeProgram) -> Array[String]

    Render bytecode with instruction offsets and source positions. This is the stable inspection surface used by debuggers and teaching tools.

    encode_module_archive

    fn encode_module_archive(modules : Array[VerifiedModule]) -> String

    Encode modules into the deterministic MWA1 archive format. Lengths count Unicode characters, so sources may contain newlines, NULs and non-ASCII text without escaping or platform-dependent byte conversions.

    encode_scheduler_replay_log

    fn encode_scheduler_replay_log(log : SchedulerReplayLog) -> String?

    Encode a replay transcript into the deterministic MWR1 format.

    encode_signed_deployment_bundle

    fn encode_signed_deployment_bundle(bundle : SignedDeploymentBundle) -> String

    Encode a signed bundle to the deterministic MWDS1 transport format.

    evaluate

    fn evaluate(source : String) -> EvaluationResult

    Parse and evaluate one standalone expression.

    module_checksum

    fn module_checksum(source : String) -> String

    Stable FNV-1a checksum used to detect accidental bundle corruption. This is not intended to replace a cryptographic signature at a trust boundary.

    parse_expression

    fn parse_expression(source : String) -> ExpressionParseResult

    Parse one complete expression, including its lexical analysis phase.

    parse_program

    fn parse_program(source : String) -> ProgramParseResult

    Parse a complete source file containing declarations and statements.

    profile_bytecode

    fn profile_bytecode(program : BytecodeProgram, max_steps : Int) -> BytecodeProfile

    Execute bytecode and return dynamic instruction, stack, branch and variable-access counters for profiling and regression analysis.

    replay_scheduler_log

    fn replay_scheduler_log(scheduler : VmScheduler, log : SchedulerReplayLog, expected_workload_digest : String) -> SchedulerReplayResult

    run

    fn run(source : String) -> ProgramRunResult

    Run a source file using a conservative default step budget.

    run_bytecode

    fn run_bytecode(program : BytecodeProgram, max_steps : Int) -> BytecodeRunResult

    Execute compiled bytecode with a deterministic instruction budget.

    run_bytecode_with_bindings

    fn run_bytecode_with_bindings(program : BytecodeProgram, max_steps : Int, loader : (String, String) -> ModuleLoadResult, foreign_methods : Array[ForeignMethodBinding], foreign_classes : Array[ForeignClassBinding]) -> BytecodeRunResult

    Execute complete bytecode semantics with host-provided modules and foreign bindings. Complex object operations currently use semantic escape instructions while sharing the same environment, limits, and object heap.

    run_bytecode_with_loader

    fn run_bytecode_with_loader(program : BytecodeProgram, max_steps : Int, loader : (String, String) -> ModuleLoadResult) -> BytecodeRunResult

    run_compiled

    fn run_compiled(source : String, max_steps : Int) -> BytecodeRunResult

    Compile and execute source through the optional bytecode backend.

    run_modules

    fn run_modules(entry_name : String, modules : Array[ModuleSource], max_steps : Int) -> ProgramRunResult

    Run an entry module from a complete in-memory source collection. Import specifiers are matched against module names exactly.

    run_with_foreign_bindings

    fn run_with_foreign_bindings(source_name : String, source : String, max_steps : Int, loader : (String, String) -> ModuleLoadResult, foreign_methods : Array[ForeignMethodBinding], foreign_classes : Array[ForeignClassBinding]) -> ProgramRunResult

    Run one named entry module with host implementations for foreign methods and host-owned foreign class state.

    run_with_foreign_methods

    fn run_with_foreign_methods(source_name : String, source : String, max_steps : Int, loader : (String, String) -> ModuleLoadResult, foreign_methods : Array[ForeignMethodBinding]) -> ProgramRunResult

    Run a named entry module with host implementations for declared foreign methods. Bindings are matched by module, class, static flag, and signature.

    run_with_limit

    fn run_with_limit(source : String, max_steps : Int) -> ProgramRunResult

    Run a source file with a configurable guard against unbounded loops.

    run_with_loader

    fn run_with_loader(source_name : String, source : String, max_steps : Int, loader : (String, String) -> ModuleLoadResult) -> ProgramRunResult

    Run one named entry module and resolve imports through an embedding callback.

    scan

    fn scan(source : String) -> ScanResult

    Tokenize a Wren source string while collecting all recoverable scan errors.

    sha256_hex

    fn sha256_hex(text : String) -> String

    Cryptographic SHA-256 digest encoded as lowercase hexadecimal. Deployment bundles use UTF-8 bytes so the result is stable across native and Wasm targets.

    telemetry_chrome_trace

    fn telemetry_chrome_trace(history : Array[VmTelemetry]) -> String

    Export complete-duration events accepted by Chrome, Perfetto, and other trace-event viewers.

    telemetry_prometheus

    fn telemetry_prometheus(history : Array[VmTelemetry], prefix : String) -> String

    Export aggregate counters in Prometheus text exposition format. The prefix is normalized to letters, digits, underscores, and colons.

    trace_bytecode

    fn trace_bytecode(program : BytecodeProgram, max_steps : Int) -> BytecodeTrace

    Execute while capturing an instruction-by-instruction trace. Source-level debugger UIs can filter events by instruction.span.line() for breakpoints.

    verified_module_loader

    fn verified_module_loader(modules : Array[VerifiedModule]) -> ((String, String) -> ModuleLoadResult)

    Build a sandboxed loader from a checked source bundle. Absolute paths and traversal segments are rejected before lookup.

    verify_signed_deployment_bundle

    fn verify_signed_deployment_bundle(bundle : SignedDeploymentBundle, verifier : (String, String, String) -> Bool) -> DeploymentBundleResult

    Verify module checksums, compiler metadata, canonical payload digest, and the external signature before returning a loader.