feat: get rid of gc and cyclic thunk
This commit is contained in:
32
Cargo.lock
generated
32
Cargo.lock
generated
@@ -159,26 +159,6 @@ version = "0.1.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "gc-arena"
|
|
||||||
version = "0.5.3"
|
|
||||||
source = "git+https://github.com/kyren/gc-arena?rev=d651e3b4363d525a2d502c2305bc73e291835c84#d651e3b4363d525a2d502c2305bc73e291835c84"
|
|
||||||
dependencies = [
|
|
||||||
"gc-arena-derive",
|
|
||||||
"hashbrown 0.15.3",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "gc-arena-derive"
|
|
||||||
version = "0.5.3"
|
|
||||||
source = "git+https://github.com/kyren/gc-arena?rev=d651e3b4363d525a2d502c2305bc73e291835c84#d651e3b4363d525a2d502c2305bc73e291835c84"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
"synstructure",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
version = "0.14.3"
|
version = "0.14.3"
|
||||||
@@ -319,7 +299,6 @@ version = "0.0.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"derive_more",
|
"derive_more",
|
||||||
"ecow",
|
"ecow",
|
||||||
"gc-arena",
|
|
||||||
"hashbrown 0.15.3",
|
"hashbrown 0.15.3",
|
||||||
"inkwell",
|
"inkwell",
|
||||||
"itertools",
|
"itertools",
|
||||||
@@ -497,17 +476,6 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "synstructure"
|
|
||||||
version = "0.13.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "text-size"
|
name = "text-size"
|
||||||
version = "1.1.1"
|
version = "1.1.1"
|
||||||
|
|||||||
@@ -29,6 +29,5 @@ regex = "1.11"
|
|||||||
hashbrown = "0.15"
|
hashbrown = "0.15"
|
||||||
replace_with = "0.1"
|
replace_with = "0.1"
|
||||||
inkwell = { version = "0.6.0", features = ["llvm18-1"] }
|
inkwell = { version = "0.6.0", features = ["llvm18-1"] }
|
||||||
gc-arena = { git = "https://github.com/kyren/gc-arena", rev = "d651e3b4363d525a2d502c2305bc73e291835c84", features= ["hashbrown"] }
|
|
||||||
|
|
||||||
rustyline = { version = "15.0", optional = true }
|
rustyline = { version = "15.0", optional = true }
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use gc_arena::{Gc, Mutation};
|
|
||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
|
|
||||||
use crate::env::VmEnv;
|
use crate::env::VmEnv;
|
||||||
use crate::ir::{DowngradeContext, Ir};
|
use crate::ir::{DowngradeContext, Ir};
|
||||||
use crate::ty::common::Const;
|
use crate::ty::common::Const;
|
||||||
use crate::ty::internal::{AttrSet, PrimOp, Value};
|
use crate::ty::internal::{PrimOp, Value};
|
||||||
use crate::vm::VM;
|
use crate::vm::VM;
|
||||||
|
|
||||||
pub fn ir_env(ctx: &mut DowngradeContext) -> HashMap<usize, Ir> {
|
pub fn ir_env(ctx: &mut DowngradeContext) -> HashMap<usize, Ir> {
|
||||||
@@ -17,16 +16,16 @@ pub fn ir_env(ctx: &mut DowngradeContext) -> HashMap<usize, Ir> {
|
|||||||
map
|
map
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn vm_env<'gc>(vm: &VM, mc: &Mutation<'gc>) -> Gc<'gc, VmEnv<'gc>> {
|
pub fn vm_env<'gc>(vm: &VM) -> Rc<VmEnv<'gc>> {
|
||||||
let primops = [
|
let primops = [
|
||||||
PrimOp::new("add", 2, |args, _, mc| {
|
PrimOp::new("add", 2, |args, _| {
|
||||||
let Ok([mut first, second]): Result<[Value; 2], _> = args.try_into() else {
|
let Ok([mut first, second]): Result<[Value; 2], _> = args.try_into() else {
|
||||||
unreachable!()
|
unreachable!()
|
||||||
};
|
};
|
||||||
first.add(second);
|
first.add(second);
|
||||||
first.ok()
|
first.ok()
|
||||||
}),
|
}),
|
||||||
PrimOp::new("sub", 2, |args, _, mc| {
|
PrimOp::new("sub", 2, |args, _| {
|
||||||
let Ok([mut first, mut second]): Result<[Value; 2], _> = args.try_into() else {
|
let Ok([mut first, mut second]): Result<[Value; 2], _> = args.try_into() else {
|
||||||
unreachable!()
|
unreachable!()
|
||||||
};
|
};
|
||||||
@@ -34,39 +33,39 @@ pub fn vm_env<'gc>(vm: &VM, mc: &Mutation<'gc>) -> Gc<'gc, VmEnv<'gc>> {
|
|||||||
first.add(second);
|
first.add(second);
|
||||||
first.ok()
|
first.ok()
|
||||||
}),
|
}),
|
||||||
PrimOp::new("mul", 2, |args, _, _| {
|
PrimOp::new("mul", 2, |args, _| {
|
||||||
let Ok([mut first, second]): Result<[Value; 2], _> = args.try_into() else {
|
let Ok([mut first, second]): Result<[Value; 2], _> = args.try_into() else {
|
||||||
unreachable!()
|
unreachable!()
|
||||||
};
|
};
|
||||||
first.mul(second);
|
first.mul(second);
|
||||||
first.ok()
|
first.ok()
|
||||||
}),
|
}),
|
||||||
PrimOp::new("div", 2, |args, _, _| {
|
PrimOp::new("div", 2, |args, _| {
|
||||||
let Ok([mut first, second]): Result<[Value; 2], _> = args.try_into() else {
|
let Ok([mut first, second]): Result<[Value; 2], _> = args.try_into() else {
|
||||||
unreachable!()
|
unreachable!()
|
||||||
};
|
};
|
||||||
first.div(second)?;
|
first.div(second)?;
|
||||||
first.ok()
|
first.ok()
|
||||||
}),
|
}),
|
||||||
PrimOp::new("lessThan", 2, |args, _, _| {
|
PrimOp::new("lessThan", 2, |args, _| {
|
||||||
let Ok([mut first, second]): Result<[Value; 2], _> = args.try_into() else {
|
let Ok([mut first, second]): Result<[Value; 2], _> = args.try_into() else {
|
||||||
unreachable!()
|
unreachable!()
|
||||||
};
|
};
|
||||||
first.lt(second);
|
first.lt(second);
|
||||||
first.ok()
|
first.ok()
|
||||||
}),
|
}),
|
||||||
/* PrimOp::new("seq", 2, |args, vm, mc| {
|
/* PrimOp::new("seq", 2, |args, vm| {
|
||||||
let Ok([mut first, second]): Result<[_; 2], _> = args.try_into() else {
|
let Ok([mut first, second]): Result<[_; 2]> = args.try_into() else {
|
||||||
unreachable!()
|
unreachable!()
|
||||||
};
|
};
|
||||||
first.force(vm, mc).unwrap();
|
first.force(vm).unwrap();
|
||||||
second.ok()
|
second.ok()
|
||||||
}),
|
}),
|
||||||
PrimOp::new("deepSeq", 2, |args, vm, mc| {
|
PrimOp::new("deepSeq", 2, |args, vm| {
|
||||||
let Ok([mut first, second]): Result<[_; 2], _> = args.try_into() else {
|
let Ok([mut first, second]): Result<[_; 2]> = args.try_into() else {
|
||||||
unreachable!()
|
unreachable!()
|
||||||
};
|
};
|
||||||
first.force_deep(vm, mc).unwrap();
|
first.force_deep(vm).unwrap();
|
||||||
second.ok()
|
second.ok()
|
||||||
}), */
|
}), */
|
||||||
];
|
];
|
||||||
@@ -85,16 +84,16 @@ pub fn vm_env<'gc>(vm: &VM, mc: &Mutation<'gc>) -> Gc<'gc, VmEnv<'gc>> {
|
|||||||
map.insert(vm.new_sym(primop.name), Value::PrimOp(primop));
|
map.insert(vm.new_sym(primop.name), Value::PrimOp(primop));
|
||||||
}
|
}
|
||||||
let sym = vm.new_sym("builtins");
|
let sym = vm.new_sym("builtins");
|
||||||
/* let mut attrs = CoW::new(AttrSet::new(map), mc);
|
/* let mut attrs = CoW::new(AttrSet::new(map));
|
||||||
unsafe {
|
unsafe {
|
||||||
attrs.make_cyclic(|attrs, this| {
|
attrs.make_cyclic(|attrs, this| {
|
||||||
let _ = attrs.push_attr(sym, Value::AttrSet(this));
|
let _ = attrs.push_attr(sym, Value::AttrSet(this));
|
||||||
}, mc);
|
});
|
||||||
}
|
}
|
||||||
let builtins = Value::AttrSet(attrs);
|
let builtins = Value::AttrSet(attrs);
|
||||||
|
|
||||||
env_map.insert(sym, builtins); */
|
env_map.insert(sym, builtins); */
|
||||||
// TODO:
|
// TODO:
|
||||||
// VmEnv::new(Gc::new(mc, env_map), mc)
|
// VmEnv::new(Gc::new(mc, env_map))
|
||||||
VmEnv::new(Vec::new(), mc)
|
VmEnv::new(Vec::new())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
use ecow::EcoString;
|
use ecow::EcoString;
|
||||||
use gc_arena::Collect;
|
|
||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
|
|
||||||
use crate::ty::common::Const;
|
use crate::ty::common::Const;
|
||||||
@@ -9,8 +8,7 @@ type Slice<T> = Box<[T]>;
|
|||||||
|
|
||||||
pub type OpCodes = Slice<OpCode>;
|
pub type OpCodes = Slice<OpCode>;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Collect)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
#[collect(no_drop)]
|
|
||||||
pub enum OpCode {
|
pub enum OpCode {
|
||||||
/// load a constant onto stack
|
/// load a constant onto stack
|
||||||
Const { idx: usize },
|
Const { idx: usize },
|
||||||
@@ -90,8 +88,7 @@ pub enum OpCode {
|
|||||||
Illegal,
|
Illegal,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Collect)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
#[collect(no_drop)]
|
|
||||||
pub enum BinOp {
|
pub enum BinOp {
|
||||||
Add,
|
Add,
|
||||||
Sub,
|
Sub,
|
||||||
@@ -105,15 +102,13 @@ pub enum BinOp {
|
|||||||
Upd,
|
Upd,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Collect)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
#[collect(no_drop)]
|
|
||||||
pub enum UnOp {
|
pub enum UnOp {
|
||||||
Neg,
|
Neg,
|
||||||
Not,
|
Not,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Collect)]
|
#[derive(Debug)]
|
||||||
#[collect(no_drop)]
|
|
||||||
pub struct Func {
|
pub struct Func {
|
||||||
pub param: Param,
|
pub param: Param,
|
||||||
pub opcodes: OpCodes,
|
pub opcodes: OpCodes,
|
||||||
|
|||||||
@@ -104,7 +104,10 @@ impl Compile for ir::Arg {
|
|||||||
|
|
||||||
impl Compile for ir::LetVar {
|
impl Compile for ir::LetVar {
|
||||||
fn compile(self, comp: &mut Compiler) {
|
fn compile(self, comp: &mut Compiler) {
|
||||||
comp.push(OpCode::LookUpLet { level: self.level, idx: self.idx });
|
comp.push(OpCode::LookUpLet {
|
||||||
|
level: self.level,
|
||||||
|
idx: self.idx,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,7 +147,9 @@ impl Compile for ir::Attrs {
|
|||||||
|
|
||||||
impl Compile for ir::List {
|
impl Compile for ir::List {
|
||||||
fn compile(self, comp: &mut Compiler) {
|
fn compile(self, comp: &mut Compiler) {
|
||||||
comp.push(OpCode::List { cap: self.items.len() });
|
comp.push(OpCode::List {
|
||||||
|
cap: self.items.len(),
|
||||||
|
});
|
||||||
for item in self.items {
|
for item in self.items {
|
||||||
item.compile(comp);
|
item.compile(comp);
|
||||||
comp.push(OpCode::PushElem);
|
comp.push(OpCode::PushElem);
|
||||||
@@ -385,14 +390,18 @@ impl Compile for ir::If {
|
|||||||
impl Compile for ir::Let {
|
impl Compile for ir::Let {
|
||||||
fn compile(self, comp: &mut Compiler) {
|
fn compile(self, comp: &mut Compiler) {
|
||||||
comp.push(OpCode::List {
|
comp.push(OpCode::List {
|
||||||
cap: self.bindings.len()
|
cap: self.bindings.len(),
|
||||||
});
|
});
|
||||||
for (_, val) in self.bindings {
|
for (_, val) in self.bindings {
|
||||||
val.compile(comp);
|
val.compile(comp);
|
||||||
comp.push(OpCode::PushElem);
|
comp.push(OpCode::PushElem);
|
||||||
}
|
}
|
||||||
comp.push(OpCode::FinalizeLet);
|
comp.push(OpCode::FinalizeLet);
|
||||||
|
let thunk = self.expr.is_thunk();
|
||||||
self.expr.compile(comp);
|
self.expr.compile(comp);
|
||||||
|
if thunk {
|
||||||
|
comp.push(OpCode::CaptureEnv);
|
||||||
|
}
|
||||||
comp.push(OpCode::LeaveEnv);
|
comp.push(OpCode::LeaveEnv);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
195
src/env.rs
195
src/env.rs
@@ -1,42 +1,34 @@
|
|||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use gc_arena::{Collect, Gc, Mutation};
|
|
||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
|
|
||||||
use crate::{ir::Ir, ty::internal::Value};
|
use crate::{ir::Ir, ty::internal::Value};
|
||||||
|
|
||||||
#[derive(Collect)]
|
pub struct Env<K: Hash + Eq, V> {
|
||||||
#[collect(no_drop)]
|
let_: Rc<LetEnv<V>>,
|
||||||
pub struct Env<'gc, K: Hash + Eq + Collect<'gc>, V: Collect<'gc>> {
|
with: Rc<With<K, V>>,
|
||||||
let_: Gc<'gc, LetEnv<'gc, V>>,
|
|
||||||
with: Gc<'gc, With<'gc, K, V>>,
|
|
||||||
args: Vec<V>,
|
args: Vec<V>,
|
||||||
jit_store: Vec<Box<V>>,
|
last: Option<Rc<Env<K, V>>>,
|
||||||
last: Option<Gc<'gc, Env<'gc, K, V>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Collect)]
|
pub struct LetEnv<V> {
|
||||||
#[collect(no_drop)]
|
|
||||||
pub struct LetEnv<'gc, V: Collect<'gc>> {
|
|
||||||
map: Vec<V>,
|
map: Vec<V>,
|
||||||
last: Option<Gc<'gc, LetEnv<'gc, V>>>,
|
last: Option<Rc<LetEnv<V>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type VmEnv<'gc> = Env<'gc, usize, Value<'gc>>;
|
pub type VmEnv<'gc> = Env<usize, Value<'gc>>;
|
||||||
pub type IrEnv<'gc> = Env<'gc, usize, Ir>;
|
pub type IrEnv<'gc> = Env<usize, Ir>;
|
||||||
|
|
||||||
#[derive(Default, Clone, Collect)]
|
#[derive(Default, Clone)]
|
||||||
#[collect(no_drop)]
|
pub struct With<K: Hash + Eq, V> {
|
||||||
pub struct With<'gc, K: Hash + Eq + Collect<'gc>, V: Collect<'gc>> {
|
map: Option<Rc<HashMap<K, V>>>,
|
||||||
map: Option<Gc<'gc, HashMap<K, V>>>,
|
last: Option<Rc<With<K, V>>>,
|
||||||
last: Option<Gc<'gc, With<'gc, K, V>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Collect)]
|
enum LetNode<K: Hash + Eq, V> {
|
||||||
#[collect(no_drop)]
|
Let(Rc<HashMap<K, V>>),
|
||||||
enum LetNode<'gc, K: Hash + Eq + Collect<'gc>, V: Collect<'gc>> {
|
MultiArg(Rc<HashMap<K, V>>),
|
||||||
Let(Gc<'gc, HashMap<K, V>>),
|
|
||||||
MultiArg(Gc<'gc, HashMap<K, V>>),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
@@ -46,24 +38,17 @@ pub enum Type {
|
|||||||
With,
|
With,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'gc, K: Hash + Eq + Clone + Collect<'gc>, V: Clone + Collect<'gc>> Env<'gc, K, V> {
|
impl<K: Hash + Eq + Clone, V: Clone> Env<K, V> {
|
||||||
pub fn new(map: Vec<V>, mc: &Mutation<'gc>) -> Gc<'gc, Self> {
|
pub fn new(map: Vec<V>) -> Rc<Self> {
|
||||||
Gc::new(
|
Rc::new(Self {
|
||||||
mc,
|
let_: LetEnv::new(map),
|
||||||
Self {
|
with: Rc::new(With {
|
||||||
let_: LetEnv::new(map, mc),
|
map: None,
|
||||||
with: Gc::new(
|
|
||||||
mc,
|
|
||||||
With {
|
|
||||||
map: None,
|
|
||||||
last: None,
|
|
||||||
},
|
|
||||||
),
|
|
||||||
args: Vec::new(),
|
|
||||||
jit_store: Vec::new(),
|
|
||||||
last: None,
|
last: None,
|
||||||
},
|
}),
|
||||||
)
|
args: Vec::new(),
|
||||||
|
last: None,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn lookup_arg(&self, level: usize) -> &V {
|
pub fn lookup_arg(&self, level: usize) -> &V {
|
||||||
@@ -83,109 +68,64 @@ impl<'gc, K: Hash + Eq + Clone + Collect<'gc>, V: Clone + Collect<'gc>> Env<'gc,
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn enter_arg(self: Gc<'gc, Self>, val: V, mc: &Mutation<'gc>) -> Gc<'gc, Self> {
|
pub fn enter_arg(self: Rc<Self>, val: V) -> Rc<Self> {
|
||||||
let mut args = self.args.clone();
|
let mut args = self.args.clone();
|
||||||
args.push(val);
|
args.push(val);
|
||||||
Gc::new(
|
Rc::new(Self {
|
||||||
mc,
|
let_: self.let_.clone(),
|
||||||
Env {
|
with: self.with.clone(),
|
||||||
let_: self.let_,
|
last: Some(self),
|
||||||
with: self.with,
|
args,
|
||||||
last: Some(self),
|
})
|
||||||
jit_store: Vec::new(),
|
|
||||||
args
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn enter_let(
|
pub fn enter_let(self: Rc<Self>, map: Vec<V>) -> Rc<Self> {
|
||||||
self: Gc<'gc, Self>,
|
Rc::new(Self {
|
||||||
map: Vec<V>,
|
let_: self.let_.clone().enter_let(map),
|
||||||
mc: &Mutation<'gc>,
|
with: self.with.clone(),
|
||||||
) -> Gc<'gc, Self> {
|
args: self.args.clone(),
|
||||||
Gc::new(
|
last: Some(self),
|
||||||
mc,
|
})
|
||||||
Self {
|
|
||||||
let_: self.let_.enter_let(map, mc),
|
|
||||||
with: self.with,
|
|
||||||
args: self.args.clone(),
|
|
||||||
jit_store: Vec::new(),
|
|
||||||
last: Some(self),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn enter_with(
|
pub fn enter_with(self: Rc<Self>, map: Rc<HashMap<K, V>>) -> Rc<Self> {
|
||||||
self: Gc<'gc, Self>,
|
Rc::new(Self {
|
||||||
map: Gc<'gc, HashMap<K, V>>,
|
let_: self.let_.clone(),
|
||||||
mc: &Mutation<'gc>,
|
with: self.with.clone().enter(map),
|
||||||
) -> Gc<'gc, Self> {
|
args: self.args.clone(),
|
||||||
Gc::new(
|
last: Some(self),
|
||||||
mc,
|
})
|
||||||
Env {
|
|
||||||
let_: self.let_,
|
|
||||||
with: self.with.enter(map, mc),
|
|
||||||
args: self.args.clone(),
|
|
||||||
jit_store: Vec::new(),
|
|
||||||
last: Some(self),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
pub fn leave(&self) -> Rc<Self> {
|
||||||
pub fn jit_store(&'gc mut self, val: V) -> &'gc V {
|
self.last.clone().unwrap()
|
||||||
self.jit_store.push(Box::new(val));
|
|
||||||
&self.jit_store[self.jit_store.len() - 1]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
pub fn jit_stored(&self) -> usize {
|
|
||||||
self.jit_store.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn leave(&self) -> Gc<'gc, Self> {
|
|
||||||
self.last.unwrap()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'gc, V: Clone + Collect<'gc>> LetEnv<'gc, V> {
|
impl<V: Clone> LetEnv<V> {
|
||||||
pub fn new(map: Vec<V>, mc: &Mutation<'gc>) -> Gc<'gc, Self> {
|
pub fn new(map: Vec<V>) -> Rc<Self> {
|
||||||
Gc::new(
|
Rc::new(Self { map, last: None })
|
||||||
mc,
|
|
||||||
Self {
|
|
||||||
map,
|
|
||||||
last: None,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn lookup(&self, level: usize, idx: usize) -> &V {
|
pub fn lookup(&self, level: usize, idx: usize) -> &V {
|
||||||
let mut cur = self;
|
let mut cur = self;
|
||||||
for _ in 0..level {
|
for _ in 0..level {
|
||||||
let last = cur.last.unwrap();
|
cur = cur.last.as_ref().unwrap();
|
||||||
cur = last.as_ref();
|
|
||||||
}
|
}
|
||||||
&cur.map[idx]
|
&cur.map[idx]
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn enter_let(
|
pub fn enter_let(self: Rc<Self>, map: Vec<V>) -> Rc<Self> {
|
||||||
self: Gc<'gc, Self>,
|
Rc::new(Self {
|
||||||
map: Vec<V>,
|
map,
|
||||||
mc: &Mutation<'gc>,
|
last: Some(self),
|
||||||
) -> Gc<'gc, Self> {
|
})
|
||||||
Gc::new(
|
|
||||||
mc,
|
|
||||||
Self {
|
|
||||||
map,
|
|
||||||
last: Some(self),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'gc, K: Hash + Eq + Clone + Collect<'gc>, V: Clone + Collect<'gc>> With<'gc, K, V> {
|
impl<K: Hash + Eq + Clone, V: Clone> With<K, V> {
|
||||||
pub fn lookup(&self, symbol: &K) -> Option<&V> {
|
pub fn lookup(&self, symbol: &K) -> Option<&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);
|
||||||
@@ -193,17 +133,10 @@ impl<'gc, K: Hash + Eq + Clone + Collect<'gc>, V: Clone + Collect<'gc>> With<'gc
|
|||||||
self.last.as_ref().and_then(|env| env.lookup(symbol))
|
self.last.as_ref().and_then(|env| env.lookup(symbol))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn enter(
|
pub fn enter(self: Rc<Self>, map: Rc<HashMap<K, V>>) -> Rc<Self> {
|
||||||
self: Gc<'gc, Self>,
|
Rc::new(Self {
|
||||||
map: Gc<'gc, HashMap<K, V>>,
|
map: Some(map),
|
||||||
mc: &Mutation<'gc>,
|
last: Some(self),
|
||||||
) -> Gc<'gc, Self> {
|
})
|
||||||
Gc::new(
|
|
||||||
mc,
|
|
||||||
Self {
|
|
||||||
map: Some(map),
|
|
||||||
last: Some(self),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
45
src/ir.rs
45
src/ir.rs
@@ -20,7 +20,7 @@ pub fn downgrade(expr: Expr) -> Result<Downgraded> {
|
|||||||
Ok(Downgraded {
|
Ok(Downgraded {
|
||||||
top_level: ir,
|
top_level: ir,
|
||||||
consts: ctx.consts.into(),
|
consts: ctx.consts.into(),
|
||||||
symbols: ctx.symbols.into(),
|
symbols: ctx.symbols,
|
||||||
symmap: ctx.symmap,
|
symmap: ctx.symmap,
|
||||||
thunks: ctx.thunks.into(),
|
thunks: ctx.thunks.into(),
|
||||||
funcs: ctx.funcs.into(),
|
funcs: ctx.funcs.into(),
|
||||||
@@ -228,12 +228,10 @@ impl<'a, 'env> Env<'a, 'env> {
|
|||||||
Builtins(map) => {
|
Builtins(map) => {
|
||||||
return if let Some(ir) = map.get(&ident) {
|
return if let Some(ir) = map.get(&ident) {
|
||||||
Ok(LookupResult::Builtin(ir.clone()))
|
Ok(LookupResult::Builtin(ir.clone()))
|
||||||
|
} else if has_with {
|
||||||
|
Ok(LookupResult::With)
|
||||||
} else {
|
} else {
|
||||||
if has_with {
|
Err(())
|
||||||
Ok(LookupResult::With)
|
|
||||||
} else {
|
|
||||||
Err(())
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
Let(map) => {
|
Let(map) => {
|
||||||
@@ -259,7 +257,7 @@ impl<'a, 'env> Env<'a, 'env> {
|
|||||||
level: arg_level,
|
level: arg_level,
|
||||||
default: default.clone(),
|
default: default.clone(),
|
||||||
});
|
});
|
||||||
} else if alias.map_or(false, |alias| alias == ident) {
|
} else if *alias == Some(ident) {
|
||||||
return Ok(LookupResult::SingleArg { level: arg_level });
|
return Ok(LookupResult::SingleArg { level: arg_level });
|
||||||
} else {
|
} else {
|
||||||
arg_level += 1;
|
arg_level += 1;
|
||||||
@@ -299,7 +297,7 @@ pub struct Downgraded {
|
|||||||
pub funcs: Box<[Func]>,
|
pub funcs: Box<[Func]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> DowngradeContext {
|
impl DowngradeContext {
|
||||||
fn new_thunk(&mut self, thunk: Ir) -> Thunk {
|
fn new_thunk(&mut self, thunk: Ir) -> Thunk {
|
||||||
let idx = self.thunks.len();
|
let idx = self.thunks.len();
|
||||||
self.thunks.push(thunk);
|
self.thunks.push(thunk);
|
||||||
@@ -384,13 +382,10 @@ impl Attrs {
|
|||||||
.get_mut(&ident)
|
.get_mut(&ident)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.as_mut()
|
.as_mut()
|
||||||
.try_unwrap_attrs()
|
.try_unwrap_attrs().map_err(|_| Error::DowngradeError(format!(
|
||||||
.or_else(|_| {
|
|
||||||
Err(Error::DowngradeError(format!(
|
|
||||||
r#"attribute '{}' already defined"#,
|
r#"attribute '{}' already defined"#,
|
||||||
ctx.get_sym(ident)
|
ctx.get_sym(ident)
|
||||||
)))
|
)))
|
||||||
})
|
|
||||||
.and_then(|attrs: &mut Attrs| attrs._insert(path, name, value, ctx))
|
.and_then(|attrs: &mut Attrs| attrs._insert(path, name, value, ctx))
|
||||||
} else {
|
} else {
|
||||||
let mut attrs = Attrs {
|
let mut attrs = Attrs {
|
||||||
@@ -795,7 +790,11 @@ impl Downgrade for ast::AttrSet {
|
|||||||
let rec = self.rec_token().is_some();
|
let rec = self.rec_token().is_some();
|
||||||
let attrs = downgrade_attrs(self, ctx)?;
|
let attrs = downgrade_attrs(self, ctx)?;
|
||||||
if rec {
|
if rec {
|
||||||
let bindings = attrs.stcs.into_iter().sorted_by_key(|(k, _)| *k).collect::<Vec<_>>();
|
let bindings = attrs
|
||||||
|
.stcs
|
||||||
|
.into_iter()
|
||||||
|
.sorted_by_key(|(k, _)| *k)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
let stcs = bindings
|
let stcs = bindings
|
||||||
.iter()
|
.iter()
|
||||||
.map(|&(sym, _)| (sym, Var { sym }.ir()))
|
.map(|&(sym, _)| (sym, Var { sym }.ir()))
|
||||||
@@ -1045,20 +1044,20 @@ impl Downgrade for ast::LetIn {
|
|||||||
|
|
||||||
impl Let {
|
impl Let {
|
||||||
fn resolve<'a, 'env>(self, ctx: &mut DowngradeContext, env: &Env<'a, 'env>) -> Result<Ir> {
|
fn resolve<'a, 'env>(self, ctx: &mut DowngradeContext, env: &Env<'a, 'env>) -> Result<Ir> {
|
||||||
let map = self
|
let map = self.bindings.iter().map(|(sym, _)| *sym).sorted().collect();
|
||||||
.bindings
|
|
||||||
.iter()
|
|
||||||
.map(|(sym, _)| *sym)
|
|
||||||
.sorted()
|
|
||||||
.collect();
|
|
||||||
let env = env.enter_let(&map);
|
let env = env.enter_let(&map);
|
||||||
let bindings = self
|
let bindings = self
|
||||||
.bindings
|
.bindings
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(k, v)| Ok((k, match v.resolve(ctx, &env)? {
|
.map(|(k, v)| {
|
||||||
ir @ Ir::Const(_) => ir,
|
Ok((
|
||||||
ir => ctx.new_thunk(ir).ir()
|
k,
|
||||||
})))
|
match v.resolve(ctx, &env)? {
|
||||||
|
ir @ Ir::Const(_) => ir,
|
||||||
|
ir => ctx.new_thunk(ir).ir(),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
})
|
||||||
.collect::<Result<_>>()?;
|
.collect::<Result<_>>()?;
|
||||||
let expr = self.expr.resolve(ctx, &env)?.boxed();
|
let expr = self.expr.resolve(ctx, &env)?.boxed();
|
||||||
Self { bindings, expr }.ir().ok()
|
Self { bindings, expr }.ir().ok()
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
use gc_arena::{Gc, Mutation};
|
use std::ptr::NonNull;
|
||||||
|
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;
|
||||||
@@ -52,11 +54,11 @@ impl<'ctx> Helpers<'ctx> {
|
|||||||
let ptr_int_type = context.ptr_sized_int_type(execution_engine.get_target_data(), None);
|
let ptr_int_type = context.ptr_sized_int_type(execution_engine.get_target_data(), None);
|
||||||
let ptr_type = context.ptr_type(AddressSpace::default());
|
let ptr_type = context.ptr_type(AddressSpace::default());
|
||||||
let value_type = context.struct_type(&[int_type.into(), int_type.into()], false);
|
let value_type = context.struct_type(&[int_type.into(), int_type.into()], false);
|
||||||
let func_type = value_type.fn_type(&[ptr_type.into(), ptr_type.into()], false);
|
let func_type = value_type.fn_type(&[ptr_type.into()], false);
|
||||||
|
|
||||||
let new_thunk = module.add_function(
|
let new_thunk = module.add_function(
|
||||||
"new_thunk",
|
"new_thunk",
|
||||||
value_type.fn_type(&[ptr_type.into(), ptr_type.into(), ptr_type.into()], false),
|
value_type.fn_type(&[ptr_type.into()], false),
|
||||||
None,
|
None,
|
||||||
);
|
);
|
||||||
let debug = module.add_function(
|
let debug = module.add_function(
|
||||||
@@ -66,10 +68,9 @@ impl<'ctx> Helpers<'ctx> {
|
|||||||
);
|
);
|
||||||
let capture_env = module.add_function(
|
let capture_env = module.add_function(
|
||||||
"capture_env",
|
"capture_env",
|
||||||
context.void_type().fn_type(
|
context
|
||||||
&[value_type.into(), ptr_type.into(), ptr_type.into()],
|
.void_type()
|
||||||
false,
|
.fn_type(&[value_type.into(), ptr_type.into()], false),
|
||||||
),
|
|
||||||
None,
|
None,
|
||||||
);
|
);
|
||||||
let neg = module.add_function(
|
let neg = module.add_function(
|
||||||
@@ -105,13 +106,7 @@ impl<'ctx> Helpers<'ctx> {
|
|||||||
let call = module.add_function(
|
let call = module.add_function(
|
||||||
"call",
|
"call",
|
||||||
value_type.fn_type(
|
value_type.fn_type(
|
||||||
&[
|
&[value_type.into(), value_type.into(), ptr_type.into()],
|
||||||
value_type.into(),
|
|
||||||
value_type.into(),
|
|
||||||
ptr_type.into(),
|
|
||||||
ptr_type.into(),
|
|
||||||
ptr_type.into(),
|
|
||||||
],
|
|
||||||
false,
|
false,
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
@@ -123,7 +118,10 @@ impl<'ctx> Helpers<'ctx> {
|
|||||||
);
|
);
|
||||||
let lookup_let = module.add_function(
|
let lookup_let = module.add_function(
|
||||||
"lookup_let",
|
"lookup_let",
|
||||||
value_type.fn_type(&[ptr_int_type.into(), ptr_int_type.into(), ptr_type.into()], false),
|
value_type.fn_type(
|
||||||
|
&[ptr_int_type.into(), ptr_int_type.into(), ptr_type.into()],
|
||||||
|
false,
|
||||||
|
),
|
||||||
None,
|
None,
|
||||||
);
|
);
|
||||||
let lookup = module.add_function(
|
let lookup = module.add_function(
|
||||||
@@ -134,12 +132,7 @@ impl<'ctx> Helpers<'ctx> {
|
|||||||
let force = module.add_function(
|
let force = module.add_function(
|
||||||
"force",
|
"force",
|
||||||
value_type.fn_type(
|
value_type.fn_type(
|
||||||
&[
|
&[value_type.into(), ptr_type.into(), ptr_type.into()],
|
||||||
value_type.into(),
|
|
||||||
ptr_type.into(),
|
|
||||||
ptr_type.into(),
|
|
||||||
ptr_type.into(),
|
|
||||||
],
|
|
||||||
false,
|
false,
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
@@ -237,14 +230,11 @@ extern "C" fn helper_debug(value: JITValue) {
|
|||||||
dbg!(value.tag);
|
dbg!(value.tag);
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "C" fn helper_capture_env<'gc>(
|
extern "C" fn helper_capture_env<'gc>(thunk: JITValue, env: *const VmEnv<'gc>) {
|
||||||
thunk: JITValue,
|
|
||||||
env: *const VmEnv<'gc>,
|
|
||||||
mc: *const Mutation<'gc>,
|
|
||||||
) {
|
|
||||||
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 { Gc::from_ptr(env) };
|
let env = unsafe { Rc::from_raw(env) };
|
||||||
thunk.capture_env(env, unsafe { mc.as_ref() }.unwrap());
|
thunk.capture_env(env.clone());
|
||||||
|
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 {
|
||||||
@@ -347,21 +337,13 @@ extern "C" fn helper_or(lhs: JITValue, rhs: JITValue) -> JITValue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "C" fn helper_call<'gc>(
|
extern "C" fn helper_call<'gc>(func: JITValue, arg: JITValue, vm: *const VM<'gc>) -> JITValue {
|
||||||
func: JITValue,
|
|
||||||
arg: JITValue,
|
|
||||||
vm: *const VM<'gc>,
|
|
||||||
env: *mut VmEnv<'gc>,
|
|
||||||
mc: *const Mutation<'gc>,
|
|
||||||
) -> JITValue {
|
|
||||||
let vm = unsafe { vm.as_ref() }.unwrap();
|
let vm = unsafe { vm.as_ref() }.unwrap();
|
||||||
let mc = unsafe { mc.as_ref() }.unwrap();
|
|
||||||
let arg = Value::from(arg);
|
let arg = Value::from(arg);
|
||||||
match func.tag {
|
match func.tag {
|
||||||
ValueTag::Function => {
|
ValueTag::Function => {
|
||||||
let func = Value::from(func).unwrap_func();
|
let func = Value::from(func).unwrap_func();
|
||||||
let env = unsafe { &mut *env };
|
func.call_compile(arg, vm).unwrap().clone().into()
|
||||||
func.call_compile(arg, vm, mc).unwrap().clone().into()
|
|
||||||
}
|
}
|
||||||
_ => todo!(),
|
_ => todo!(),
|
||||||
}
|
}
|
||||||
@@ -387,36 +369,28 @@ extern "C" fn helper_lookup(sym: usize, env: *const VmEnv) -> JITValue {
|
|||||||
|
|
||||||
extern "C" fn helper_force<'gc>(
|
extern "C" fn helper_force<'gc>(
|
||||||
thunk: JITValue,
|
thunk: JITValue,
|
||||||
vm: *const VM<'gc>,
|
vm: NonNull<VM<'gc>>,
|
||||||
mc: *const Mutation<'gc>,
|
|
||||||
jit: *const JITContext<'gc>,
|
jit: *const JITContext<'gc>,
|
||||||
) -> JITValue {
|
) -> JITValue {
|
||||||
if !matches!(thunk.tag, ValueTag::Thunk) {
|
if !matches!(thunk.tag, ValueTag::Thunk) {
|
||||||
return thunk;
|
return thunk;
|
||||||
}
|
}
|
||||||
|
|
||||||
let vm = unsafe { vm.as_ref() }.unwrap();
|
let vm = unsafe { vm.as_ref() };
|
||||||
let mc = unsafe { mc.as_ref() }.unwrap();
|
|
||||||
let thunk = Value::from(thunk).unwrap_thunk();
|
let thunk = Value::from(thunk).unwrap_thunk();
|
||||||
if let Some(val) = thunk.get_value() {
|
if let Some(val) = thunk.get_value() {
|
||||||
return val.clone().into();
|
return val.clone().into();
|
||||||
}
|
}
|
||||||
let (opcodes, env) = thunk.suspend(mc).unwrap();
|
let (opcodes, env) = thunk.suspend().unwrap();
|
||||||
let func = unsafe { jit.as_ref() }
|
let func = unsafe { jit.as_ref() }
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.compile_seq(opcodes.iter().copied().rev(), vm)
|
.compile_seq(opcodes.iter().copied().rev(), vm)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let val = unsafe { func(env.as_ref() as *const _, mc as *const _) };
|
let val = unsafe { func(env.as_ref() as *const _) };
|
||||||
thunk.insert_value(val.into(), mc);
|
thunk.insert_value(val.into());
|
||||||
val
|
val
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "C" fn helper_new_thunk<'gc>(opcodes: *const OpCodes, env: *mut VmEnv<'gc>, mc: *const Mutation<'gc>) -> JITValue {
|
extern "C" fn helper_new_thunk(opcodes: *const OpCodes) -> JITValue {
|
||||||
let mc = unsafe { &*mc };
|
Value::Thunk(Thunk::new(unsafe { opcodes.as_ref() }.unwrap())).into()
|
||||||
let env = unsafe { &mut *env };
|
|
||||||
Value::Thunk(Thunk::new(
|
|
||||||
unsafe { opcodes.as_ref() }.unwrap(),
|
|
||||||
mc
|
|
||||||
))
|
|
||||||
.into()
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::rc::Rc;
|
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use gc_arena::{Collect, Gc, Mutation};
|
|
||||||
use inkwell::OptimizationLevel;
|
use inkwell::OptimizationLevel;
|
||||||
use inkwell::builder::Builder;
|
use inkwell::builder::Builder;
|
||||||
use inkwell::context::Context;
|
use inkwell::context::Context;
|
||||||
@@ -66,7 +65,7 @@ impl<'gc> From<JITValue> for Value<'gc> {
|
|||||||
Null => Value::Null,
|
Null => Value::Null,
|
||||||
Function => Value::Func(unsafe { Rc::from_raw(value.data.ptr as *const _) }),
|
Function => Value::Func(unsafe { Rc::from_raw(value.data.ptr as *const _) }),
|
||||||
Thunk => Value::Thunk(self::Thunk {
|
Thunk => Value::Thunk(self::Thunk {
|
||||||
thunk: unsafe { Gc::from_ptr(value.data.ptr as *const _) },
|
thunk: unsafe { Rc::from_raw(value.data.ptr as *const _) },
|
||||||
}),
|
}),
|
||||||
_ => todo!("not implemented for {:?}", value.tag),
|
_ => todo!("not implemented for {:?}", value.tag),
|
||||||
}
|
}
|
||||||
@@ -80,18 +79,16 @@ impl From<Value<'_>> for JITValue {
|
|||||||
tag: ValueTag::Int,
|
tag: ValueTag::Int,
|
||||||
data: JITValueData { int },
|
data: JITValueData { int },
|
||||||
},
|
},
|
||||||
Value::Func(func) => {
|
Value::Func(func) => JITValue {
|
||||||
JITValue {
|
tag: ValueTag::Function,
|
||||||
tag: ValueTag::Function,
|
data: JITValueData {
|
||||||
data: JITValueData {
|
ptr: Rc::into_raw(func) as *const _,
|
||||||
ptr: Rc::into_raw(func) as *const _,
|
},
|
||||||
},
|
},
|
||||||
}
|
|
||||||
}
|
|
||||||
Value::Thunk(thunk) => JITValue {
|
Value::Thunk(thunk) => JITValue {
|
||||||
tag: ValueTag::Thunk,
|
tag: ValueTag::Thunk,
|
||||||
data: JITValueData {
|
data: JITValueData {
|
||||||
ptr: Gc::as_ptr(thunk.thunk) as *const _,
|
ptr: Rc::into_raw(thunk.thunk) as *const _,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
_ => todo!(),
|
_ => todo!(),
|
||||||
@@ -99,19 +96,11 @@ impl From<Value<'_>> for JITValue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct JITFunc<'gc>(F<'gc>, PhantomData<fn(&'gc F<'gc>) -> &'gc F<'gc>>);
|
pub struct JITFunc<'gc>(F<'gc>, PhantomData<&'gc mut ()>);
|
||||||
type F<'gc> = unsafe extern "C" fn(*const VmEnv<'gc>, *const Mutation<'gc>) -> JITValue;
|
type F<'gc> = unsafe extern "C" fn(*const VmEnv<'gc>) -> JITValue;
|
||||||
|
|
||||||
unsafe impl<'gc> Collect<'gc> for JITFunc<'gc> {
|
impl<'gc> From<F<'gc>> for JITFunc<'gc> {
|
||||||
fn trace<T: gc_arena::collect::Trace<'gc>>(&self, _: &mut T) {}
|
fn from(value: F<'gc>) -> Self {
|
||||||
const NEEDS_TRACE: bool = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'gc> From<F<'gc>> for JITFunc<'gc>
|
|
||||||
{
|
|
||||||
fn from(
|
|
||||||
value: F<'gc>
|
|
||||||
) -> Self {
|
|
||||||
Self(value, PhantomData)
|
Self(value, PhantomData)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -132,11 +121,6 @@ pub struct JITContext<'gc> {
|
|||||||
helpers: Helpers<'gc>,
|
helpers: Helpers<'gc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl<'gc> Collect<'gc> for JITContext<'gc> {
|
|
||||||
fn trace<T: gc_arena::collect::Trace<'gc>>(&self, _: &mut T) {}
|
|
||||||
const NEEDS_TRACE: bool = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'gc> JITContext<'gc> {
|
impl<'gc> JITContext<'gc> {
|
||||||
pub fn new(context: &'gc Context) -> Self {
|
pub fn new(context: &'gc Context) -> Self {
|
||||||
// force linker to link JIT engine
|
// force linker to link JIT engine
|
||||||
@@ -172,18 +156,17 @@ impl<'gc> JITContext<'gc> {
|
|||||||
pub fn compile_seq(
|
pub fn compile_seq(
|
||||||
&self,
|
&self,
|
||||||
mut opcodes: impl ExactSizeIterator<Item = OpCode>,
|
mut opcodes: impl ExactSizeIterator<Item = OpCode>,
|
||||||
vm: &'gc VM<'gc>,
|
vm: &VM<'gc>,
|
||||||
) -> Result<JITFunc<'gc>> {
|
) -> Result<JITFunc<'gc>> {
|
||||||
let mut stack = Stack::<_, STACK_SIZE>::new();
|
let mut stack = Stack::<_, STACK_SIZE>::new();
|
||||||
let func_ = self
|
let func_ = self
|
||||||
.module
|
.module
|
||||||
.add_function("nixjit_function", self.helpers.func_type, None);
|
.add_function("nixjit_function", self.helpers.func_type, None);
|
||||||
let env = func_.get_nth_param(0).unwrap().into_pointer_value();
|
let env = func_.get_nth_param(0).unwrap().into_pointer_value();
|
||||||
let mc = func_.get_nth_param(1).unwrap().into_pointer_value();
|
|
||||||
let entry = self.context.append_basic_block(func_, "entry");
|
let entry = self.context.append_basic_block(func_, "entry");
|
||||||
self.builder.position_at_end(entry);
|
self.builder.position_at_end(entry);
|
||||||
let len = opcodes.len();
|
let len = opcodes.len();
|
||||||
self.build_expr(&mut opcodes, vm, env, mc, &mut stack, func_, len)?;
|
self.build_expr(&mut opcodes, vm, env, &mut stack, func_, len)?;
|
||||||
|
|
||||||
assert_eq!(stack.len(), 1);
|
assert_eq!(stack.len(), 1);
|
||||||
let value = stack.pop();
|
let value = stack.pop();
|
||||||
@@ -205,16 +188,15 @@ impl<'gc> JITContext<'gc> {
|
|||||||
fn build_expr<const CAP: usize>(
|
fn build_expr<const CAP: usize>(
|
||||||
&self,
|
&self,
|
||||||
iter: &mut impl Iterator<Item = OpCode>,
|
iter: &mut impl Iterator<Item = OpCode>,
|
||||||
vm: &'gc VM<'gc>,
|
vm: &VM<'gc>,
|
||||||
env: PointerValue<'gc>,
|
env: PointerValue<'gc>,
|
||||||
mc: PointerValue<'gc>,
|
|
||||||
stack: &mut Stack<BasicValueEnum<'gc>, CAP>,
|
stack: &mut Stack<BasicValueEnum<'gc>, CAP>,
|
||||||
func: FunctionValue<'gc>,
|
func: FunctionValue<'gc>,
|
||||||
mut length: usize,
|
mut length: usize,
|
||||||
) -> Result<usize> {
|
) -> Result<usize> {
|
||||||
while length > 1 {
|
while length > 1 {
|
||||||
let opcode = iter.next().unwrap();
|
let opcode = iter.next().unwrap();
|
||||||
let br = self.single_op(opcode, vm, env, mc, stack)?;
|
let br = self.single_op(opcode, vm, env, stack)?;
|
||||||
length -= 1;
|
length -= 1;
|
||||||
if br > 0 {
|
if br > 0 {
|
||||||
let consq = self.context.append_basic_block(func, "consq");
|
let consq = self.context.append_basic_block(func, "consq");
|
||||||
@@ -246,13 +228,13 @@ impl<'gc> JITContext<'gc> {
|
|||||||
|
|
||||||
length -= br;
|
length -= br;
|
||||||
self.builder.position_at_end(consq);
|
self.builder.position_at_end(consq);
|
||||||
let br = self.build_expr(iter, vm, env, mc, stack, func, br)?;
|
let br = self.build_expr(iter, vm, env, stack, func, br)?;
|
||||||
self.builder.build_store(result, stack.pop())?;
|
self.builder.build_store(result, stack.pop())?;
|
||||||
self.builder.build_unconditional_branch(cont)?;
|
self.builder.build_unconditional_branch(cont)?;
|
||||||
|
|
||||||
length -= br;
|
length -= br;
|
||||||
self.builder.position_at_end(alter);
|
self.builder.position_at_end(alter);
|
||||||
self.build_expr(iter, vm, env, mc, stack, func, br)?;
|
self.build_expr(iter, vm, env, stack, func, br)?;
|
||||||
self.builder.build_store(result, stack.pop())?;
|
self.builder.build_store(result, stack.pop())?;
|
||||||
self.builder.build_unconditional_branch(cont)?;
|
self.builder.build_unconditional_branch(cont)?;
|
||||||
|
|
||||||
@@ -265,7 +247,7 @@ impl<'gc> JITContext<'gc> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if length > 0 {
|
if length > 0 {
|
||||||
self.single_op(iter.next().unwrap(), vm, env, mc, stack)
|
self.single_op(iter.next().unwrap(), vm, env, stack)
|
||||||
} else {
|
} else {
|
||||||
Ok(0)
|
Ok(0)
|
||||||
}
|
}
|
||||||
@@ -275,9 +257,8 @@ impl<'gc> JITContext<'gc> {
|
|||||||
fn single_op<const CAP: usize>(
|
fn single_op<const CAP: usize>(
|
||||||
&self,
|
&self,
|
||||||
opcode: OpCode,
|
opcode: OpCode,
|
||||||
vm: &'gc VM<'_>,
|
vm: &VM<'_>,
|
||||||
env: PointerValue<'gc>,
|
env: PointerValue<'gc>,
|
||||||
mc: PointerValue<'gc>,
|
|
||||||
stack: &mut Stack<BasicValueEnum<'gc>, CAP>,
|
stack: &mut Stack<BasicValueEnum<'gc>, CAP>,
|
||||||
) -> Result<usize> {
|
) -> Result<usize> {
|
||||||
match opcode {
|
match opcode {
|
||||||
@@ -295,11 +276,7 @@ impl<'gc> JITContext<'gc> {
|
|||||||
self.builder
|
self.builder
|
||||||
.build_direct_call(
|
.build_direct_call(
|
||||||
self.helpers.new_thunk,
|
self.helpers.new_thunk,
|
||||||
&[
|
&[self.new_ptr(vm.get_thunk(idx) as *const _).into()],
|
||||||
self.new_ptr(vm.get_thunk(idx) as *const _).into(),
|
|
||||||
env.into(),
|
|
||||||
mc.into(),
|
|
||||||
],
|
|
||||||
"call_capture_env",
|
"call_capture_env",
|
||||||
)?
|
)?
|
||||||
.try_as_basic_value()
|
.try_as_basic_value()
|
||||||
@@ -314,7 +291,6 @@ impl<'gc> JITContext<'gc> {
|
|||||||
&[
|
&[
|
||||||
thunk.into(),
|
thunk.into(),
|
||||||
self.new_ptr(vm as *const _).into(),
|
self.new_ptr(vm as *const _).into(),
|
||||||
mc.into(),
|
|
||||||
self.new_ptr(self as *const _).into(),
|
self.new_ptr(self as *const _).into(),
|
||||||
],
|
],
|
||||||
"call_force",
|
"call_force",
|
||||||
@@ -475,7 +451,7 @@ impl<'gc> JITContext<'gc> {
|
|||||||
.builder
|
.builder
|
||||||
.build_direct_call(
|
.build_direct_call(
|
||||||
self.helpers.call,
|
self.helpers.call,
|
||||||
&[func.into(), arg.into(), self.new_ptr(vm).into(), env.into(), mc.into()],
|
&[func.into(), arg.into(), self.new_ptr(vm).into()],
|
||||||
"call",
|
"call",
|
||||||
)?
|
)?
|
||||||
.try_as_basic_value()
|
.try_as_basic_value()
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
use std::mem::{MaybeUninit, replace, transmute};
|
use std::mem::{MaybeUninit, replace, transmute};
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|
||||||
use gc_arena::Collect;
|
|
||||||
|
|
||||||
use crate::error::*;
|
use crate::error::*;
|
||||||
|
|
||||||
macro_rules! into {
|
macro_rules! into {
|
||||||
@@ -20,13 +18,6 @@ pub struct Stack<T, const CAP: usize> {
|
|||||||
top: usize,
|
top: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl<'gc, T: Collect<'gc>, const CAP: usize> Collect<'gc> for Stack<T, CAP> {
|
|
||||||
fn trace<Tr: gc_arena::collect::Trace<'gc>>(&self, cc: &mut Tr) {
|
|
||||||
for v in self.iter() {
|
|
||||||
v.trace(cc);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T, const CAP: usize> Default for Stack<T, CAP> {
|
impl<T, const CAP: usize> Default for Stack<T, CAP> {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
|
|||||||
@@ -3,10 +3,8 @@ use std::hash::Hash;
|
|||||||
|
|
||||||
use derive_more::{Constructor, IsVariant, Unwrap};
|
use derive_more::{Constructor, IsVariant, Unwrap};
|
||||||
use ecow::EcoString;
|
use ecow::EcoString;
|
||||||
use gc_arena::Collect;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Constructor, Hash, Collect)]
|
#[derive(Clone, Debug, PartialEq, Constructor, Hash)]
|
||||||
#[collect(no_drop)]
|
|
||||||
pub struct Catchable {
|
pub struct Catchable {
|
||||||
msg: String,
|
msg: String,
|
||||||
}
|
}
|
||||||
@@ -23,8 +21,7 @@ impl Display for Catchable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, IsVariant, Unwrap, Collect)]
|
#[derive(Debug, Clone, IsVariant, Unwrap)]
|
||||||
#[collect(require_static)]
|
|
||||||
pub enum Const {
|
pub enum Const {
|
||||||
Bool(bool),
|
Bool(bool),
|
||||||
Int(i64),
|
Int(i64),
|
||||||
@@ -115,5 +112,5 @@ impl Eq for Const {}
|
|||||||
|
|
||||||
pub enum MaybeThunk {
|
pub enum MaybeThunk {
|
||||||
Thunk(usize),
|
Thunk(usize),
|
||||||
Const(Const)
|
Const(Const),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ use std::ops::Deref;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use derive_more::Constructor;
|
use derive_more::Constructor;
|
||||||
use gc_arena::Collect;
|
|
||||||
use hashbrown::{HashMap, HashSet};
|
use hashbrown::{HashMap, HashSet};
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
|
|
||||||
@@ -17,12 +16,6 @@ pub struct AttrSet<'gc> {
|
|||||||
data: HashMap<usize, Value<'gc>>,
|
data: HashMap<usize, Value<'gc>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl<'gc> Collect<'gc> for AttrSet<'gc> {
|
|
||||||
fn trace<T: gc_arena::collect::Trace<'gc>>(&self, cc: &mut T) {
|
|
||||||
self.data.trace(cc);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'gc> From<HashMap<usize, Value<'gc>>> for AttrSet<'gc> {
|
impl<'gc> From<HashMap<usize, Value<'gc>>> for AttrSet<'gc> {
|
||||||
fn from(data: HashMap<usize, Value<'gc>>) -> Self {
|
fn from(data: HashMap<usize, Value<'gc>>) -> Self {
|
||||||
Self { data }
|
Self { data }
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
use std::cell::Cell;
|
use std::cell::{Cell, OnceCell};
|
||||||
|
use std::rc::Rc;
|
||||||
use gc_arena::lock::{GcRefLock, RefLock};
|
|
||||||
use gc_arena::{Collect, Gc, Mutation};
|
|
||||||
|
|
||||||
use crate::bytecode::Func as BFunc;
|
use crate::bytecode::Func as BFunc;
|
||||||
use crate::env::VmEnv;
|
use crate::env::VmEnv;
|
||||||
@@ -11,8 +9,7 @@ use crate::jit::JITFunc;
|
|||||||
use crate::ty::internal::Value;
|
use crate::ty::internal::Value;
|
||||||
use crate::vm::VM;
|
use crate::vm::VM;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Collect)]
|
#[derive(Debug, Clone)]
|
||||||
#[collect(no_drop)]
|
|
||||||
pub enum Param {
|
pub enum Param {
|
||||||
Ident(usize),
|
Ident(usize),
|
||||||
Formals {
|
Formals {
|
||||||
@@ -44,42 +41,25 @@ impl From<ir::Param> for Param {
|
|||||||
|
|
||||||
pub struct Func<'gc> {
|
pub struct Func<'gc> {
|
||||||
pub func: &'gc BFunc,
|
pub func: &'gc BFunc,
|
||||||
pub env: Gc<'gc, VmEnv<'gc>>,
|
pub env: Rc<VmEnv<'gc>>,
|
||||||
pub compiled: GcRefLock<'gc, Option<JITFunc<'gc>>>,
|
pub compiled: OnceCell<JITFunc<'gc>>,
|
||||||
pub count: Cell<usize>,
|
pub count: Cell<usize>,
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl<'gc> Collect<'gc> for Func<'gc> {
|
|
||||||
fn trace<Tr: gc_arena::collect::Trace<'gc>>(&self, cc: &mut Tr) {
|
|
||||||
self.env.trace(cc);
|
|
||||||
self.compiled.trace(cc);
|
|
||||||
self.count.trace(cc);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'gc> Func<'gc> {
|
impl<'gc> Func<'gc> {
|
||||||
pub fn new(func: &'gc BFunc, env: Gc<'gc, VmEnv<'gc>>, mc: &Mutation<'gc>) -> Self {
|
pub fn new(func: &'gc BFunc, env: Rc<VmEnv<'gc>>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
func,
|
func,
|
||||||
env,
|
env,
|
||||||
compiled: Gc::new(mc, RefLock::new(None)),
|
compiled: OnceCell::new(),
|
||||||
count: Cell::new(0),
|
count: Cell::new(0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn call_compile(
|
pub fn call_compile(&self, arg: Value<'gc>, vm: &'gc VM<'gc>) -> Result<Value<'gc>> {
|
||||||
&self,
|
let env = self.env.clone().enter_arg(arg);
|
||||||
arg: Value<'gc>,
|
let compiled = self.compiled.get_or_init(|| vm.compile_func(self.func));
|
||||||
vm: &'gc VM<'gc>,
|
let ret = unsafe { compiled(env.as_ref() as *const VmEnv) };
|
||||||
mc: &Mutation<'gc>,
|
|
||||||
) -> Result<Value<'gc>> {
|
|
||||||
let env = self.env.enter_arg(arg, mc);
|
|
||||||
let compiled = self
|
|
||||||
.compiled
|
|
||||||
.borrow_mut(mc)
|
|
||||||
.get_or_insert_with(|| vm.compile_func(self.func))
|
|
||||||
.clone();
|
|
||||||
let ret = unsafe { compiled(env.as_ref() as *const VmEnv, mc as *const _) };
|
|
||||||
Ok(ret.into())
|
Ok(ret.into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
use hashbrown::HashSet;
|
use std::rc::Weak;
|
||||||
use gc_arena::{Collect, Gc, Mutation};
|
|
||||||
|
|
||||||
|
use hashbrown::HashSet;
|
||||||
|
|
||||||
|
use crate::env::VmEnv;
|
||||||
use crate::ty::public as p;
|
use crate::ty::public as p;
|
||||||
use crate::vm::VM;
|
use crate::vm::VM;
|
||||||
use crate::env::VmEnv;
|
|
||||||
|
|
||||||
use super::Value;
|
use super::Value;
|
||||||
|
|
||||||
@@ -12,17 +13,15 @@ pub struct List<'gc> {
|
|||||||
data: Vec<Value<'gc>>,
|
data: Vec<Value<'gc>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl<'gc> Collect<'gc> for List<'gc> {
|
impl<'gc> Default for List<'gc> {
|
||||||
fn trace<T: gc_arena::collect::Trace<'gc>>(&self, cc: &mut T) {
|
fn default() -> Self {
|
||||||
self.data.trace(cc);
|
Self::new()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'gc> List<'gc> {
|
impl<'gc> List<'gc> {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
List {
|
List { data: Vec::new() }
|
||||||
data: Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_capacity(cap: usize) -> Self {
|
pub fn with_capacity(cap: usize) -> Self {
|
||||||
@@ -41,10 +40,10 @@ impl<'gc> List<'gc> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn capture(&mut self, env: Gc<'gc, VmEnv<'gc>>, mc: &Mutation<'gc>) {
|
pub fn capture(&mut self, env: &Weak<VmEnv<'gc>>) {
|
||||||
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_env(env, mc);
|
thunk.capture_env_weak(env.clone());
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
|
use std::cell::RefCell;
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::rc::Rc;
|
use std::rc::{Rc, Weak};
|
||||||
|
|
||||||
use derive_more::{IsVariant, Unwrap};
|
use derive_more::{IsVariant, Unwrap};
|
||||||
use gc_arena::Mutation;
|
|
||||||
use gc_arena::lock::RefLock;
|
|
||||||
use gc_arena::{Collect, Gc, lock::GcRefLock};
|
|
||||||
use hashbrown::HashSet;
|
use hashbrown::HashSet;
|
||||||
use replace_with::replace_with_or_abort;
|
use replace_with::replace_with_or_abort;
|
||||||
|
|
||||||
@@ -27,9 +25,7 @@ pub use func::*;
|
|||||||
pub use list::List;
|
pub use list::List;
|
||||||
pub use primop::*;
|
pub use primop::*;
|
||||||
|
|
||||||
#[derive(IsVariant, Unwrap, Clone, Collect)]
|
#[derive(IsVariant, Unwrap, Clone)]
|
||||||
#[collect(no_drop)]
|
|
||||||
// #[derive(IsVariant, Unwrap, Clone)]
|
|
||||||
pub enum Value<'gc> {
|
pub enum Value<'gc> {
|
||||||
Int(i64),
|
Int(i64),
|
||||||
Float(f64),
|
Float(f64),
|
||||||
@@ -155,16 +151,15 @@ impl<'gc> Value<'gc> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn call(&mut self, arg: Self, vm: &VM, mc: &Mutation<'gc>) -> Result<()> {
|
pub fn call(&mut self, arg: Self, vm: &VM) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
if matches!(arg, Value::Catchable(_)) {
|
if matches!(arg, Value::Catchable(_)) {
|
||||||
*self = arg;
|
*self = arg;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
*self = match self {
|
*self = match self {
|
||||||
PrimOp(func) => func.call(arg, vm, mc),
|
PrimOp(func) => func.call(arg, vm),
|
||||||
PartialPrimOp(func) => func.call(arg, vm, mc),
|
PartialPrimOp(func) => func.call(arg, vm),
|
||||||
// Value::Func(func) => func.call(arg, vm, mc),
|
|
||||||
Catchable(_) => return Ok(()),
|
Catchable(_) => return Ok(()),
|
||||||
_ => todo!(),
|
_ => todo!(),
|
||||||
}?;
|
}?;
|
||||||
@@ -238,20 +233,18 @@ impl<'gc> Value<'gc> {
|
|||||||
|
|
||||||
pub fn add(&mut self, other: Self) {
|
pub fn add(&mut self, other: Self) {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
replace_with_or_abort(self, |a| {
|
replace_with_or_abort(self, |a| match (a, other) {
|
||||||
match (a, other) {
|
(Int(a), Int(b)) => Int(a + b),
|
||||||
(Int(a), Int(b)) => Int(a + b),
|
(Int(a), Float(b)) => Float(a as f64 + b),
|
||||||
(Int(a), Float(b)) => Float(a as f64 + b),
|
(Float(a), Int(b)) => Float(a + b as f64),
|
||||||
(Float(a), Int(b)) => Float(a + b as f64),
|
(Float(a), Float(b)) => Float(a + b),
|
||||||
(Float(a), Float(b)) => Float(a + b),
|
(String(mut a), String(b)) => {
|
||||||
(String(mut a), String(b)) => {
|
Rc::make_mut(&mut a).push_str(&b);
|
||||||
Rc::make_mut(&mut a).push_str(&b);
|
String(a)
|
||||||
String(a)
|
|
||||||
}
|
|
||||||
(a @ Value::Catchable(_), _) => a,
|
|
||||||
(_, x @ Value::Catchable(_)) => x,
|
|
||||||
_ => todo!(),
|
|
||||||
}
|
}
|
||||||
|
(a @ Value::Catchable(_), _) => a,
|
||||||
|
(_, x @ Value::Catchable(_)) => x,
|
||||||
|
_ => todo!(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -430,54 +423,73 @@ impl<'gc> Value<'gc> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[repr(transparent)]
|
#[repr(transparent)]
|
||||||
#[derive(Clone, Collect)]
|
#[derive(Clone)]
|
||||||
#[collect(no_drop)]
|
|
||||||
pub struct Thunk<'gc> {
|
pub struct Thunk<'gc> {
|
||||||
pub thunk: GcRefLock<'gc, _Thunk<'gc>>,
|
pub thunk: Rc<RefCell<_Thunk<'gc>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(IsVariant, Unwrap)]
|
#[derive(IsVariant, Unwrap)]
|
||||||
pub enum _Thunk<'gc> {
|
pub enum _Thunk<'gc> {
|
||||||
Code(&'gc OpCodes, Option<Gc<'gc, VmEnv<'gc>>>),
|
Code(&'gc OpCodes, Option<Env<'gc>>),
|
||||||
Suspended,
|
Suspended,
|
||||||
Value(Value<'gc>),
|
Value(Value<'gc>),
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl<'gc> Collect<'gc> for _Thunk<'gc> {
|
#[derive(Unwrap)]
|
||||||
fn trace<T: gc_arena::collect::Trace<'gc>>(&self, cc: &mut T) {
|
pub enum Env<'gc> {
|
||||||
use _Thunk::*;
|
Strong(Rc<VmEnv<'gc>>),
|
||||||
match self {
|
Weak(Weak<VmEnv<'gc>>),
|
||||||
Code(_, env) => env.trace(cc),
|
}
|
||||||
Value(val) => val.trace(cc),
|
|
||||||
_ => (),
|
impl Env<'_> {
|
||||||
|
fn upgrade(self) -> Self {
|
||||||
|
if let Self::Weak(weak) = self {
|
||||||
|
Env::Strong(weak.upgrade().unwrap())
|
||||||
|
} else {
|
||||||
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'gc> Thunk<'gc> {
|
impl<'gc> Thunk<'gc> {
|
||||||
pub fn new(opcodes: &'gc OpCodes, mc: &Mutation<'gc>) -> Self {
|
pub fn new(opcodes: &'gc OpCodes) -> Self {
|
||||||
Thunk {
|
Thunk {
|
||||||
thunk: Gc::new(mc, RefLock::new(_Thunk::Code(opcodes, None))),
|
thunk: RefCell::new(_Thunk::Code(opcodes, None)).into(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn capture_env(&self, env: Gc<'gc, VmEnv<'gc>>, mc: &Mutation<'gc>) {
|
pub fn capture_env(&self, env: Rc<VmEnv<'gc>>) {
|
||||||
if let _Thunk::Code(_, envcell) = &mut *self.thunk.borrow_mut(mc) {
|
if let _Thunk::Code(_, envcell) = &mut *self.thunk.borrow_mut() {
|
||||||
let _ = envcell.insert(env);
|
let _ = envcell.insert(Env::Strong(env));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn suspend(&self, mc: &Mutation<'gc>) -> Result<(&'gc OpCodes, Gc<'gc, VmEnv<'gc>>)> {
|
pub fn capture_env_weak(&self, env: Weak<VmEnv<'gc>>) {
|
||||||
let _Thunk::Code(opcodes, env) =
|
if let _Thunk::Code(_, envcell) = &mut *self.thunk.borrow_mut() {
|
||||||
std::mem::replace(&mut *self.thunk.borrow_mut(mc), _Thunk::Suspended)
|
let _ = envcell.insert(Env::Weak(env));
|
||||||
else {
|
}
|
||||||
return Err(Error::EvalError("infinite recursion encountered".into()));
|
|
||||||
};
|
|
||||||
Ok((opcodes, env.unwrap()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn insert_value(&self, value: Value<'gc>, mc: &Mutation<'gc>) {
|
pub fn upgrade(&self) {
|
||||||
*self.thunk.borrow_mut(mc) = _Thunk::Value(value);
|
replace_with_or_abort(&mut *self.thunk.borrow_mut(), |this| {
|
||||||
|
if let _Thunk::Code(opcodes, envcell) = this {
|
||||||
|
_Thunk::Code(opcodes, envcell.map(Env::upgrade))
|
||||||
|
} else {
|
||||||
|
this
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn suspend(&self) -> Result<(&'gc OpCodes, Rc<VmEnv<'gc>>)> {
|
||||||
|
use _Thunk::*;
|
||||||
|
match std::mem::replace(&mut *self.thunk.borrow_mut(), _Thunk::Suspended) {
|
||||||
|
Code(opcodes, env) => Ok((opcodes, env.unwrap().upgrade().unwrap_strong())),
|
||||||
|
_ => Err(Error::EvalError("infinite recursion encountered".into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert_value(&self, value: Value<'gc>) {
|
||||||
|
*self.thunk.borrow_mut() = _Thunk::Value(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_value(&self) -> Option<&Value<'gc>> {
|
pub fn get_value(&self) -> Option<&Value<'gc>> {
|
||||||
|
|||||||
@@ -1,20 +1,17 @@
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use derive_more::Constructor;
|
use derive_more::Constructor;
|
||||||
use gc_arena::Collect;
|
|
||||||
use gc_arena::Mutation;
|
|
||||||
|
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::vm::VM;
|
use crate::vm::VM;
|
||||||
|
|
||||||
use super::Value;
|
use super::Value;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Constructor, Collect)]
|
#[derive(Debug, Clone, Constructor)]
|
||||||
#[collect(require_static)]
|
|
||||||
pub struct PrimOp {
|
pub struct PrimOp {
|
||||||
pub name: &'static str,
|
pub name: &'static str,
|
||||||
arity: usize,
|
arity: usize,
|
||||||
func: for<'gc> fn(Vec<Value<'gc>>, &VM, &Mutation<'gc>) -> Result<Value<'gc>>,
|
func: for<'gc> fn(Vec<Value<'gc>>, &VM) -> Result<Value<'gc>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialEq for PrimOp {
|
impl PartialEq for PrimOp {
|
||||||
@@ -24,21 +21,19 @@ impl PartialEq for PrimOp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PrimOp {
|
impl PrimOp {
|
||||||
pub fn call<'gc>(&self, arg: Value<'gc>, vm: &VM, mc: &Mutation<'gc>) -> Result<Value<'gc>> {
|
pub fn call<'gc>(&self, arg: Value<'gc>, vm: &VM) -> Result<Value<'gc>> {
|
||||||
let mut args = Vec::with_capacity(self.arity);
|
let mut args = Vec::with_capacity(self.arity);
|
||||||
args.push(arg);
|
args.push(arg);
|
||||||
if self.arity > 1 {
|
if self.arity > 1 {
|
||||||
Value::PartialPrimOp(Rc::new(
|
Value::PartialPrimOp(Rc::new(PartialPrimOp {
|
||||||
PartialPrimOp {
|
name: self.name,
|
||||||
name: self.name,
|
arity: self.arity - 1,
|
||||||
arity: self.arity - 1,
|
args,
|
||||||
args,
|
func: self.func,
|
||||||
func: self.func,
|
}))
|
||||||
},
|
|
||||||
))
|
|
||||||
.ok()
|
.ok()
|
||||||
} else {
|
} else {
|
||||||
(self.func)(args, vm, mc)
|
(self.func)(args, vm)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -48,15 +43,7 @@ pub struct PartialPrimOp<'gc> {
|
|||||||
pub name: &'static str,
|
pub name: &'static str,
|
||||||
arity: usize,
|
arity: usize,
|
||||||
args: Vec<Value<'gc>>,
|
args: Vec<Value<'gc>>,
|
||||||
func: fn(Vec<Value<'gc>>, &VM, &Mutation<'gc>) -> Result<Value<'gc>>,
|
func: fn(Vec<Value<'gc>>, &VM) -> Result<Value<'gc>>,
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl<'gc> Collect<'gc> for PartialPrimOp<'gc> {
|
|
||||||
fn trace<Tr: gc_arena::collect::Trace<'gc>>(&self, cc: &mut Tr) {
|
|
||||||
for v in self.args.iter() {
|
|
||||||
v.trace(cc);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialEq for PartialPrimOp<'_> {
|
impl PartialEq for PartialPrimOp<'_> {
|
||||||
@@ -66,19 +53,14 @@ impl PartialEq for PartialPrimOp<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'gc> PartialPrimOp<'gc> {
|
impl<'gc> PartialPrimOp<'gc> {
|
||||||
pub fn call(
|
pub fn call(self: &mut Rc<Self>, arg: Value<'gc>, vm: &VM) -> Result<Value<'gc>> {
|
||||||
self: &mut Rc<Self>,
|
|
||||||
arg: Value<'gc>,
|
|
||||||
vm: &VM,
|
|
||||||
mc: &Mutation<'gc>,
|
|
||||||
) -> Result<Value<'gc>> {
|
|
||||||
let func = self.func;
|
let func = self.func;
|
||||||
let Some(ret) = ({
|
let Some(ret) = ({
|
||||||
let self_mut = Rc::make_mut(self);
|
let self_mut = Rc::make_mut(self);
|
||||||
self_mut.args.push(arg);
|
self_mut.args.push(arg);
|
||||||
self_mut.arity -= 1;
|
self_mut.arity -= 1;
|
||||||
if self_mut.arity == 0 {
|
if self_mut.arity == 0 {
|
||||||
Some(func(std::mem::take(&mut self_mut.args), vm, mc))
|
Some(func(std::mem::take(&mut self_mut.args), vm))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|||||||
209
src/vm/mod.rs
209
src/vm/mod.rs
@@ -1,8 +1,6 @@
|
|||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use gc_arena::arena::CollectionPhase;
|
|
||||||
use gc_arena::{Arena, Collect, Gc, Mutation, Rootable};
|
|
||||||
use hashbrown::{HashMap, HashSet};
|
use hashbrown::{HashMap, HashSet};
|
||||||
use inkwell::context::Context;
|
use inkwell::context::Context;
|
||||||
|
|
||||||
@@ -25,110 +23,65 @@ mod test;
|
|||||||
const STACK_SIZE: usize = 8 * 1024 / size_of::<Value>();
|
const STACK_SIZE: usize = 8 * 1024 / size_of::<Value>();
|
||||||
const COLLECTOR_GRANULARITY: f64 = 1024.0;
|
const COLLECTOR_GRANULARITY: f64 = 1024.0;
|
||||||
|
|
||||||
#[derive(Collect)]
|
|
||||||
#[collect(require_static)]
|
|
||||||
struct ContextWrapper(Context);
|
struct ContextWrapper(Context);
|
||||||
|
|
||||||
pub fn run(mut prog: Program) -> Result<p::Value> {
|
pub fn run(mut prog: Program) -> Result<p::Value> {
|
||||||
let mut arena: Arena<Rootable![GcRoot<'_>]> = Arena::new(|mc| {
|
let jit = Context::create();
|
||||||
let jit = Gc::new(mc, ContextWrapper(Context::create()));
|
prog.thunks.iter_mut().for_each(|code| code.reverse());
|
||||||
let mut thunks = std::mem::take(&mut prog.thunks);
|
prog.funcs
|
||||||
thunks.iter_mut().for_each(|code| code.reverse());
|
.iter_mut()
|
||||||
let mut funcs = std::mem::take(&mut prog.funcs);
|
.for_each(|F { opcodes, .. }| opcodes.reverse());
|
||||||
funcs
|
let vm = VM {
|
||||||
.iter_mut()
|
thunks: prog.thunks,
|
||||||
.for_each(|F { opcodes, .. }| opcodes.reverse());
|
funcs: prog.funcs,
|
||||||
let symbols = std::mem::take(&mut prog.symbols);
|
consts: prog.consts,
|
||||||
let symmap = std::mem::take(&mut prog.symmap);
|
symbols: RefCell::new(prog.symbols),
|
||||||
let consts = std::mem::take(&mut prog.consts);
|
symmap: RefCell::new(prog.symmap),
|
||||||
let vm = VM {
|
jit: JITContext::new(&jit),
|
||||||
thunks,
|
};
|
||||||
funcs,
|
|
||||||
consts,
|
|
||||||
symbols: RefCell::new(symbols),
|
|
||||||
symmap: RefCell::new(symmap),
|
|
||||||
jit: JITContext::new(&jit.as_ref().0),
|
|
||||||
};
|
|
||||||
let vm = Gc::new(mc, vm);
|
|
||||||
GcRoot {
|
|
||||||
vm,
|
|
||||||
jit,
|
|
||||||
stack: Stack::new(),
|
|
||||||
envs: vec![vm_env(&vm, mc)],
|
|
||||||
}
|
|
||||||
});
|
|
||||||
prog.top_level.reverse();
|
prog.top_level.reverse();
|
||||||
eval(prog.top_level, &mut arena, |val, root, _| {
|
Ok(eval(prog.top_level, &vm, vm_env(&vm))?.to_public(&vm, &mut HashSet::new()))
|
||||||
Ok(val.to_public(&root.vm, &mut HashSet::new()))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn eval<T, F: for<'gc> FnOnce(Value<'gc>, &mut GcRoot<'gc>, &Mutation<'gc>) -> Result<T>>(
|
pub fn eval<'gc>(opcodes: Box<[OpCode]>, vm: &VM<'gc>, env: Rc<VmEnv<'gc>>) -> Result<Value<'gc>> {
|
||||||
opcodes: Box<[OpCode]>,
|
|
||||||
arena: &mut Arena<impl for<'gc> Rootable<'gc, Root = GcRoot<'gc>>>,
|
|
||||||
f: F,
|
|
||||||
) -> Result<T> {
|
|
||||||
let mut opcodes = opcodes.into_vec();
|
let mut opcodes = opcodes.into_vec();
|
||||||
|
let mut envs = vec![env];
|
||||||
|
let mut stack = Stack::<_, STACK_SIZE>::new();
|
||||||
while let Some(opcode) = opcodes.pop() {
|
while let Some(opcode) = opcodes.pop() {
|
||||||
arena.mutate_root(|mc, root| {
|
let consq = single_op(vm, opcode, &mut stack, envs.last_mut().unwrap())?;
|
||||||
let consq = single_op(
|
match consq {
|
||||||
&root.vm,
|
Consq::NoOp => (),
|
||||||
opcode,
|
Consq::Jmp(step) => opcodes.resize_with(opcodes.len() - step, || unreachable!()),
|
||||||
&mut root.stack,
|
Consq::Force => {
|
||||||
root.envs.last_mut().unwrap(),
|
let thunk = stack.tos().as_ref().unwrap_thunk();
|
||||||
mc,
|
let (code, env) = thunk.suspend()?;
|
||||||
)?;
|
opcodes.push(OpCode::InsertValue);
|
||||||
match consq {
|
opcodes.push(OpCode::PopEnv);
|
||||||
Consq::NoOp => (),
|
opcodes.extend(code);
|
||||||
Consq::Jmp(step) => opcodes.resize_with(opcodes.len() - step, || unreachable!()),
|
envs.push(env);
|
||||||
Consq::Force => {
|
|
||||||
let thunk = root.stack.tos().as_ref().unwrap_thunk();
|
|
||||||
let (code, env) = thunk.suspend(mc)?;
|
|
||||||
opcodes.push(OpCode::InsertValue);
|
|
||||||
opcodes.push(OpCode::PopEnv);
|
|
||||||
opcodes.extend(code);
|
|
||||||
root.envs.push(env);
|
|
||||||
}
|
|
||||||
Consq::PopEnv => {
|
|
||||||
let _ = root.envs.pop().unwrap();
|
|
||||||
}
|
|
||||||
Consq::Call => {
|
|
||||||
let arg = root.stack.pop();
|
|
||||||
let func = root.stack.pop().unwrap_func();
|
|
||||||
let env = func.env.enter_arg(arg, mc);
|
|
||||||
let count = func.count.get();
|
|
||||||
func.count.set(count + 1);
|
|
||||||
if count > 1 {
|
|
||||||
let compiled = func
|
|
||||||
.compiled
|
|
||||||
.borrow_mut(mc)
|
|
||||||
.get_or_insert_with(|| root.vm.compile_func(func.func))
|
|
||||||
.clone();
|
|
||||||
let ret =
|
|
||||||
unsafe { compiled(env.as_ref() as *const VmEnv, mc as *const _) };
|
|
||||||
root.stack.push(ret.into())?;
|
|
||||||
} else {
|
|
||||||
root.envs.push(env);
|
|
||||||
opcodes.push(OpCode::PopEnv);
|
|
||||||
opcodes.extend(&func.func.opcodes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Result::Ok(())
|
Consq::PopEnv => {
|
||||||
})?;
|
let _ = envs.pop().unwrap();
|
||||||
if arena.metrics().allocation_debt() > COLLECTOR_GRANULARITY {
|
}
|
||||||
if arena.collection_phase() == CollectionPhase::Sweeping {
|
Consq::Call => {
|
||||||
arena.collect_debt();
|
let arg = stack.pop();
|
||||||
} else if let Some(marked) = arena.mark_debt() {
|
let func = stack.pop().unwrap_func();
|
||||||
marked.start_sweeping();
|
let env = func.env.clone().enter_arg(arg);
|
||||||
|
let count = func.count.get();
|
||||||
|
func.count.set(count + 1);
|
||||||
|
if count > 1 {
|
||||||
|
let compiled = func.compiled.get_or_init(|| vm.compile_func(func.func));
|
||||||
|
let ret = unsafe { compiled(env.as_ref() as *const VmEnv) };
|
||||||
|
stack.push(ret.into())?;
|
||||||
|
} else {
|
||||||
|
envs.push(env);
|
||||||
|
opcodes.push(OpCode::PopEnv);
|
||||||
|
opcodes.extend(&func.func.opcodes);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
arena.mutate_root(|mc, root| {
|
stack.pop().ok()
|
||||||
assert_eq!(root.stack.len(), 1);
|
|
||||||
let ret = root.stack.pop();
|
|
||||||
f(ret, root, mc)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum Consq {
|
enum Consq {
|
||||||
@@ -139,18 +92,12 @@ enum Consq {
|
|||||||
NoOp,
|
NoOp,
|
||||||
}
|
}
|
||||||
|
|
||||||
enum CycleAction {
|
|
||||||
Collect,
|
|
||||||
NoOp
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn single_op<'gc, const CAP: usize>(
|
fn single_op<'gc, const CAP: usize>(
|
||||||
vm: &'gc VM<'gc>,
|
vm: &VM<'gc>,
|
||||||
opcode: OpCode,
|
opcode: OpCode,
|
||||||
stack: &mut Stack<Value<'gc>, CAP>,
|
stack: &mut Stack<Value<'gc>, CAP>,
|
||||||
env: &mut Gc<'gc, VmEnv<'gc>>,
|
env: &mut Rc<VmEnv<'gc>>,
|
||||||
mc: &'gc Mutation<'gc>,
|
|
||||||
) -> Result<Consq> {
|
) -> Result<Consq> {
|
||||||
match opcode {
|
match opcode {
|
||||||
OpCode::Illegal => panic!("illegal opcode"),
|
OpCode::Illegal => panic!("illegal opcode"),
|
||||||
@@ -161,13 +108,13 @@ fn single_op<'gc, const CAP: usize>(
|
|||||||
Const::String(x) => Value::String(Rc::new(x.into())),
|
Const::String(x) => Value::String(Rc::new(x.into())),
|
||||||
Const::Null => Value::Null,
|
Const::Null => Value::Null,
|
||||||
})?,
|
})?,
|
||||||
OpCode::LoadThunk { idx } => stack.push(Value::Thunk(Thunk::new(vm.get_thunk(idx), mc)))?,
|
OpCode::LoadThunk { idx } => stack.push(Value::Thunk(Thunk::new(vm.get_thunk(idx))))?,
|
||||||
OpCode::LoadValue { idx } => {
|
OpCode::LoadValue { idx } => {
|
||||||
stack.push(Value::Thunk(Thunk::new(vm.get_thunk(idx), mc)))?;
|
stack.push(Value::Thunk(Thunk::new(vm.get_thunk(idx))))?;
|
||||||
stack.tos().as_ref().unwrap_thunk().capture_env(*env, mc);
|
stack.tos().as_ref().unwrap_thunk().capture_env(env.clone());
|
||||||
return Ok(Consq::Force);
|
return Ok(Consq::Force);
|
||||||
}
|
}
|
||||||
OpCode::CaptureEnv => stack.tos().as_ref().unwrap_thunk().capture_env(*env, mc),
|
OpCode::CaptureEnv => stack.tos().as_ref().unwrap_thunk().capture_env(env.clone()),
|
||||||
OpCode::ForceValue => {
|
OpCode::ForceValue => {
|
||||||
if !stack.tos().is_thunk() {
|
if !stack.tos().is_thunk() {
|
||||||
return Ok(Consq::NoOp);
|
return Ok(Consq::NoOp);
|
||||||
@@ -179,7 +126,11 @@ fn single_op<'gc, const CAP: usize>(
|
|||||||
}
|
}
|
||||||
OpCode::InsertValue => {
|
OpCode::InsertValue => {
|
||||||
let val = stack.pop();
|
let val = stack.pop();
|
||||||
stack.tos().as_ref().unwrap_thunk().insert_value(val.clone(), mc);
|
stack
|
||||||
|
.tos()
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_thunk()
|
||||||
|
.insert_value(val.clone());
|
||||||
*stack.tos_mut() = val;
|
*stack.tos_mut() = val;
|
||||||
}
|
}
|
||||||
OpCode::Jmp { step } => return Ok(Consq::Jmp(step)),
|
OpCode::Jmp { step } => return Ok(Consq::Jmp(step)),
|
||||||
@@ -195,11 +146,11 @@ fn single_op<'gc, const CAP: usize>(
|
|||||||
let _ = stack.push(arg);
|
let _ = stack.push(arg);
|
||||||
return Ok(Consq::Call);
|
return Ok(Consq::Call);
|
||||||
}
|
}
|
||||||
func.call(arg, vm, mc)?;
|
func.call(arg, vm)?;
|
||||||
}
|
}
|
||||||
OpCode::Func { idx } => {
|
OpCode::Func { idx } => {
|
||||||
let func = vm.get_func(idx);
|
let func = vm.get_func(idx);
|
||||||
stack.push(Value::Func(Rc::new(Func::new(func, *env, mc))))?;
|
stack.push(Value::Func(Rc::new(Func::new(func, env.clone()))))?;
|
||||||
}
|
}
|
||||||
OpCode::Arg { level } => {
|
OpCode::Arg { level } => {
|
||||||
stack.push(env.lookup_arg(level).clone())?;
|
stack.push(env.lookup_arg(level).clone())?;
|
||||||
@@ -251,12 +202,9 @@ fn single_op<'gc, const CAP: usize>(
|
|||||||
}
|
}
|
||||||
OpCode::FinalizeLet => {
|
OpCode::FinalizeLet => {
|
||||||
let mut list = stack.pop().unwrap_list();
|
let mut list = stack.pop().unwrap_list();
|
||||||
let map = list
|
let map = list.as_ref().clone().into_inner();
|
||||||
.as_ref()
|
*env = env.clone().enter_let(map);
|
||||||
.clone()
|
Rc::make_mut(&mut list).capture(&Rc::downgrade(env));
|
||||||
.into_inner();
|
|
||||||
*env = env.enter_let(map, mc);
|
|
||||||
Rc::make_mut(&mut list).capture(*env, mc);
|
|
||||||
}
|
}
|
||||||
OpCode::PushStaticAttr { name } => {
|
OpCode::PushStaticAttr { name } => {
|
||||||
let val = stack.pop();
|
let val = stack.pop();
|
||||||
@@ -305,7 +253,11 @@ fn single_op<'gc, const CAP: usize>(
|
|||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
OpCode::LookUpLet { level, idx } => {
|
OpCode::LookUpLet { level, idx } => {
|
||||||
stack.push(env.lookup_let(level, idx).clone())?;
|
let val = env.lookup_let(level, idx);
|
||||||
|
if let Value::Thunk(thunk) = val {
|
||||||
|
thunk.upgrade();
|
||||||
|
}
|
||||||
|
stack.push(val.clone())?;
|
||||||
}
|
}
|
||||||
OpCode::LeaveEnv => *env = env.leave(),
|
OpCode::LeaveEnv => *env = env.leave(),
|
||||||
OpCode::EnterWithEnv => {
|
OpCode::EnterWithEnv => {
|
||||||
@@ -317,7 +269,7 @@ fn single_op<'gc, const CAP: usize>(
|
|||||||
.iter()
|
.iter()
|
||||||
.map(|(&k, v)| (k, v.clone()))
|
.map(|(&k, v)| (k, v.clone()))
|
||||||
.collect_into(&mut new);
|
.collect_into(&mut new);
|
||||||
*env = env.enter_with(Gc::new(mc, new), mc);
|
*env = env.clone().enter_with(new.into());
|
||||||
}
|
}
|
||||||
OpCode::PopEnv => return Ok(Consq::PopEnv),
|
OpCode::PopEnv => return Ok(Consq::PopEnv),
|
||||||
OpCode::Assert => {
|
OpCode::Assert => {
|
||||||
@@ -329,18 +281,7 @@ fn single_op<'gc, const CAP: usize>(
|
|||||||
Ok(Consq::NoOp)
|
Ok(Consq::NoOp)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Collect)]
|
#[derive(Constructor)]
|
||||||
#[collect(no_drop)]
|
|
||||||
pub struct GcRoot<'gc, const CAP: usize = STACK_SIZE> {
|
|
||||||
vm: Gc<'gc, VM<'gc>>,
|
|
||||||
jit: Gc<'gc, ContextWrapper>,
|
|
||||||
|
|
||||||
stack: Stack<Value<'gc>, CAP>,
|
|
||||||
envs: Vec<Gc<'gc, VmEnv<'gc>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Constructor, Collect)]
|
|
||||||
#[collect(no_drop)]
|
|
||||||
pub struct VM<'gc> {
|
pub struct VM<'gc> {
|
||||||
thunks: Box<[OpCodes]>,
|
thunks: Box<[OpCodes]>,
|
||||||
funcs: Box<[F]>,
|
funcs: Box<[F]>,
|
||||||
@@ -351,12 +292,12 @@ pub struct VM<'gc> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'gc> VM<'gc> {
|
impl<'gc> VM<'gc> {
|
||||||
pub fn get_thunk(&self, idx: usize) -> &OpCodes {
|
pub fn get_thunk(&self, idx: usize) -> &'gc OpCodes {
|
||||||
&self.thunks[idx]
|
unsafe { &*(&self.thunks[idx] as *const _) }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_func(&self, idx: usize) -> &F {
|
pub fn get_func(&self, idx: usize) -> &'gc F {
|
||||||
&self.funcs[idx]
|
unsafe { &*(&self.funcs[idx] as *const _) }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_sym(&self, idx: usize) -> Symbol {
|
pub fn get_sym(&self, idx: usize) -> Symbol {
|
||||||
@@ -380,7 +321,7 @@ impl<'gc> VM<'gc> {
|
|||||||
self.consts[idx].clone()
|
self.consts[idx].clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn compile_func(&'gc self, func: &'gc F) -> JITFunc<'gc> {
|
pub fn compile_func(&self, func: &'gc F) -> JITFunc<'gc> {
|
||||||
self.jit
|
self.jit
|
||||||
.compile_seq(func.opcodes.iter().copied().rev(), self)
|
.compile_seq(func.opcodes.iter().copied().rev(), self)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
|
|||||||
Reference in New Issue
Block a user