๐ REPL Demo
๐ Notebook Demo https://moonbit-notebook.oboard.fun/
MoonBit Eval is an interpreter for the MoonBit language.
Built on top of the @moonbitlang/parser library, it provides comprehensive and accurate MoonBit syntax support, capable of correctly parsing and executing complex MoonBit code structures including functions, structs, lambdas, loops, and more.
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")Use compile when the same code needs to run repeatedly. Parsing happens once,
and each run executes the compiled code against the VM you pass in.
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",
)Compiled parameters are bound in a temporary scope, so they do not leak into the VM global environment after execution.
eval accepts top-level expressions directly, with or without fn main.
Import declarations can appear before either form.
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)))",
)Core packages are loaded on demand. moonbitlang/core/builtin is always
available, but other core packages such as moonbitlang/core/list must be
imported explicitly before using their package aliases.
Optional runtime modules can be injected when constructing a VM. They register packages and embedded runtime functions without loading every package into the current eval scope.
let vm = MoonBitVM(modules=[@eval/async.module()])The async module makes the root @async package available. Subpackages are
lazy-loaded and must be imported explicitly:
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)",
)vm.test_all(code) runs top-level test and async test blocks and returns a
TestResult summary instead of swallowing assertion failures.
evalparses code through a compatibility wrapper aroundmoonbitlang/parser.- Top-level expressions are supported directly, so users do not need to wrap
snippets in
fn main. - Full top-level code with declarations and
fn mainremains supported. - Diagnostics from parser reports are preserved and returned in
Err(...)when parse fails.
- โ ๐ฅฎ Mooncakes Loader: Load Mooncakes packages at runtime
- โ Builtin FileSystem Library: Provides basic file system operations.
- โ Eval Function: Allows dynamic evaluation of MoonBit code strings.
| 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 |
We welcome contributions to the MoonBit Eval project! Whether it's bug fixes, feature additions, or documentation improvements, your contributions are valuable.
Join our community for discussions and support:
- QQ Group: 949886784
