A Scheme interpreter implemented in Moonbit for teaching purposes
Dependencies
///|
test {
let env = Environment::base()
env.define_vars(number_primitive)
let code =
#|(define (fact x)
#| (if (= x 0)
#| 1 ; base case
#| (* x (fact (- x 1))))) ; rec case
#|(fact 5)
let sexp : Array[Value] = parse(code)
let program : Array[CoreForm] = sexp.map(Value::to_core_form)
let inst : Array[Inst] = program.map(compile)
// make VM, load "(define (fact x) ...)" and env
let vm = VM::new(inst=inst[0], env~)
// run, add "fact" to env
vm.run_to_halt()
inspect(
vm.env.lookup(@symbol.Symbol::of("fact")),
content="#<procedure fact>",
)
// load and run "(fact 5)"
vm.next = inst[1]
vm.run_to_halt()
inspect(vm.acc, content="120")
}///|
test {
let env = Environment::base()
env.define_vars(number_primitive)
let code =
#|(define (fact x)
#| (if (= x 0)
#| 1 ; base case
#| (* x (fact (- x 1))))) ; rec case
#|(fact 5)
let sexp : Array[Value] = parse(code)
let program : Array[CoreForm] = sexp.map(Value::to_core_form)
let inst : Array[Inst] = program.map(compile)
// make VM, load "(define (fact x) ...)" and env
let vm = VM::new(inst=inst[0], env~)
// run, add "fact" to env
vm.run_to_halt()
inspect(
vm.env.lookup(@symbol.Symbol::of("fact")),
content="#<procedure fact>",
)
// load and run "(fact 5)"
vm.next = inst[1]
vm.run_to_halt()
inspect(vm.acc, content="120")
}pub suberror ParseException {
UnexpectedToken(Token)
MoreThanOneAfterDot(Token)
UnexpectedEndOfInput
ReadException(ReadException)
} derive(Debug)pub(all) struct Environment {
binds : HashMap[Symbol, Value]
next : Environment?
closure : Closure?
}impl Show for Environmentfn Environment::define_vars(self : Environment, name_value : ReadOnlyArray[(Symbol, Value)]) -> Unitfn Environment::extend_(self : Environment, names : FixedArray[Symbol], values : FixedArray[Value], closure : Closure) -> Environmentfn Environment::set_var(self : Environment, name : Symbol, new_value : Value) -> Unit raise SchemeExceptionpub(all) enum Primitive {
Normal(name~ : Symbol, (FixedArray[Value]) -> Value raise SchemeException)
CallCC
Apply
}pub(all) struct VM {
acc : Value
next : Inst
env : Environment
rib : FixedArray[Value]
stack : Frame?
}A Scheme interpreter implemented in Moonbit for teaching purposes
Dependencies