feat: bumpalo

This commit is contained in:
2025-05-23 12:09:53 +08:00
parent 53cbb37b00
commit a47a08b051
12 changed files with 130 additions and 127 deletions

10
Cargo.lock generated
View File

@@ -45,6 +45,15 @@ version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
[[package]]
name = "bumpalo"
version = "3.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf"
dependencies = [
"allocator-api2",
]
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.21" version = "1.2.21"
@@ -307,6 +316,7 @@ dependencies = [
name = "nixjit" name = "nixjit"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"bumpalo",
"derive_more", "derive_more",
"ecow", "ecow",
"hashbrown 0.15.3", "hashbrown 0.15.3",

View File

@@ -25,11 +25,11 @@ rnix = "0.12"
thiserror = "2.0" thiserror = "2.0"
itertools = "0.14" itertools = "0.14"
rpds = "1.1" rpds = "1.1"
derive_more = { version = "2.0", features = [ "full" ] } derive_more = { version = "2.0", features = ["full"] }
ecow = "0.2" ecow = "0.2"
regex = "1.11" regex = "1.11"
hashbrown = "0.15" hashbrown = "0.15"
inkwell = { version = "0.6.0", features = ["llvm18-1"] } inkwell = { version = "0.6.0", features = ["llvm18-1"] }
bumpalo = { version = "3.17", features = ["allocator-api2"] }
rustyline = { version = "15.0", optional = true } rustyline = { version = "15.0", optional = true }

View File

@@ -1,15 +1,12 @@
use hashbrown::HashMap;
use std::rc::Rc; use std::rc::Rc;
use hashbrown::HashMap;
use crate::ty::common::Const; use crate::ty::common::Const;
use crate::ty::internal::{AttrSet, PrimOp, Value}; use crate::ty::internal::{AttrSet, PrimOp, Value};
use crate::vm::{VM, VmEnv}; use crate::vm::{VM, VmEnv};
pub fn env<'jit, 'vm>(vm: &'vm VM<'jit>) -> VmEnv<'jit, 'vm> { pub fn env<'jit, 'vm>(vm: &'vm VM<'jit>) -> VmEnv<'jit, 'vm> {
let mut env_map = HashMap::new();
env_map.insert(vm.new_sym("true"), Value::Const(Const::Bool(true)));
env_map.insert(vm.new_sym("false"), Value::Const(Const::Bool(false)));
let primops = [ let primops = [
PrimOp::new("add", 2, |_, args| { PrimOp::new("add", 2, |_, args| {
let [mut first, second]: [Value; 2] = args.try_into().unwrap(); let [mut first, second]: [Value; 2] = args.try_into().unwrap();
@@ -49,6 +46,11 @@ pub fn env<'jit, 'vm>(vm: &'vm VM<'jit>) -> VmEnv<'jit, 'vm> {
}), }),
]; ];
let mut env_map = HashMap::new_in(&vm.bump);
env_map.insert(vm.new_sym("true"), Value::Const(Const::Bool(true)));
env_map.insert(vm.new_sym("false"), Value::Const(Const::Bool(false)));
let mut map = HashMap::new(); let mut map = HashMap::new();
for primop in primops { for primop in primops {
let primop = Rc::new(primop); let primop = Rc::new(primop);
@@ -66,5 +68,5 @@ pub fn env<'jit, 'vm>(vm: &'vm VM<'jit>) -> VmEnv<'jit, 'vm> {
let builtins = Value::AttrSet(attrs); let builtins = Value::AttrSet(attrs);
env_map.insert(sym, builtins); env_map.insert(sym, builtins);
VmEnv::new(env_map.into()) VmEnv::new(vm.bump.alloc(env_map), &vm.bump)
} }

View File

@@ -1,5 +1,3 @@
use std::rc::Rc;
use inkwell::AddressSpace; use inkwell::AddressSpace;
use inkwell::context::Context; use inkwell::context::Context;
use inkwell::execution_engine::ExecutionEngine; use inkwell::execution_engine::ExecutionEngine;
@@ -209,9 +207,8 @@ extern "C" fn helper_debug(value: JITValue) {
extern "C" fn helper_capture_env(thunk: JITValue, env: *const VmEnv) { extern "C" fn helper_capture_env(thunk: JITValue, env: *const VmEnv) {
let thunk = unsafe { (thunk.data.ptr as *const Thunk).as_ref().unwrap() }; let thunk = unsafe { (thunk.data.ptr as *const Thunk).as_ref().unwrap() };
let env = unsafe { Rc::from_raw(env) }; let env = unsafe { env.as_ref() }.unwrap();
thunk.capture(env.clone()); thunk.capture(env);
std::mem::forget(env);
} }
extern "C" fn helper_neg(rhs: JITValue, _env: *const VmEnv) -> JITValue { extern "C" fn helper_neg(rhs: JITValue, _env: *const VmEnv) -> JITValue {

View File

@@ -165,10 +165,10 @@ impl<'vm, 'ctx: 'vm> JITContext<'ctx> {
.unwrap() .unwrap()
} }
pub fn compile_function( pub fn compile_function<'bump>(
&self, &self,
func: &Func, func: &Func,
vm: &'vm VM<'_>, vm: &'vm VM<'ctx>,
) -> Result<JitFunction<'ctx, JITFunc<'ctx, 'vm>>> { ) -> Result<JitFunction<'ctx, JITFunc<'ctx, 'vm>>> {
let mut stack = Stack::<_, STACK_SIZE>::new(); let mut stack = Stack::<_, STACK_SIZE>::new();
let mut iter = func.opcodes.iter().copied(); let mut iter = func.opcodes.iter().copied();

View File

@@ -2,6 +2,7 @@
extern crate test; extern crate test;
use bumpalo::Bump;
use hashbrown::{HashMap, HashSet}; use hashbrown::{HashMap, HashSet};
use inkwell::context::Context; use inkwell::context::Context;
@@ -30,11 +31,12 @@ fn test_expr(expr: &str, expected: Value) {
prog.symbols.into(), prog.symbols.into(),
prog.symmap.into(), prog.symmap.into(),
prog.consts, prog.consts,
Bump::new(),
jit, jit,
); );
let env = env(&vm); let env = env(&vm);
let value = vm let value = vm
.eval(prog.top_level.into_iter(), env.into()) .eval(prog.top_level.into_iter(), vm.bump.alloc(env))
.unwrap() .unwrap()
.to_public(&vm, &mut HashSet::new()); .to_public(&vm, &mut HashSet::new());
assert_eq!(value, expected); assert_eq!(value, expected);

View File

@@ -1,5 +1,6 @@
#![cfg_attr(test, feature(test))] #![cfg_attr(test, feature(test))]
#![allow(dead_code)] #![allow(dead_code)]
#![feature(iter_collect_into)]
mod builtins; mod builtins;
mod bytecode; mod bytecode;

View File

@@ -52,10 +52,10 @@ impl<'jit: 'vm, 'vm> AttrSet<'jit, 'vm> {
self.data.get(&sym).is_some() self.data.get(&sym).is_some()
} }
pub fn capture(&mut self, env: &Rc<VmEnv<'jit, 'vm>>) { pub fn capture(&mut self, env: &'vm VmEnv<'jit, 'vm>) {
self.data.iter().for_each(|(_, v)| { self.data.iter().for_each(|(_, v)| {
if let Value::Thunk(ref thunk) = v.clone() { if let Value::Thunk(ref thunk) = v.clone() {
thunk.capture(Rc::clone(env)); thunk.capture(env);
} }
}) })
} }

View File

@@ -1,5 +1,4 @@
use std::cell::{Cell, OnceCell}; use std::cell::{Cell, OnceCell};
use std::rc::Rc;
use derive_more::Constructor; use derive_more::Constructor;
use hashbrown::HashMap; use hashbrown::HashMap;
@@ -46,7 +45,7 @@ impl From<ir::Param> for Param {
#[derive(Debug, Clone, Constructor)] #[derive(Debug, Clone, Constructor)]
pub struct Func<'jit: 'vm, 'vm> { pub struct Func<'jit: 'vm, 'vm> {
pub func: &'vm BFunc, pub func: &'vm BFunc,
pub env: Rc<VmEnv<'jit, 'vm>>, pub env: &'vm VmEnv<'jit, 'vm>,
pub compiled: OnceCell<JitFunction<'jit, JITFunc<'jit, 'vm>>>, pub compiled: OnceCell<JitFunction<'jit, JITFunc<'jit, 'vm>>>,
pub count: Cell<usize>, pub count: Cell<usize>,
} }
@@ -55,16 +54,16 @@ impl<'vm, 'jit: 'vm> Func<'jit, 'vm> {
pub fn call(&self, vm: &'vm VM<'jit>, arg: Value<'jit, 'vm>) -> Result<Value<'jit, 'vm>> { pub fn call(&self, vm: &'vm VM<'jit>, arg: Value<'jit, 'vm>) -> Result<Value<'jit, 'vm>> {
use Param::*; use Param::*;
let mut env = self.env.clone(); let mut env = self.env;
match self.func.param.clone() { env = match self.func.param.clone() {
Ident(ident) => env.enter_arg(ident, arg), Ident(ident) => env.enter_arg(ident, arg, &vm.bump),
Formals { Formals {
formals, formals,
ellipsis, ellipsis,
alias, alias,
} => { } => {
let arg = arg.unwrap_attr_set(); let arg = arg.unwrap_attr_set();
let mut new = HashMap::with_capacity(formals.len() + alias.iter().len()); let mut new = HashMap::with_capacity_in(formals.len() + alias.iter().len(), &vm.bump);
if !ellipsis if !ellipsis
&& arg && arg
.as_inner() .as_inner()
@@ -87,7 +86,7 @@ impl<'vm, 'jit: 'vm> Func<'jit, 'vm> {
if let Some(alias) = alias { if let Some(alias) = alias {
new.insert(alias, Value::AttrSet(arg)); new.insert(alias, Value::AttrSet(arg));
} }
env.enter_let(new.into()) env.enter_let(vm.bump.alloc(new), &vm.bump)
} }
}; };
@@ -95,14 +94,11 @@ impl<'vm, 'jit: 'vm> Func<'jit, 'vm> {
self.count.replace(count + 1); self.count.replace(count + 1);
if count >= 1 { if count >= 1 {
let compiled = self.compiled.get_or_init(|| vm.compile_func(self.func)); let compiled = self.compiled.get_or_init(|| vm.compile_func(self.func));
let env = Rc::into_raw(env); let env = env as *const _;
let ret = unsafe { compiled.call(vm as *const VM, env) }; let ret = unsafe { compiled.call(vm as *const VM, env) };
unsafe {
Rc::decrement_strong_count(env);
}
return Ok(ret.into()); return Ok(ret.into());
} }
vm.eval(self.func.opcodes.iter().copied(), env) vm.eval(self.func.opcodes.iter().copied(), vm.bump.alloc(env))
} }
} }

View File

@@ -467,17 +467,11 @@ pub struct Thunk<'jit, 'vm> {
#[derive(Debug, IsVariant, Unwrap, Clone)] #[derive(Debug, IsVariant, Unwrap, Clone)]
pub enum _Thunk<'jit, 'vm> { pub enum _Thunk<'jit, 'vm> {
Code(&'vm OpCodes, OnceCell<EnvRef<'jit, 'vm>>), Code(&'vm OpCodes, OnceCell<&'vm VmEnv<'jit, 'vm>>),
SuspendedFrom(*const Thunk<'jit, 'vm>), SuspendedFrom(*const Thunk<'jit, 'vm>),
Value(Value<'jit, 'vm>), Value(Value<'jit, 'vm>),
} }
#[derive(Debug, IsVariant, Unwrap, Clone)]
pub enum EnvRef<'jit, 'vm> {
Strong(Rc<VmEnv<'jit, 'vm>>),
Weak(Weak<VmEnv<'jit, 'vm>>),
}
impl<'jit, 'vm> Thunk<'jit, 'vm> { impl<'jit, 'vm> Thunk<'jit, 'vm> {
pub fn new(opcodes: &'vm OpCodes) -> Self { pub fn new(opcodes: &'vm OpCodes) -> Self {
Thunk { Thunk {
@@ -485,15 +479,9 @@ impl<'jit, 'vm> Thunk<'jit, 'vm> {
} }
} }
pub fn capture(&self, env: Rc<VmEnv<'jit, 'vm>>) { pub fn capture(&self, env: &'vm VmEnv<'jit, 'vm>) {
if let _Thunk::Code(_, envcell) = &*self.thunk.borrow() { if let _Thunk::Code(_, envcell) = &*self.thunk.borrow() {
envcell.get_or_init(|| EnvRef::Strong(env)); envcell.get_or_init(|| env);
}
}
pub fn capture_weak(&self, env: Weak<VmEnv<'jit, 'vm>>) {
if let _Thunk::Code(_, envcell) = &*self.thunk.borrow() {
envcell.get_or_init(|| EnvRef::Weak(env));
} }
} }
@@ -519,10 +507,7 @@ impl<'jit, 'vm> Thunk<'jit, 'vm> {
_Thunk::SuspendedFrom(self as *const Thunk), _Thunk::SuspendedFrom(self as *const Thunk),
) )
.unwrap_code(); .unwrap_code();
let env = match env.get().unwrap() { let env = env.get().unwrap();
EnvRef::Strong(env) => env.clone(),
EnvRef::Weak(env) => env.upgrade().unwrap(),
};
let value = vm.eval(opcodes.iter().copied(), env)?; let value = vm.eval(opcodes.iter().copied(), env)?;
let _ = std::mem::replace(&mut *self.thunk.borrow_mut(), _Thunk::Value(value)); let _ = std::mem::replace(&mut *self.thunk.borrow_mut(), _Thunk::Value(value));
Ok(match unsafe { &*(&*self.thunk.borrow() as *const _) } { Ok(match unsafe { &*(&*self.thunk.borrow() as *const _) } {

View File

@@ -1,53 +1,58 @@
use std::fmt::Debug; use std::fmt::Debug;
use std::{hash::Hash, rc::Rc}; use std::hash::Hash;
use hashbrown::HashMap; use hashbrown::{DefaultHashBuilder, HashMap};
use bumpalo::Bump;
use crate::ty::internal::Value; use crate::ty::internal::Value;
type Map<'bump, K, V> = HashMap<K, V, DefaultHashBuilder, &'bump Bump>;
#[derive(Clone)] #[derive(Clone)]
pub struct Env<K: Hash + Eq + Clone, V: Clone> { pub struct Env<'bump, K: Hash + Eq + Clone, V: Clone> {
let_: Rc<LetEnv<K, V>>, let_: &'bump LetEnv<'bump, K, V>,
with: Rc<With<K, V>>, with: &'bump With<'bump, K, V>,
last: Option<&'bump Env<'bump, K, V>>,
} }
#[derive(Clone)] #[derive(Clone)]
pub struct LetEnv<K: Hash + Eq + Clone, V: Clone> { pub struct LetEnv<'bump, K: Hash + Eq + Clone, V: Clone> {
map: LetNode<K, V>, map: LetNode<'bump, K, V>,
last: Option<Rc<LetEnv<K, V>>>, last: Option<&'bump LetEnv<'bump, K, V>>,
} }
impl<K: Debug + Hash + Eq + Clone, V: Debug + Clone> Debug for Env<K, V> { impl<K: Debug + Hash + Eq + Clone, V: Debug + Clone> Debug for Env<'_, K, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Env") f.debug_struct("Env")
.field("let_", &self.let_) .field("let_", &self.let_)
.field("with", &self.with) .field("with", &self.with)
.field("last", &self.last)
.finish() .finish()
} }
} }
impl<K: Debug + Hash + Eq + Clone, V: Debug + Clone> Debug for LetEnv<K, V> { impl<K: Debug + Hash + Eq + Clone, V: Debug + Clone> Debug for LetEnv<'_, K, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Env") f.debug_struct("LetEnv")
.field("map", &self.map) .field("map", &self.map)
.field("last", &self.last) .field("last", &self.last)
.finish() .finish()
} }
} }
pub type VmEnv<'jit, 'vm> = Env<usize, Value<'jit, 'vm>>; pub type VmEnv<'jit, 'vm> = Env<'vm, usize, Value<'jit, 'vm>>;
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub struct With<K: Hash + Eq, V> { pub struct With<'bump, K: Hash + Eq, V> {
map: Option<Rc<HashMap<K, V>>>, map: Option<&'bump Map<'bump, K, V>>,
last: Option<Rc<With<K, V>>>, last: Option<&'bump With<'bump, K, V>>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
enum LetNode<K: Hash + Eq, V> { enum LetNode<'bump, K: Hash + Eq + Clone, V: Clone> {
Let(Rc<HashMap<K, V>>), Let(&'bump Map<'bump, K, V>),
SingleArg(K, V), SingleArg(K, V),
MultiArg(Rc<HashMap<K, V>>), MultiArg(&'bump Map<'bump, K, V>),
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@@ -57,15 +62,15 @@ pub enum Type {
With, With,
} }
impl<K: Hash + Eq + Clone, V: Clone> Env<K, V> { impl<'bump, K: Hash + Eq + Clone, V: Clone> Env<'bump, K, V> {
pub fn new(map: Rc<HashMap<K, V>>) -> Self { pub fn new(map: &'bump Map<'bump, K, V>, bump: &'bump Bump) -> Self {
Self { Self {
let_: LetEnv::new(map).into(), let_: &*bump.alloc(LetEnv::new(map)),
with: With { with: &*bump.alloc(With {
map: None, map: None,
last: None, last: None,
} }),
.into(), last: None
} }
} }
@@ -76,29 +81,37 @@ impl<K: Hash + Eq + Clone, V: Clone> Env<K, V> {
self.with.lookup(symbol) self.with.lookup(symbol)
} }
pub fn enter_arg(self: &mut Rc<Self>, ident: K, val: V) { pub fn enter_arg(&'bump self, ident: K, val: V, bump: &'bump Bump) -> &'bump Self {
Rc::make_mut(self).let_.enter_arg(ident, val); &*bump.alloc(Env {
let_: self.let_.enter_arg(ident, val, bump),
with: self.with,
last: Some(self)
})
} }
pub fn enter_let(self: &mut Rc<Self>, map: Rc<HashMap<K, V>>) { pub fn enter_let(&'bump self, map: &'bump Map<'bump, K, V>, bump: &'bump Bump) -> &'bump Self {
Rc::make_mut(self).let_.enter_let(map); &*bump.alloc(Env {
let_: self.let_.enter_let(map, bump),
with: self.with,
last: Some(self)
})
} }
pub fn enter_with(self: &mut Rc<Self>, map: Rc<HashMap<K, V>>) { pub fn enter_with(&'bump self, map: &'bump Map<'bump, K, V>, bump: &'bump Bump) -> &'bump Self {
Rc::make_mut(self).with.enter(map); &*bump.alloc(Env {
let_: self.let_,
with: self.with.enter(map, bump),
last: Some(self)
})
} }
pub fn leave_let(self: &mut Rc<Self>) { pub fn leave(&self) -> &Self {
Rc::make_mut(self).let_.leave(); self.last.unwrap()
}
pub fn leave_with(self: &mut Rc<Self>) {
Rc::make_mut(self).with.leave();
} }
} }
impl<K: Hash + Eq + Clone, V: Clone> LetEnv<K, V> { impl<'bump, K: Hash + Eq + Clone, V: Clone> LetEnv<'bump, K, V> {
pub fn new(map: Rc<HashMap<K, V>>) -> Self { pub fn new(map: &'bump HashMap<K, V, DefaultHashBuilder, &Bump>) -> Self {
Self { Self {
map: LetNode::Let(map), map: LetNode::Let(map),
last: None, last: None,
@@ -122,45 +135,33 @@ impl<K: Hash + Eq + Clone, V: Clone> LetEnv<K, V> {
self.last.as_ref().and_then(|env| env.lookup(symbol)) self.last.as_ref().and_then(|env| env.lookup(symbol))
} }
pub fn enter_arg(self: &mut Rc<Self>, ident: K, val: V) { pub fn enter_arg(&'bump self, ident: K, val: V, bump: &'bump Bump) -> &'bump Self {
let cloned = self.clone(); &*bump.alloc(Self {
let mutref = Rc::make_mut(self); map: LetNode::SingleArg(ident, val),
mutref.last = Some(cloned); last: Some(self)
mutref.map = LetNode::SingleArg(ident, val); })
} }
pub fn enter_let(self: &mut Rc<Self>, map: Rc<HashMap<K, V>>) { pub fn enter_let(&'bump self, map: &'bump Map<'bump, K, V>, bump: &'bump Bump) -> &'bump Self {
let cloned = self.clone(); &*bump.alloc(Self {
let mutref = Rc::make_mut(self); map: LetNode::Let(map),
mutref.last = Some(cloned); last: Some(self)
mutref.map = LetNode::Let(map); })
}
pub fn leave(self: &mut Rc<Self>) {
let refmut = Rc::make_mut(self);
let last = refmut.last.take().unwrap();
*self = last;
} }
} }
impl<K: Hash + Eq + Clone, V: Clone> With<K, V> { impl<'bump, K: Hash + Eq + Clone, V: Clone> With<'bump, K, V> {
pub fn lookup(&self, symbol: &K) -> Option<&V> { pub fn lookup(&'bump self, symbol: &K) -> Option<&'bump V> {
if let Some(val) = self.map.as_ref()?.get(symbol) { if let Some(val) = self.map.as_ref()?.get(symbol) {
return Some(val); return Some(val);
} }
self.last.as_ref().and_then(|env| env.lookup(symbol)) self.last.as_ref().and_then(|env| env.lookup(symbol))
} }
pub fn enter(self: &mut Rc<Self>, map: Rc<HashMap<K, V>>) { pub fn enter(&'bump self, map: &'bump Map<'bump, K, V>, bump: &'bump Bump) -> &'bump Self {
let cloned = self.clone(); &*bump.alloc(Self {
let mutref = Rc::make_mut(self); map: Some(map),
mutref.last = Some(cloned); last: Some(self)
mutref.map = Some(map); })
}
pub fn leave(self: &mut Rc<Self>) {
let refmut = Rc::make_mut(self);
let last = refmut.last.take().unwrap();
*self = last;
} }
} }

View File

@@ -1,7 +1,7 @@
use bumpalo::Bump;
use hashbrown::{HashMap, HashSet}; use hashbrown::{HashMap, HashSet};
use inkwell::execution_engine::JitFunction; use inkwell::execution_engine::JitFunction;
use std::cell::{Cell, OnceCell, RefCell}; use std::cell::{Cell, OnceCell, RefCell};
use std::rc::Rc;
use crate::builtins::env; use crate::builtins::env;
use crate::bytecode::{BinOp, Func as F, OpCode, OpCodes, Program, UnOp}; use crate::bytecode::{BinOp, Func as F, OpCode, OpCodes, Program, UnOp};
@@ -30,12 +30,13 @@ pub fn run(prog: Program, jit: JITContext<'_>) -> Result<p::Value> {
symbols: RefCell::new(prog.symbols), symbols: RefCell::new(prog.symbols),
symmap: RefCell::new(prog.symmap), symmap: RefCell::new(prog.symmap),
consts: prog.consts, consts: prog.consts,
bump: Bump::new(),
jit, jit,
}; };
let env = env(&vm); let env = env(&vm);
let mut seen = HashSet::new(); let mut seen = HashSet::new();
let value = vm let value = vm
.eval(prog.top_level.into_iter(), env.into())? .eval(prog.top_level.into_iter(), vm.bump.alloc(env))?
.to_public(&vm, &mut seen); .to_public(&vm, &mut seen);
Ok(value) Ok(value)
} }
@@ -47,6 +48,7 @@ pub struct VM<'jit> {
symbols: RefCell<Vec<EcoString>>, symbols: RefCell<Vec<EcoString>>,
symmap: RefCell<HashMap<EcoString, usize>>, symmap: RefCell<HashMap<EcoString, usize>>,
consts: Box<[Const]>, consts: Box<[Const]>,
pub bump: Bump,
jit: JITContext<'jit>, jit: JITContext<'jit>,
} }
@@ -83,7 +85,7 @@ impl<'vm, 'jit: 'vm> VM<'jit> {
pub fn eval( pub fn eval(
&'vm self, &'vm self,
opcodes: impl Iterator<Item = OpCode>, opcodes: impl Iterator<Item = OpCode>,
mut env: Rc<VmEnv<'jit, 'vm>>, mut env: &'vm VmEnv<'jit, 'vm>,
) -> Result<Value<'jit, 'vm>> { ) -> Result<Value<'jit, 'vm>> {
let mut stack = Stack::<_, STACK_SIZE>::new(); let mut stack = Stack::<_, STACK_SIZE>::new();
let mut iter = opcodes.into_iter(); let mut iter = opcodes.into_iter();
@@ -104,7 +106,7 @@ impl<'vm, 'jit: 'vm> VM<'jit> {
&'vm self, &'vm self,
opcode: OpCode, opcode: OpCode,
stack: &'s mut Stack<Value<'jit, 'vm>, CAP>, stack: &'s mut Stack<Value<'jit, 'vm>, CAP>,
env: &mut Rc<VmEnv<'jit, 'vm>>, env: &mut &'vm VmEnv<'jit, 'vm>,
) -> Result<usize> { ) -> Result<usize> {
match opcode { match opcode {
OpCode::Illegal => panic!("illegal opcode"), OpCode::Illegal => panic!("illegal opcode"),
@@ -112,7 +114,7 @@ impl<'vm, 'jit: 'vm> VM<'jit> {
OpCode::LoadThunk { idx } => { OpCode::LoadThunk { idx } => {
stack.push(Value::Thunk(Thunk::new(self.get_thunk(idx)).into()))? stack.push(Value::Thunk(Thunk::new(self.get_thunk(idx)).into()))?
} }
OpCode::CaptureEnv => stack.tos().as_ref().unwrap_thunk().capture(env.clone()), OpCode::CaptureEnv => stack.tos().as_ref().unwrap_thunk().capture(*env),
OpCode::ForceValue => { OpCode::ForceValue => {
stack.tos_mut().force(self)?; stack.tos_mut().force(self)?;
} }
@@ -131,7 +133,7 @@ impl<'vm, 'jit: 'vm> VM<'jit> {
OpCode::Func { idx } => { OpCode::Func { idx } => {
let func = self.get_func(idx); let func = self.get_func(idx);
stack.push(Value::Func( stack.push(Value::Func(
Func::new(func, env.clone(), OnceCell::new(), Cell::new(0)).into(), Func::new(func, env, OnceCell::new(), Cell::new(0)).into(),
))?; ))?;
} }
OpCode::UnOp { op } => { OpCode::UnOp { op } => {
@@ -184,7 +186,8 @@ impl<'vm, 'jit: 'vm> VM<'jit> {
stack.push(Value::AttrSet(AttrSet::with_capacity(cap).into()))?; stack.push(Value::AttrSet(AttrSet::with_capacity(cap).into()))?;
} }
OpCode::FinalizeRec => { OpCode::FinalizeRec => {
env.enter_let(stack.tos().clone().unwrap_attr_set().into_inner()); let new = self.bump.alloc(HashMap::new_in(&self.bump));
*env = env.enter_let(stack.tos().as_ref().unwrap_attr_set().as_inner().iter().map(|(&k, v)| (k, v.clone())).collect_into(new), &self.bump);
stack.tos_mut().as_mut().unwrap_attr_set().capture(env); stack.tos_mut().as_mut().unwrap_attr_set().capture(env);
} }
OpCode::PushStaticAttr { name } => { OpCode::PushStaticAttr { name } => {
@@ -244,10 +247,16 @@ impl<'vm, 'jit: 'vm> VM<'jit> {
.clone(), .clone(),
)?; )?;
} }
OpCode::EnterLetEnv => env.enter_let(stack.pop().unwrap_attr_set().into_inner()), OpCode::EnterLetEnv => {
OpCode::LeaveLetEnv => env.leave_let(), let new = self.bump.alloc(HashMap::new_in(&self.bump));
OpCode::EnterWithEnv => env.enter_with(stack.pop().unwrap_attr_set().into_inner()), *env = env.enter_let(stack.pop().unwrap_attr_set().into_inner().iter().map(|(&k, v)| (k, v.clone())).collect_into(new), &self.bump);
OpCode::LeaveWithEnv => env.leave_with(), }
OpCode::LeaveLetEnv => *env = env.leave(),
OpCode::EnterWithEnv => {
let new = self.bump.alloc(HashMap::new_in(&self.bump));
*env = env.enter_with(stack.pop().unwrap_attr_set().into_inner().iter().map(|(&k, v)| (k, v.clone())).collect_into(new), &self.bump);
}
OpCode::LeaveWithEnv => *env = env.leave(),
OpCode::Assert => { OpCode::Assert => {
if !stack.pop().unwrap_const().unwrap_bool() { if !stack.pop().unwrap_const().unwrap_bool() {
todo!() todo!()