feat: init

This commit is contained in:
2025-05-03 12:49:48 +08:00
commit 5e35da49ef
27 changed files with 3390 additions and 0 deletions

47
src/vm/env.rs Normal file
View File

@@ -0,0 +1,47 @@
use rpds::HashTrieMapSync;
use super::value::{Symbol, VmValue};
pub struct Env {
last: Option<*mut Env>,
map: HashTrieMapSync<Symbol, VmValue>,
}
impl Env {
pub fn empty() -> Env {
Env {
last: None,
map: HashTrieMapSync::new_sync(),
}
}
pub fn lookup(&self, symbol: Symbol) -> VmValue {
if let Some(value) = self.map.get(&symbol) {
value.clone()
} else {
let last = unsafe { &*self.last.unwrap() };
last.lookup(symbol)
}
}
pub fn insert(&mut self, symbol: Symbol, value: VmValue) {
self.map.insert_mut(symbol, value);
}
pub fn enter(&mut self, map: HashTrieMapSync<Symbol, VmValue>) {
let last = std::mem::replace(
self,
Env {
last: None,
map,
},
);
self.last = Some(Box::leak(Box::new(last)) as *mut Env);
}
pub fn leave(&mut self) {
let last = unsafe { &*self.last.unwrap() };
self.last = last.last;
self.map = last.map.clone();
}
}

12
src/vm/mod.rs Normal file
View File

@@ -0,0 +1,12 @@
mod env;
mod stack;
mod value;
mod vm;
mod vmthunk;
#[cfg(test)]
mod test;
pub use env::Env;
pub use value::Symbol;
pub use value::VmValue as Value;

93
src/vm/stack.rs Normal file
View File

@@ -0,0 +1,93 @@
use std::mem::{size_of, transmute, MaybeUninit};
use std::ops::Deref;
use anyhow::{anyhow, Result};
use super::value::VmValue;
pub const STACK_SIZE: usize = 8 * 1024 / size_of::<VmValue>();
pub struct Stack<const CAP: usize> {
items: Box<[MaybeUninit<VmValue>; CAP]>,
top: usize,
}
impl<const CAP: usize> Stack<CAP> {
pub fn new() -> Self {
Stack {
items: (0..CAP)
.map(|_| MaybeUninit::uninit())
.collect::<Box<_>>()
.try_into()
.unwrap(),
top: 0,
}
}
pub fn push(&mut self, item: VmValue) -> Result<()> {
self.items
.get_mut(self.top)
.map_or(Err(anyhow!("stack overflow")), |ok| Ok(ok))?
.write(item);
self.top += 1;
Ok(())
}
pub fn pop(&mut self) -> Result<VmValue> {
self.top -= 1;
let item = self
.items
.get_mut(self.top)
.map_or(Err(anyhow!("stack empty")), |ok| Ok(ok))?;
unsafe { Ok(std::mem::replace(item, MaybeUninit::uninit()).assume_init()) }
}
pub fn tos(&self) -> Result<&VmValue> {
if self.top == 0 {
Err(anyhow!(""))
} else {
unsafe { Ok(transmute(self.items.get(self.top - 1).unwrap())) }
}
}
pub fn tos_mut(&mut self) -> Result<&mut VmValue> {
if self.top == 0 {
Err(anyhow!(""))
} else {
unsafe { Ok(transmute(self.items.get_mut(self.top - 1).unwrap())) }
}
}
pub fn with_tos(&self, func: impl Fn(&VmValue)) -> Result<()> {
if self.top != 0 {
Err(anyhow!(""))
} else {
unsafe { func(transmute(self.items.get(self.top - 1).unwrap())) }
Ok(())
}
}
pub fn with_tos_mut(&mut self, func: impl Fn(&mut VmValue)) -> Result<()> {
if self.top != 0 {
Err(anyhow!(""))
} else {
unsafe { func(transmute(self.items.get_mut(self.top - 1).unwrap())) }
Ok(())
}
}
}
impl<const CAP: usize> Deref for Stack<CAP> {
type Target = [VmValue];
fn deref(&self) -> &Self::Target {
unsafe { transmute(&self.items[0..self.top]) }
}
}
impl<const CAP: usize> Drop for Stack<CAP> {
fn drop(&mut self) {
self.items.as_mut_slice()[0..self.top]
.iter_mut()
.map(|item| unsafe { item.assume_init_drop() })
.for_each(drop)
}
}

169
src/vm/test.rs Normal file
View File

@@ -0,0 +1,169 @@
use ecow::EcoString;
use rpds::{ht_map_sync, vector_sync};
use crate::compile::compile;
use crate::value::*;
use crate::bytecode::Const;
use super::vm::run;
#[inline]
fn test_expr(expr: &str, expected: Value) {
let prog = compile(expr).unwrap();
dbg!(&prog);
assert_eq!(run(prog).unwrap(), expected);
}
macro_rules! int {
($e:expr) => {
Value::Const(Const::Int($e))
};
}
macro_rules! float {
($e:expr) => {
Value::Const(Const::Float($e as f64))
};
}
macro_rules! boolean {
($e:expr) => {
Value::Const(Const::Bool($e))
};
}
macro_rules! string {
($e:expr) => {
Value::Const(Const::String(EcoString::from($e)))
};
}
macro_rules! symbol {
($e:expr) => {
Symbol::from($e.to_string())
};
}
macro_rules! list {
($($x:tt)*) => (
Value::List(List::new(vector_sync![$($x)*]))
);
}
macro_rules! attrs {
($($x:tt)*) => (
Value::AttrSet(AttrSet::new(ht_map_sync!{$($x)*}))
)
}
#[test]
fn test_arith() {
test_expr("1", int!(1));
test_expr("1.", float!(1));
test_expr("-1", int!(-1));
test_expr("-1.", float!(-1));
test_expr("1 + 1", int!(2));
test_expr("1 + 1.", float!(2));
test_expr("1. + 1", float!(2));
test_expr("1. + 1.", float!(2));
test_expr("1 - 1", int!(0));
test_expr("1 - 1.", float!(0));
test_expr("1. - 1", float!(0));
test_expr("1. - 1.", float!(0));
test_expr("1 * 1", int!(1));
test_expr("1 * 1.", float!(1));
test_expr("1. * 1", float!(1));
test_expr("1. * 1.", float!(1));
test_expr("1 / 1", int!(1));
test_expr("1 / 1.", float!(1));
test_expr("1. / 1", float!(1));
test_expr("1. / 1.", float!(1));
}
#[test]
fn test_cmp() {
test_expr("1 < 2", boolean!(true));
test_expr("1 < 1", boolean!(false));
test_expr("1 > 0", boolean!(true));
test_expr("1 > 1", boolean!(false));
test_expr("1 <= 1", boolean!(true));
test_expr("1 <= 0", boolean!(false));
test_expr("1 >= 1", boolean!(true));
test_expr("1 >= 2", boolean!(false));
}
#[test]
fn test_string() {
test_expr(r#""test""#, string!("test"));
test_expr(r#""hello" + " world""#, string!("hello world"));
}
#[test]
fn test_bool() {
test_expr("true", boolean!(true));
test_expr("false", boolean!(false));
test_expr("!false", boolean!(true));
test_expr("true && false", boolean!(false));
test_expr("true || false", boolean!(true));
test_expr("true -> false", boolean!(false));
}
#[test]
fn test_list() {
test_expr(
"[ 1 2 3 true ]",
list![int!(1), int!(2), int!(3), boolean!(true)],
);
test_expr(
"[ 1 2 ] ++ [ 3 4 ]",
list![int!(1), int!(2), int!(3), int!(4)],
);
}
#[test]
fn test_attrs() {
test_expr(
"{ a = 1; }",
attrs! {
symbol!("a") => int!(1)
},
);
test_expr("{ a = 1; }.a", int!(1));
test_expr("{ a = 1; }.b or 1", int!(1));
test_expr(
"{ a = { a = 1; }; }.a",
attrs! {
symbol!("a") => int!(1)
},
);
test_expr("{ a.b = 1; }.a.b", int!(1));
test_expr(
"{ a.b = 1; a.c = 2; }",
attrs! { symbol!("a") => attrs!{ symbol!("b") => int!(1), symbol!("c") => int!(2) } },
);
test_expr("{ a.b = 1; } ? a.b", boolean!(true));
test_expr(
"{ a.b = 1; } // { a.c = 2 }",
attrs! { symbol!("a") => attrs!{ symbol!("b") => int!(1), symbol!("c") => int!(2) } },
);
}
#[test]
fn test_if() {
test_expr("if true || false then 1 else 2", int!(1));
}
#[test]
fn test_with() {
test_expr(r#"with { a = 1; }; a"#, int!(1));
}
#[test]
fn test_let() {
test_expr(r#"let a = 1; in a"#, int!(1));
test_expr(r#"let a = { a = 1; }; b = "a"; in a.${b}"#, int!(1));
test_expr(
r#"let b = "c"; in { a.b = 1; } // { a."a${b}" = 2 }"}"#,
attrs! { symbol!("a") => attrs!{ symbol!("b") => int!(1), symbol!("ac") => int!(2) } },
);
}

53
src/vm/value/attrset.rs Normal file
View File

@@ -0,0 +1,53 @@
use derive_more::Constructor;
use rpds::HashTrieMapSync;
use crate::value::{self, Value};
use super::super::vm::VM;
use super::{Symbol, ToValue, VmValue};
#[derive(Debug, Constructor, Clone, PartialEq)]
pub struct AttrSet {
data: HashTrieMapSync<Symbol, VmValue>,
}
impl AttrSet {
pub fn push_attr(&mut self, sym: Symbol, val: VmValue) {
self.data.insert_mut(sym, val);
}
pub fn select(&self, sym: Symbol) -> Option<VmValue> {
self.data.get(&sym).cloned()
}
pub fn has_attr(&self, sym: Symbol) -> bool {
self.data.get(&sym).is_some()
}
pub fn update(mut self, other: AttrSet) -> AttrSet {
for (k, v) in other.data.iter() {
if let Some(attr) = self.data.get(k) {
let new_attr = attr.clone().update(v.clone());
self.data.insert_mut(k.clone(), new_attr);
} else {
self.push_attr(k.clone(), v.clone())
}
}
self
}
pub fn to_data(self) -> HashTrieMapSync<Symbol, VmValue> {
self.data
}
}
impl ToValue for AttrSet {
fn to_value(self, vm: &VM) -> Value {
Value::AttrSet(value::AttrSet::new(
self.data
.iter()
.map(|(sym, value)| (value::Symbol::new(sym.0.clone()), value.clone().to_value(vm)))
.collect(),
))
}
}

36
src/vm/value/list.rs Normal file
View File

@@ -0,0 +1,36 @@
use derive_more::Constructor;
use rpds::VectorSync;
use crate::value::{self, Value};
use super::super::vm::VM;
use super::{ToValue, VmValue};
#[derive(Debug, Constructor, Clone, PartialEq)]
pub struct List {
data: VectorSync<VmValue>,
}
impl List {
pub fn push(&mut self, elem: VmValue) {
self.data.push_back_mut(elem);
}
pub fn concat(mut self, other: List) -> List {
for elem in other.data.iter() {
self.data.push_back_mut(elem.clone());
}
self
}
}
impl ToValue for List {
fn to_value(self, vm: &VM) -> Value {
Value::List(value::List::new(
self.data
.iter()
.map(|value| value.clone().to_value(vm))
.collect(),
))
}
}

251
src/vm/value/mod.rs Normal file
View File

@@ -0,0 +1,251 @@
use derive_more::{Constructor, IsVariant, Unwrap};
use anyhow::Result;
use ecow::EcoString;
use crate::value::*;
use crate::bytecode::Const;
use super::vm::VM;
use super::env::Env;
mod attrset;
mod list;
mod string;
pub use attrset::AttrSet;
pub use list::List;
pub use string::ContextfulString;
pub trait ToValue {
fn to_value(self, vm: &VM) -> Value;
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Constructor)]
pub struct Symbol(EcoString);
impl<T: Into<EcoString>> From<T> for Symbol {
fn from(value: T) -> Self {
Symbol(value.into())
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Constructor)]
pub struct Thunk(usize);
#[derive(Debug, IsVariant, Unwrap, Clone, PartialEq)]
pub enum VmValue {
Const(Const),
Thunk(Thunk),
AttrSet(AttrSet),
List(List),
Catchable(crate::value::Catchable),
PrimOp(crate::builtins::PrimOp),
PartialPrimOp(crate::builtins::PartialPrimOp)
}
use VmValue::Const as VmConst;
impl VmValue {
pub fn call(self, args: Vec<VmValue>) -> VmValue {
match self {
VmValue::PrimOp(func) => func.call(args),
VmValue::PartialPrimOp(func) => func.call(args),
_ => todo!()
}
}
pub fn not(self) -> VmValue {
use Const::*;
match self {
VmConst(Bool(bool)) => VmConst(Bool(!bool)),
_ => todo!(),
}
}
pub fn and(self, other: VmValue) -> VmValue {
use Const::*;
match (self, other) {
(VmConst(Bool(a)), VmConst(Bool(b))) => VmConst(Bool(a && b)),
_ => todo!(),
}
}
pub fn or(self, other: VmValue) -> VmValue {
use Const::*;
match (self, other) {
(VmConst(Bool(a)), VmConst(Bool(b))) => VmConst(Bool(a || b)),
_ => todo!(),
}
}
pub fn eq(self, other: VmValue) -> VmValue {
use Const::Bool;
VmConst(Bool(self == other))
}
pub fn lt(self, other: VmValue) -> VmValue {
use Const::*;
VmConst(Bool(match (self, other) {
(VmConst(Int(a)), VmConst(Int(b))) => a < b,
(VmConst(Int(a)), VmConst(Float(b))) => (a as f64) < b,
(VmConst(Float(a)), VmConst(Int(b))) => a < b as f64,
(VmConst(Float(a)), VmConst(Float(b))) => a < b,
(VmConst(String(a)), VmConst(String(b))) => a < b,
_ => todo!()
}))
}
pub fn neg(self) -> VmValue {
use Const::*;
match self {
VmConst(Int(int)) => VmConst(Int(-int)),
VmConst(Float(float)) => VmConst(Float(-float)),
_ => todo!(),
}
}
pub fn add(self, other: VmValue) -> VmValue {
use Const::*;
match (self, other) {
(VmConst(Int(a)), VmConst(Int(b))) => VmConst(Int(a + b)),
(VmConst(Int(a)), VmConst(Float(b))) => VmConst(Float(a as f64 + b)),
(VmConst(Float(a)), VmConst(Int(b))) => VmConst(Float(a + b as f64)),
(VmConst(Float(a)), VmConst(Float(b))) => VmConst(Float(a + b)),
(VmConst(String(a)), VmConst(String(b))) => {
let mut string = a.clone();
string.push_str(b.as_str());
VmConst(String(string))
}
_ => todo!(),
}
}
pub fn mul(self, other: VmValue) -> VmValue {
use Const::*;
match (self, other) {
(VmConst(Int(a)), VmConst(Int(b))) => VmConst(Int(a * b)),
(VmConst(Int(a)), VmConst(Float(b))) => VmConst(Float(a as f64 * b)),
(VmConst(Float(a)), VmConst(Int(b))) => VmConst(Float(a * b as f64)),
(VmConst(Float(a)), VmConst(Float(b))) => VmConst(Float(a * b)),
_ => todo!(),
}
}
pub fn div(self, other: VmValue) -> VmValue {
use Const::*;
match (self, other) {
(_, VmConst(Int(0))) => todo!(),
(_, VmConst(Float(0.))) => todo!(),
(VmConst(Int(a)), VmConst(Int(b))) => VmConst(Int(a / b)),
(VmConst(Int(a)), VmConst(Float(b))) => VmConst(Float(a as f64 / b)),
(VmConst(Float(a)), VmConst(Int(b))) => VmConst(Float(a / b as f64)),
(VmConst(Float(a)), VmConst(Float(b))) => VmConst(Float(a / b)),
_ => todo!(),
}
}
pub fn concat_string(&mut self, mut other: VmValue) -> &mut Self {
if let (VmConst(Const::String(a)), VmConst(Const::String(b))) = (self.coerce_to_string(), other.coerce_to_string()) {
a.push_str(b.as_str());
} else {
todo!()
}
self
}
pub fn push(&mut self, elem: VmValue) -> &mut Self {
if let VmValue::List(list) = self {
list.push(elem);
} else {
todo!()
}
self
}
pub fn concat(self, other: VmValue) -> VmValue {
if let (VmValue::List(a), VmValue::List(b)) = (self, other) {
VmValue::List(a.concat(b))
} else {
todo!()
}
}
pub fn push_attr(&mut self, sym: Symbol, val: VmValue) -> &mut Self {
if let VmValue::AttrSet(attrs) = self {
attrs.push_attr(sym, val)
} else {
todo!()
}
self
}
pub fn update(self, other: VmValue) -> VmValue {
if let (VmValue::AttrSet(a), VmValue::AttrSet(b)) = (self, other) {
VmValue::AttrSet(a.update(b))
} else {
todo!()
}
}
pub fn select(&mut self, sym: Symbol) -> &mut Self {
if let VmValue::AttrSet(attrs) = self {
let val = attrs
.select(sym.clone())
.unwrap_or(VmValue::Catchable(Catchable::new(Some(format!("{sym:?} not found")))));
*self = val;
} else {
todo!()
}
self
}
pub fn select_with_default(&mut self, sym: Symbol, default: VmValue) -> &mut Self {
if let VmValue::AttrSet(attrs) = self {
let val = attrs.select(sym).unwrap_or(default);
*self = val;
} else {
todo!()
}
self
}
pub fn has_attr(&mut self, sym: Symbol) -> &mut Self {
if let VmValue::AttrSet(attrs) = self {
let val = VmConst(Const::Bool(attrs.has_attr(sym)));
*self = val;
} else {
*self = VmConst(Const::Bool(false));
}
self
}
pub fn coerce_to_string(&mut self) -> &mut Self {
if let VmConst(Const::String(_)) = self {
()
} else {
todo!()
}
self
}
pub fn force(&mut self, vm: &VM, env: &mut Env) -> Result<&mut Self> {
if let VmValue::Thunk(thunk) = self {
let value = vm.get_thunk_value(thunk.0, env)?;
*self = value
}
Ok(self)
}
}
impl ToValue for VmValue {
fn to_value(self, vm: &VM) -> Value {
match self {
VmValue::AttrSet(attrs) => attrs.to_value(vm),
VmValue::List(list) => list.to_value(vm),
VmValue::Catchable(catchable) => Value::Catchable(catchable),
VmValue::Const(cnst) => Value::Const(cnst),
VmValue::Thunk(_) => Value::Thunk,
VmValue::PrimOp(_) => Value::PrimOp,
VmValue::PartialPrimOp(_) => Value::PartialPrimOp,
}
}
}

30
src/vm/value/string.rs Normal file
View File

@@ -0,0 +1,30 @@
// TODO: Contextful String
use ecow::EcoString;
use rpds::List;
pub struct StringContext {
context: List<()>,
}
impl StringContext {
pub fn new() -> StringContext {
StringContext {
context: List::new(),
}
}
}
pub struct ContextfulString {
string: EcoString,
context: StringContext,
}
impl ContextfulString {
pub fn new(string: EcoString) -> ContextfulString {
ContextfulString {
string,
context: StringContext::new(),
}
}
}

188
src/vm/vm.rs Normal file
View File

@@ -0,0 +1,188 @@
use anyhow::{anyhow, Result};
use rpds::{HashTrieMap, HashTrieMapSync, Vector};
use crate::bytecode::{self, *};
use crate::slice::*;
use crate::value::{self, Value};
use crate::builtins::env;
use super::env::Env;
use super::stack::{Stack, STACK_SIZE};
use super::value::{self as vmValue, *};
use super::vmthunk::*;
pub fn run(prog: Program) -> Result<Value> {
let vm = VM::new(prog.thunks);
Ok(vm.eval(prog.top_level, &mut env())?.to_value(&vm))
}
pub struct VM {
thunks: Slice<VmThunk>,
}
impl VM {
fn new(thunks: Thunks) -> Self {
let thunks = thunks
.into_iter()
.map(|bytecode::Thunk { opcodes }| VmThunk::new(opcodes))
.collect();
VM {
thunks,
}
}
pub fn get_thunk_value(&self, idx: usize, env: &mut Env) -> Result<VmValue> {
self.thunks.get(idx).unwrap().force(self, env)
}
pub fn eval(&self, opcodes: OpCodes, env: &mut Env) -> Result<VmValue> {
let mut stack = Stack::<STACK_SIZE>::new();
let mut iter = opcodes.into_iter();
while let Some(opcode) = iter.next() {
let jmp = self.single_op(opcode, &mut stack, env)?;
for _ in 0..jmp {
iter.next().unwrap();
}
}
assert_eq!(stack.len(), 1);
stack.pop()
}
#[inline]
fn single_op<const CAP: usize>(
&self,
opcode: OpCode,
stack: &mut Stack<CAP>,
env: &mut Env,
) -> Result<usize> {
match opcode {
OpCode::NoOp => (),
OpCode::Const { value } => stack.push(VmValue::Const(value))?,
OpCode::LoadThunk { idx } => stack.push(VmValue::Thunk(vmValue::Thunk::new(idx)))?,
OpCode::LoadValue { idx } => {
stack.push(self.get_thunk_value(idx, env)?)?;
}
OpCode::ForceValue => {
stack.tos_mut()?.force(self, env)?;
}
OpCode::Jmp { step } => return Ok(step),
OpCode::JmpIfTrue { step } => {
if let VmValue::Const(Const::Bool(true)) = stack.pop()? {
return Ok(step);
}
}
OpCode::JmpIfFalse { step } => {
if let VmValue::Const(Const::Bool(false)) = stack.pop()? {
return Ok(step);
}
}
OpCode::Call { arity } => {
let mut args = Vec::with_capacity(arity);
for _ in 0..arity {
args.insert(0, stack.pop()?);
}
let func = stack.pop()?;
stack.push(func.call(args))?;
}
OpCode::UnOp { op } => {
use UnOp::*;
let value = stack.pop()?;
stack.push(match op {
Not => value.not(),
})?;
}
OpCode::BinOp { op } => {
use BinOp::*;
let rhs = stack.pop()?;
let lhs = stack.pop()?;
stack.push(match op {
Add => lhs.add(rhs),
And => lhs.and(rhs),
Or => lhs.or(rhs),
Eq => lhs.eq(rhs),
Con => lhs.concat(rhs),
Upd => lhs.update(rhs),
})?;
}
OpCode::ConcatString => {
let rhs = stack.pop()?;
stack.tos_mut()?.concat_string(rhs);
}
OpCode::List => {
stack.push(VmValue::List(List::new(Vector::new_sync())))?;
}
OpCode::PushElem => {
let elem = stack.pop()?;
stack.tos_mut()?.push(elem);
}
OpCode::AttrSet => {
stack.push(VmValue::AttrSet(AttrSet::new(HashTrieMap::new_sync())))?;
}
OpCode::PushStaticAttr { name } => {
let val = stack.pop()?;
stack.tos_mut()?.push_attr(Symbol::new(name), val);
}
OpCode::PushDynamicAttr => {
let val = stack.pop()?;
let mut sym = stack.pop().unwrap();
sym.coerce_to_string();
let sym = sym.unwrap_const().unwrap_string().into();
stack.tos_mut()?.push_attr(sym, val);
}
OpCode::Select { sym } => {
stack.tos_mut()?.select(Symbol::new(sym)).force(self, env)?;
}
OpCode::SelectWithDefault { sym } => {
let default = stack.pop()?;
stack
.tos_mut()?
.select_with_default(Symbol::new(sym), default.clone());
}
OpCode::SelectOrEmpty { sym } => {
stack
.tos_mut()?
.select_with_default(Symbol::new(sym), VmValue::AttrSet(AttrSet::new(HashTrieMapSync::new_sync())));
}
OpCode::SelectDynamic => {
let mut val = stack.pop().unwrap();
val.coerce_to_string();
let sym = val.unwrap_const().unwrap_string().into();
stack.tos_mut()?.select(sym);
}
OpCode::SelectDynamicWithDefault => {
let mut val = stack.pop().unwrap();
val.coerce_to_string();
let sym = val.unwrap_const().unwrap_string().into();
let default = stack.pop()?;
stack.tos_mut()?.select_with_default(sym, default.clone());
}
OpCode::SelectDynamicOrEmpty => {
let mut val = stack.pop().unwrap();
val.coerce_to_string();
let sym = val.unwrap_const().unwrap_string().into();
stack.tos_mut()?.select_with_default(sym, VmValue::AttrSet(AttrSet::new(HashTrieMapSync::new_sync())));
}
OpCode::HasAttr { sym } => {
stack.tos_mut()?.has_attr(Symbol::new(sym));
}
OpCode::HasDynamicAttr => {
let mut val = stack.pop().unwrap();
val.coerce_to_string();
let sym = val.unwrap_const().unwrap_string().into();
stack.tos_mut()?.has_attr(sym);
}
OpCode::LookUp { sym } => {
stack.push(env.lookup(Symbol::new(sym)))?;
}
OpCode::EnterEnv => {
env.enter(stack.pop()?.unwrap_attr_set().to_data());
}
OpCode::LeaveEnv => {
env.leave();
}
_ => todo!(),
}
Ok(0)
}
}

65
src/vm/vmthunk.rs Normal file
View File

@@ -0,0 +1,65 @@
use std::cell::RefCell;
use std::sync::RwLock;
use anyhow::{anyhow, Result};
use derive_more::{IsVariant, Unwrap};
use crate::bytecode::OpCodes;
use super::vm::VM;
use super::env::Env;
use super::value::VmValue;
pub struct VmThunk {
thunk: RefCell<_VmThunk>,
lock: RwLock<()>
}
#[derive(IsVariant, Unwrap)]
enum _VmThunk {
Code(OpCodes),
SuspendedFrom(*const VmThunk),
Value(VmValue),
}
impl VmThunk {
pub fn new(opcodes: OpCodes) -> VmThunk {
VmThunk {
thunk: RefCell::new(_VmThunk::Code(opcodes)),
lock: RwLock::new(())
}
}
pub fn force(&self, vm: &VM, env: &mut Env) -> Result<VmValue> {
{
let _guard = self.lock.read().unwrap();
match &*self.thunk.borrow() {
_VmThunk::Value(value) => return Ok(value.clone()),
_VmThunk::SuspendedFrom(from) => {
return Err(anyhow!(
"already suspended from {from:p} (infinite recursion encountered)"
))
}
_VmThunk::Code(_) => (),
}
}
{
let _guard = self.lock.write().unwrap();
let opcodes = std::mem::replace(
&mut *self.thunk.borrow_mut(),
_VmThunk::SuspendedFrom(self as *const VmThunk),
).unwrap_code();
let value = vm.eval(opcodes, env).unwrap();
let _ = std::mem::replace(&mut *self.thunk.borrow_mut(), _VmThunk::Value(value.clone()));
Ok(value)
}
}
pub fn value(&self) -> Option<VmValue> {
let _guard = self.lock.read();
match &*self.thunk.borrow() {
_VmThunk::Value(value) => Some(value.clone()),
_ => None,
}
}
}