Sign in

    moonbit-eval

    MoonBit Eval Package

    moonbit
    eval
    Download zip
    Author
    Version
    0.3.5
    License
    Apache-2.0
    Last updated
    last year
    Downloads
    170

    #MoonBit Eval

    #Introduction

    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.

    #Progress

    #Examples

    #Basic Operations

    test "basic" {
    let vm = MoonBitVM::new()
    inspect(vm.eval("1 + 1"), content="2")
    inspect(vm.eval("5 * 3"), content="15")
    inspect(vm.eval("10 / 2"), content="5")
    inspect(vm.eval("7 % 3"), content="1")
    inspect(vm.eval("5 == 5"), content="true")
    inspect(vm.eval("5 != 3"), content="true")
    inspect(vm.eval("3 < 5"), content="true")
    inspect(vm.eval("5 > 3"), content="true")
    inspect(vm.eval("\"hello\" + \"world\""), content="helloworld")
    }

    #Variables and Functions

    test "variables and functions" {
    let vm = MoonBitVM::new()
    inspect(vm.eval("let a = 1"), content="()")
    inspect(vm.eval("a"), content="1")

    inspect(vm.eval("fn add(a: Int, b: Int) -> Int { a + b }"), content="(a: Int, b: Int) -> Int")
    inspect(vm.eval("add(1, 2)"), content="3")
    }

    #Mutable Variables

    test "mutable variables" {
    let vm = MoonBitVM::new()
    inspect(vm.eval("let mut a = 1"), content="()")
    inspect(vm.eval("a = 12"), content="()")
    inspect(vm.eval("a"), content="12")
    }

    #Control Flow

    test "control flow" {
    let vm = MoonBitVM::new()
    inspect(vm.eval("if 1 > 0 { 3 } else { 4 }"), content="3")

    inspect(vm.eval("let mut sum = 0"), content="()")
    inspect(vm.eval("for i = 0; i < 5; i = i + 1 { sum += i }"), content="()")
    inspect(vm.eval("sum"), content="10")
    }

    #Lambda Functions

    test "lambda" {
    let vm = MoonBitVM::new()
    inspect(vm.eval("let f = x => x * 2"), content="()")
    inspect(vm.eval("f(3)"), content="6")

    inspect(vm.eval("let h = z => z * z"), content="()")
    inspect(vm.eval("h(4)"), content="16")
    }

    #Structs and Methods

    test "struct" {
    let vm = MoonBitVM::new()
    inspect(
    vm.eval(
    #|struct S {
    #| a: Int
    #| b: Int
    #|}
    #|fn S::sum(self: S) -> Int {
    #| self.a + self.b
    #|}
    top=true,
    ),
    content="()",
    )
    inspect(vm.eval("let s = { a: 23, b: 32 }"), content="()")
    inspect(vm.eval("s.sum()"), content="55")
    }

    #Arrays and Tuples

    test "array and tuple" {
    let vm = MoonBitVM::new()
    // Array operations
    inspect(vm.eval("let a = [1, 2, 3]"), content="()")
    inspect(vm.eval("a[0]"), content="1")
    inspect(vm.eval("a[1] = 4"), content="()")
    inspect(vm.eval("a"), content="[1, 4, 3]")

    // Tuple operations
    inspect(vm.eval("let t = (1, 2)"), content="()")
    inspect(vm.eval("t.0"), content="1")
    inspect(vm.eval("t.1"), content="2")
    inspect(vm.eval("let (a, b) = t"), content="()")
    }

    #Mutable Struct Fields

    test "mutable fields" {
    let vm = MoonBitVM::new()
    inspect(
    vm.eval(
    #|struct Point {
    #| mut x : Int
    #| mut y : Int
    #|}
    top=true,
    ),
    content="()",
    )
    inspect(vm.eval("let p = { x: 1, y: 2 }"), content="()")
    inspect(vm.eval("p.x = 3"), content="()")
    inspect(vm.eval("p.y = 4"), content="()")
    inspect(vm.eval("p.x"), content="3")
    }

    #Fibonacci Recursion

    test "fibonacci" {
    let vm = MoonBitVM::new()
    inspect(
    vm.eval(
    #|fn fib(n : Int) -> Int {
    #| if n <= 1 {
    #| 1
    #| } else {
    #| fib(n - 1) + fib(n - 2)
    #| }
    #|}
    ),
    content="(n: Int) -> Int",
    )
    inspect(vm.eval("fib(10)"), content="89")
    }

    #External Functions

    test "extern" {
    let vm = MoonBitVM::new()
    vm.interpreter.add_extern_fn("println", params => {
    if params is More(Constant(c=String(s), ..), ..) {
    println(s)
    }
    unit()
    })
    inspect(vm.eval("println(\"Hello from external function\")"), content="()")
    }

    #Embedded Functions

    test "embedded" {
    let vm = MoonBitVM::new()
    vm.interpreter.add_embedded_fn("%string_length", params =>
    if params is More(Constant(c=String(s), loc~), ..) {
    Constant(c=Int(s.length().to_string()), loc~)
    } else {
    unit()
    }
    )
    inspect(
    vm.eval("pub fn String::length(self : String) -> Int = \"%string_length\""),
    content="()",
    )
    inspect(vm.eval("\"hello\".length()"), content="5")
    }

    #Match Expressions

    test "match" {
    let vm = MoonBitVM::new()
    // 基本常量匹配
    inspect(vm.eval("let s = 10"), content="()")
    inspect(vm.eval("match s { 10 => 100 }"), content="100")

    // 变量模式匹配
    inspect(vm.eval("match 42 { x => x * 2 }"), content="84")

    // 通配符模式匹配
    inspect(vm.eval("match 123 { _ => 999 }"), content="999")

    // Or模式匹配
    inspect(vm.eval("match 5 { 1 | 5 | 10 => 100 }"), content="100")
    inspect(vm.eval("match 3 { 1 | 5 | 10 => 100; _ => 200 }"), content="200")

    // 测试简单变量绑定
    inspect(vm.eval("match 42 { x => x }"), content="42")

    // Tuple模式匹配 - 简化测试
    inspect(vm.eval("match (1, 2) { (a, b) => a }"), content="1")
    inspect(vm.eval("match (1, 2) { (a, b) => b }"), content="2")
    inspect(vm.eval("match (1, 2) { (a, b) => a + b }"), content="3")

    // Array模式匹配
    inspect(vm.eval("match [1, 2, 3] { [a, b, c] => a + b + c }"), content="6")
    inspect(vm.eval("match [5, 10] { [x, y] => x * y }"), content="50")

    // Record模式匹配
    inspect(vm.eval("match { x: 10, y: 20 } { { x, y } => x + y }"), content="30")
    inspect(
    vm.eval("match { name: \"Alice\", age: 25 } { { name, .. } => name }"),
    content="Alice",
    )
    inspect(
    vm.eval("match { name: \"Alice\", age: 25 } { { age, .. } => age }"),
    content="25",
    )
    // 嵌套模式匹配
    inspect(
    vm.eval("match (1, [2, 3]) { (a, [b, c]) => a + b + c }"),
    content="6",
    )

    // 多个case的匹配
    inspect(vm.eval("match 2 { 1 => 10; 2 => 20; _ => 30 }"), content="20")
    inspect(vm.eval("match 5 { 1 => 10; 2 => 20; _ => 30 }"), content="30")
    }

    #Features

    • ✅ Complete Expression Support: Arithmetic, logical, and comparison operations
    • ✅ Variable Management: Immutable and mutable variable declarations
    • ✅ Control Flow: If-else statements, for loops, while loops
    • ✅ Function Definitions: Named functions with parameters and return types
    • ✅ Lambda Expressions: Anonymous functions with closure support
    • ✅ Struct Definitions: Custom data types with methods and mutable fields
    • ✅ Match Expressions: Pattern matching with constant, variable, tuple, array, and record patterns
    • ✅ Range Patterns: Pattern matching with range expressions (e.g., 1..=10, 'a'..='z')
    • ✅ Constructor Patterns: Pattern matching with constant constructors
    • ✅ Array Operations: Array creation, indexing, and element assignment
    • ✅ Tuple Operations: Tuple creation, field access, and destructuring
    • ✅ External Functions: Integration with external function calls
    • ✅ Embedded Functions: Native function integration with custom implementations
    • ✅ Type System: Basic type checking and inference

    #Contributing

    We welcome contributions to the MoonBit Eval project! Whether it's bug fixes, feature additions, or documentation improvements, your contributions are valuable.

    #Community

    Join our community for discussions and support:
    • QQ Group: 949886784

    QQ群

    ClosureInterpreter

    type ClosureInterpreter
    支持引用系统的解释器

    ClosureInterpreter::add_embedded_fn

    fn ClosureInterpreter::add_embedded_fn(self : ClosureInterpreter, name : String, f : (Array[RuntimeArgument]) -> RuntimeValue) -> Unit

    ClosureInterpreter::add_embedded_method

    fn ClosureInterpreter::add_embedded_method(self : ClosureInterpreter, type_name : String, method_name : String, f : (Array[RuntimeArgument]) -> RuntimeValue) -> Unit

    ClosureInterpreter::add_extern_fn

    fn ClosureInterpreter::add_extern_fn(self : ClosureInterpreter, name : String, f : (Array[RuntimeArgument]) -> RuntimeValue) -> Unit

    ClosureInterpreter::bind_function_parameters

    支持所有参数类型:位置参数、标签参数、可选参数、问号可选参数、丢弃参数

    ClosureInterpreter::bind_function_parameters_runtime

    ClosureInterpreter::constants_equal

    检查两个常量是否相等

    ClosureInterpreter::constants_equal_expr

    检查两个表达式是否相等(用于构造函数匹配)

    ClosureInterpreter::define_function

    fn ClosureInterpreter::define_function(self : ClosureInterpreter, name : String, func :
    Func
    ) -> Unit
    将函数存储到用户函数映射中

    ClosureInterpreter::define_struct_method

    fn ClosureInterpreter::define_struct_method(self : ClosureInterpreter, type_name : String, method_name : String, func :
    Func
    ) -> Unit

    ClosureInterpreter::execute_function_call

    处理用户定义函数的调用,包括作用域管理和参数绑定

    ClosureInterpreter::execute_function_call_runtime

    ClosureInterpreter::execute_match

    执行match表达式的模式匹配

    ClosureInterpreter::execute_match_runtime

    执行match表达式的模式匹配(返回RuntimeValue)

    ClosureInterpreter::find_user_function

    fn ClosureInterpreter::find_user_function(self : ClosureInterpreter, name : String) ->
    Func
    ?
    查找用户定义的函数

    ClosureInterpreter::new

    ClosureInterpreter::pattern_matches

    检查值是否匹配模式

    ClosureInterpreter::pattern_to_value

    将模式转换为值(用于范围匹配)

    ClosureInterpreter::pop_scope

    fn ClosureInterpreter::pop_scope(self : ClosureInterpreter) -> Unit
    销毁当前作用域

    ClosureInterpreter::push_scope

    fn ClosureInterpreter::push_scope(self : ClosureInterpreter) -> Unit
    创建新的作用域

    ClosureInterpreter::set_immutable_variable

    fn ClosureInterpreter::set_immutable_variable(self : ClosureInterpreter, name : String, value : RuntimeValue) -> Unit
    设置不可变变量

    ClosureInterpreter::set_mutable_variable

    fn ClosureInterpreter::set_mutable_variable(self : ClosureInterpreter, name : String, value : RuntimeValue) -> Unit
    设置可变变量

    ClosureInterpreter::value_in_range

    检查值是否在范围内

    EvalResult

    pub struct EvalResult {
    value : RuntimeValue
    store : RuntimeStore
    }

    impl Show for EvalResult

    MoonBitVM

    type MoonBitVM

    MoonBitVM::create

    fn MoonBitVM::create(log? : Bool) -> MoonBitVM

    MoonBitVM::eval

    fn MoonBitVM::eval(self : MoonBitVM, code : String, log? : Bool, top? : Bool) -> EvalResult raise Failure

    MoonBitVM::new

    fn MoonBitVM::new(log? : Bool) -> MoonBitVM

    RefId

    pub type RefId Int
    引用ID类型 - 用于标识可变对象
    impl Eq for RefId
    impl Hash for RefId
    impl Show for RefId

    RefId::inner

    fn RefId::inner(self : RefId) -> Int
    Convert newtype to its underlying type, automatically derived.

    RuntimeArgument

    pub struct RuntimeArgument {
    value : RuntimeValue
    kind :
    ArgumentKind

    }

    RuntimeStore

    pub struct RuntimeStore {
    structs : Map[RefId, Map[String, RuntimeValue]]
    next_id : RefId
    }
    运行时存储 - 统一管理所有可变对象

    RuntimeStore::alloc_struct

    fn RuntimeStore::alloc_struct(self : RuntimeStore, fields : Map[String, RuntimeValue]) -> RefId
    分配新的结构引用

    RuntimeStore::get_struct

    fn RuntimeStore::get_struct(self : RuntimeStore, id : RefId) -> Map[String, RuntimeValue]?
    获取结构数据

    RuntimeStore::new

    RuntimeStore::update_struct_field

    fn RuntimeStore::update_struct_field(self : RuntimeStore, id : RefId, field : String, value : RuntimeValue) -> Bool
    更新结构字段

    RuntimeValue

    pub enum RuntimeValue {
    Unit
    Bool(Bool)
    Int(Int)
    Double(Double)
    Char(Char)
    String(String)
    Tuple(Array[RuntimeValue])
    Array(Array[RuntimeValue])
    StructRef(RefId)
    Function(
    Func
    )
    }
    运行时值 - 解释器实际操作的数据类型

    RuntimeValue::from_expr

    将@syntax.Expr转换为RuntimeValue

    RuntimeValue::from_expr_with_store

    fn RuntimeValue::from_expr_with_store(expr :
    Expr
    , store : RuntimeStore) -> RuntimeValue
    将@syntax.Expr转换为RuntimeValue(通过store处理记录)

    RuntimeValue::is_mutable

    fn RuntimeValue::is_mutable(self : RuntimeValue) -> Bool
    检查值是否为可变类型

    RuntimeValue::is_reference

    fn RuntimeValue::is_reference(self : RuntimeValue) -> Bool
    检查值是否为引用类型

    RuntimeValue::to_expr

    将RuntimeValue转换为表达式(用于输出)

    RuntimeValue::to_expr_with_store

    将RuntimeValue转换为表达式(通过store解析引用)

    RuntimeValue::to_reference_expr

    将RuntimeValue转换为引用表达式(保持引用语义)

    RuntimeValue::to_string_with_store

    fn RuntimeValue::to_string_with_store(self : RuntimeValue, store : RuntimeStore) -> String
    将RuntimeValue转换为字符串表示(通过store解析引用)

    compare

    fn[T : Compare + Eq] compare(left : T, right : T, op : String) ->
    Constant

    eval_double_op

    fn eval_double_op(left : Double, right : Double, op : String) ->
    Constant

    eval_float_op

    fn eval_float_op(left : Double, right : Double, op : String) ->
    Constant

    eval_int64_op

    fn eval_int64_op(left : Int64, right : Int64, op : String) ->
    Constant

    eval_int_op

    fn eval_int_op(left : Int, right : Int, op : String) ->
    Constant

    eval_uint64_op

    fn eval_uint64_op(left : UInt64, right : UInt64, op : String) ->
    Constant

    eval_uint_op

    fn eval_uint_op(left : UInt, right : UInt, op : String) ->
    Constant

    expr_to_string

    fn expr_to_string(expr :
    Expr
    ) -> String

    find_variable

    fn find_variable(immutable_values : Array[Map[String, RuntimeValue]], mutable_values : Array[Map[String, RuntimeValue]], name : String) -> RuntimeValue
    优先查找不可变变量(性能优化),然后查找可变变量

    is_comparison_op

    fn is_comparison_op(op : String) -> Bool

    runtime_value_infix

    fn runtime_value_infix(op : String, lhs : RuntimeValue, rhs : RuntimeValue) -> RuntimeValue
    RuntimeValue 之间的中缀运算 - 消除对 constant_infix 的依赖

    type_to_string

    fn type_to_string(ty :
    Type
    ) -> String

    update_mutable_variable

    fn update_mutable_variable(mutable_values : Array[Map[String, RuntimeValue]], name : String, new_value : RuntimeValue) -> Bool
    在可变变量数组中查找并更新指定变量