MoonBit Eval Package
Dependencies
let vm = MoonBitVM()
// Basic expressions
inspect(vm.eval("1 + 2 * 3"), content="7")
inspect(vm.eval("\"hello\" + \" world\""), content="hello world")
// Variables and functions
inspect(vm.eval("let x = 42"), content="()")
inspect(vm.eval("fn double(n: Int) -> Int { n * 2 }"), content="(n: Int) -> Int")
inspect(vm.eval("double(x)"), content="84")
// Control flow
inspect(vm.eval("if x > 40 { \"big\" } else { \"small\" }"), content="big")
// Pattern matching
inspect(vm.eval("match (1, 2) { (a, b) => a + b }"), content="3")
// Using aliases (new parser style)
inspect(vm.eval("using @int {abs}"), content="()")
inspect(vm.eval("abs(-5)"), content="5")let vm = MoonBitVM()
let expr = vm.compile("x + y * 2", params=["x", "y"])
inspect(
expr.run(vm, args=[3, 4]),
content="11",
)
inspect(
expr.run(vm, args=[10, 1]),
content="12",
)let vm = MoonBitVM()
inspect(
vm.eval(
(
#|import {
#| "moonbitlang/core/list"
#|}
#|@list.from_array([1, 2, 3])
),
),
content="More(1, tail=More(2, tail=More(3, tail=Empty)))",
)let vm = MoonBitVM(modules=[@eval/async.module()])inspect(
vm.test_all(
(
#|import { "moonbitlang/async/http" }
#|async test "https request" {
#| let (response, body) = @async.retry(FixedDelay(250), max_retry=3, () => {
#| @async.with_timeout(3000, () => @http.get("https://www.moonbitlang.com"))
#| })
#| assert_true(response.code is (200..<300), msg=response.code.to_string())
#| assert_true(body.text().to_lower().has_prefix("<!doctype html>"), msg=body.text())
#|}
),
),
content="TestResult(total=1, passed=1, failed=0)",
)| Feature | Status | Description |
|---|---|---|
| Core Language | ||
| Basic Types (Int, Bool, String, Double, Char) | â | Full support for primitive types |
| Expressions (arithmetic, logical, comparison) | â | Complete expression evaluation |
| Variables (let, let mut) | â | Immutable and mutable variables |
| Assignment | â | Variable reassignment and shadowing |
| Multiline strings | â | #|syntax for multiline string literals |
| String interpolation | â | {variable} syntax in string literals |
| Type constraints | â | (value : Type) syntax for explicit typing |
| Control Flow | ||
| If-else | â | Conditional expressions |
| For loops | â | C-style for loops with continue/break |
| While loops | â | While loop constructs with else clause |
| Loop control | â | Continue and break statements |
| Guard expressions | â | guard condition else { action } syntax |
| Is expressions | â | Pattern matching with 'is' operator |
| Defer expressions | â | defer statement for cleanup code |
| Return expressions | â | Early return from functions |
| Raise expressions | â | Exception throwing with raise |
| Try-catch expressions | â | Exception handling with try-catch |
| Loop expressions | â | loop pattern matching with break/continue |
| Functions | ||
| Function definitions | â | Named functions with parameters |
| Named parameters | â | Named and optional parameters |
| Lambda expressions | â | Anonymous functions (x => x * 2) |
| Closures | â | Proper closure environment capture |
| Recursive functions | â | Self-referencing function calls |
| Currying | â | Higher-order function composition |
| External functions | â | Integration with external calls |
| Embedded functions | â | Native function integration |
| Data Structures | ||
| Arrays | â | Array creation, indexing, assignment |
| Array methods | â | length, get, push, pop, contains, slice, concat, join |
| Array boolean methods | â | any, all operations |
| Array spread syntax | â | [..array1, ..array2] syntax |
| Array slice operations | â | arr[start:end], arr[start:], arr[:end] syntax |
| Array augmented assignment | â | arr[i] += value, arr[i] *= value syntax |
| Tuples | â | Tuple creation, access, destructuring |
| Structs | â | Custom data types with methods |
| Mutable struct fields | â | Field mutation support |
| Nested struct references | â | Reference semantics for nested structures |
| Record update syntax | â | { ..record, field: new_value } syntax |
| Map literals | â | { "key": value } syntax for map creation |
| Pattern Matching | ||
| Basic patterns | â | Constants, variables, wildcards |
| Tuple patterns | â | Destructuring tuples |
| Array patterns | â | Array destructuring |
| Record patterns | â | Struct field matching |
| Range patterns | â | Range expressions (_..<x, 'a'..='z') |
| Constructor patterns | â | Constant constructor matching |
| Or patterns | â | Multiple pattern alternatives |
| Nested patterns | â | Complex nested pattern matching |
| Enums and Generics | ||
| Basic enums | â | Simple enumeration types |
| Enums with data | â | Algebraic data types |
| Enum pattern matching | â | Pattern matching on enum variants |
| Generic types | â | Generic enums and functions |
| Generic functions | â | Polymorphic function definitions |
| Option Type | ||
| Option basics | â | Some/None construction |
| Option pattern matching | â | Pattern matching on Option |
| Option methods | â | unwrap, unwrap_or, is_empty, map, filter |
| Built-in Methods | ||
| Bool methods | â | compare, default |
| Int methods | â | Bitwise ops, comparisons, bit manipulation |
| String methods | â | length, get, unsafe_get, to_string |
| Double methods | â | compare, to_int64 |
| Char methods | â | compare, to_int |
| Advanced Features | ||
| Type system | â | Basic type checking and inference |
| Static method calls | â | Class::method() syntax |
| Pipe operator | â | |> operator for function chaining |
| Function aliases | â | using @pkg {name} alias support |
| Cross-package method calls | â | Method calls across different packages |
| Error handling | â | Result type error handling |
| Group expressions | â | Parenthesized expressions for precedence |
| For-in loops | â | Iterator-based loops |
| Iterator methods | â | iter, map, filter, reduce, for_each |
| Nested iteration | â | Complex nested loop structures |
| Iterator control flow | â | break/continue in iterator contexts |
| Package System | ||
| Module imports | â | Explicit import { "package/path" } declarations and @package.function syntax |
| Cross-package types | â | Using types from other packages |
| Built-in packages | â | Builtin package is always loaded; other core packages load through explicit imports |
| Package method calling | â | Method calls across package boundaries |
| Runtime modules | â | Optional injected modules such as @eval/async.module() |
| IO and FFI | ||
| Print functions | â | println and print support |
| Embedded functions | â | Native function integration via FFI |
| External function binding | â | Custom function registration |
| Sorting and Collections | ||
| List sorting | â | Built-in sort methods for collections |
| Array sorting | â | Sorting operations on arrays |
| Collection methods | â | Comprehensive collection manipulation |
| Comparison Operations | ||
| Equality operators | â | == and != operators |
| Relational operators | â | , <=, >= operators |
| Type-aware comparison | â | Proper type checking in comparisons |
| Constructor Patterns | ||
| Single argument matching | â | Constructor pattern with single args |
| Named field matching | â | Constructor patterns with named fields |
| Wildcard patterns | â | _ patterns in constructor matching |
| Functional Programming | ||
| Higher-order functions | â | Functions as first-class values |
| Function composition | â | Combining functions effectively |
| Closure environments | â | Proper variable capture in closures |
| Literal Overloading | ||
| Numeric literal overloading | â | Automatic conversion between numeric types |
| Character literal overloading | â | Char to Int conversion in pattern matching |
| String literal overloading | â | String to Bytes conversion |
| Array literal overloading | â | Array to various types (Bytes, String) conversion |
| Double literal overloading | â | Double to Float precision conversion |
| Map literal overloading | â | Map to Json object conversion |
| Complex overloading scenarios | â | Multi-step type conversions |
| Traits | đĄ | Interface definitions |
| Trait as expressions | đĄ | (value as Trait) syntax for trait casting |
| Packages | đĄ | Module system with @package.function syntax (no trait, trait derive, operator overloading) |
| Attribute | ||
| #alias | â | Function alias |
| #external | â | External function binding |
| #callsite | â | Call site information |
| #skip | â | Skipping compilation of a function |
| #cfg | â | Conditional compilation based on configuration |
| Not Yet Supported | ||
| Async/await | đĄ | Async tests and selected moonbitlang/async APIs through explicit runtime module injection |

pub(all) struct CompiledCode {
// private fields
}fn CompiledCode::run(self : CompiledCode, vm : MoonBitVM, args? : Array[&ToRuntime], log? : Bool) -> EvalResultpub(all) struct MoonBitVM {
interpreter : ClosureInterpreter
log : Bool
// private fields
}
#alias(new)
fn MoonBitVM::MoonBitVM(log? : Bool, modules? : Array[RuntimeModule]) -> MoonBitVMpub(all) struct TestResult {
total : Int
passed : Int
failed : Int
failures : Array[TestFailure]
} derive(ToJson)impl Show for TestResultfn add_embedded_fn(vm : MoonBitVM, name : String, func : (RuntimeFunctionContext) -> RuntimeValue raise ControlFlow) -> Unitfn add_embedded_method(vm : MoonBitVM, name : String, method_name : String, func : (RuntimeFunctionContext) -> RuntimeValue raise ControlFlow) -> Unitfn add_extern_fn(vm : MoonBitVM, name : String, func : (RuntimeFunctionContext) -> RuntimeValue raise ControlFlow) -> Unitfn run_compiled(vm : MoonBitVM, compiled : CompiledCode, args? : Array[&ToRuntime], log? : Bool) -> EvalResultMoonBit Eval Package
Dependencies