feat: usable?

This commit is contained in:
2025-05-05 11:31:46 +08:00
parent eea4a4ce9f
commit b9dcc83c39
24 changed files with 688 additions and 244 deletions

View File

@@ -1,63 +1,84 @@
use std::cell::RefCell;
use std::sync::Arc;
use rpds::HashTrieMapSync;
use crate::ty::common::Symbol;
use crate::ty::internal::Value;
#[derive(Debug, Default)]
pub struct Env {
last: Option<Box<Env>>,
map: HashTrieMapSync<Symbol, Value>,
last: RefCell<Option<Arc<Env>>>,
map: Arc<RefCell<HashTrieMapSync<Symbol, Value>>>,
}
impl Clone for Env {
fn clone(&self) -> Self {
Env {
last: RefCell::new(self.last.borrow().clone().map(|e| Arc::new(e.as_ref().clone()))),
map: Arc::new(RefCell::new(self.map.borrow().clone()))
}
}
}
#[derive(Debug, Clone)]
pub struct LockedEnv {
map: HashTrieMapSync<Symbol, Value>
pub struct CapturedEnv {
env: Arc<Env>,
}
impl Env {
pub fn empty() -> Env {
Env {
last: None,
map: HashTrieMapSync::new_sync(),
}
Env::default()
}
pub fn lookup(&self, symbol: Symbol) -> Option<Value> {
self.map.get(&symbol).cloned()
self.map.borrow().get(&symbol).cloned()
}
pub fn insert(&mut self, symbol: Symbol, value: Value) {
self.map.insert_mut(symbol, value);
pub fn insert(&self, symbol: Symbol, value: Value) {
self.map.borrow_mut().insert_mut(symbol, value);
}
pub fn enter(&mut self, new: HashTrieMapSync<Symbol, Value>) {
let mut map = self.map.clone();
pub fn enter(&self, new: HashTrieMapSync<Symbol, Value>) {
let mut map = self.map.borrow().clone();
for (k, v) in new.iter() {
map.insert_mut(k.clone(), v.clone());
}
let last = std::mem::replace(self, Env { last: None, map });
self.last = Some(Box::new(last));
let last = Env {
last: self.last.clone(),
map: self.map.clone(),
};
*self.last.borrow_mut() = Some(Arc::new(last));
*self.map.borrow_mut() = map;
}
pub fn leave(&mut self) {
let last = std::mem::replace(&mut self.last, None).unwrap();
let _ = std::mem::replace(&mut self.last, last.last);
self.map = last.map;
pub fn enter_rec(&self) -> Arc<RefCell<HashTrieMapSync<Symbol, Value>>> {
let last = Env {
last: self.last.clone(),
map: self.map.clone(),
};
*self.last.borrow_mut() = Some(Arc::new(last));
self.map.clone()
}
pub fn locked(&self) -> LockedEnv {
LockedEnv { map: self.map.clone() }
pub fn leave(&self) {
let last = std::mem::replace(&mut *self.last.borrow_mut(), None).unwrap();
let _ = std::mem::replace(&mut *self.last.borrow_mut(), last.last.borrow().clone());
let map = last.map.borrow().clone();
*self.map.borrow_mut() = map;
}
pub fn captured(self: Arc<Self>) -> CapturedEnv {
CapturedEnv { env: self }
}
}
impl LockedEnv {
impl CapturedEnv {
pub fn lookup(&self, symbol: Symbol) -> Option<Value> {
self.map.get(&symbol).cloned()
self.env.lookup(symbol)
}
pub fn unlocked(self) -> Env {
Env {
map: self.map,
last: None
}
pub fn released(self) -> Arc<Env> {
Arc::new(self.env.as_ref().clone())
}
}

View File

@@ -6,5 +6,6 @@ mod vmthunk;
#[cfg(test)]
mod test;
pub use env::{Env, LockedEnv};
pub use env::{Env, CapturedEnv};
pub use vm::VM;
pub use vm::run;

View File

@@ -2,8 +2,8 @@ use ecow::EcoString;
use rpds::{ht_map_sync, vector_sync};
use crate::compile::compile;
use crate::ty::public::*;
use crate::ty::common::Symbol;
use crate::ty::public::*;
use super::vm::run;
@@ -14,6 +14,12 @@ fn test_expr(expr: &str, expected: Value) {
assert_eq!(run(prog).unwrap(), expected);
}
macro_rules! thunk {
() => {
Value::Thunk
};
}
macro_rules! int {
($e:expr) => {
Value::Const(Const::Int($e))
@@ -125,7 +131,7 @@ fn test_attrs() {
test_expr(
"{ a = 1; }",
attrs! {
symbol!("a") => int!(1)
symbol!("a") => thunk!()
},
);
test_expr("{ a = 1; }.a", int!(1));
@@ -133,18 +139,18 @@ fn test_attrs() {
test_expr(
"{ a = { a = 1; }; }.a",
attrs! {
symbol!("a") => int!(1)
symbol!("a") => thunk!()
},
);
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) } },
attrs! { symbol!("a") => attrs!{ symbol!("b") => thunk!(), symbol!("c") => thunk!() } },
);
test_expr("{ a.b = 1; } ? a.b", boolean!(true));
test_expr(
"{ a.b = 1; } // { a.c = 2 }",
attrs! { symbol!("a") => attrs!{ symbol!("c") => int!(2) } },
attrs! { symbol!("a") => attrs!{ symbol!("c") => thunk!() } },
);
}
@@ -161,10 +167,11 @@ fn test_with() {
#[test]
fn test_let() {
test_expr(r#"let a = 1; in a"#, int!(1));
test_expr(r#"let a = 1; b = a; in b"#, 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!("ac") => int!(2) } },
r#"let b = "c"; in { a.b = 1; } // { a."a${b}" = 2; }"#,
attrs! { symbol!("a") => attrs!{ symbol!("ac") => thunk!() } },
);
}
@@ -175,5 +182,8 @@ fn test_func() {
test_expr("(x: y: x + y) 1 1", int!(2));
test_expr("({ x, y }: x + y) { x = 1; y = 2; }", int!(3));
test_expr("({ x, y, ... }: x + y) { x = 1; y = 2; z = 3; }", int!(3));
test_expr("(inputs@{ x, y, ... }: x + inputs.y) { x = 1; y = 2; z = 3; }", int!(3));
test_expr(
"(inputs@{ x, y, ... }: x + inputs.y) { x = 1; y = 2; z = 3; }",
int!(3),
);
}

View File

@@ -1,3 +1,5 @@
use std::sync::Arc;
use anyhow::{Result, anyhow};
use crate::builtins::env;
@@ -12,7 +14,7 @@ use super::vmthunk::*;
pub fn run(prog: Program) -> Result<p::Value> {
let vm = VM::new(prog.thunks);
Ok(vm.eval(prog.top_level, &mut env())?.to_public(&vm))
Ok(vm.eval(prog.top_level, env())?.to_public(&vm))
}
pub struct VM {
@@ -28,21 +30,25 @@ impl VM {
VM { thunks }
}
pub fn get_thunk_value(&self, idx: usize, env: &mut Env) -> Result<Value> {
self.thunks.get(idx).unwrap().force(self, env)
pub fn get_thunk_value(&self, idx: usize) -> Result<Value> {
self.thunks.get(idx).unwrap().force(self)
}
pub fn eval(&self, opcodes: OpCodes, env: &mut Env) -> Result<Value> {
pub fn eval(&self, opcodes: OpCodes, env: Arc<Env>) -> Result<Value> {
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)?;
let jmp = self.single_op(opcode, &mut stack, env.clone())?;
for _ in 0..jmp {
iter.next().unwrap();
}
}
assert_eq!(stack.len(), 1);
stack.pop()
let mut ret = stack.pop();
if let Ok(ref mut value) = ret {
value.force(self)?;
}
ret
}
#[inline]
@@ -50,17 +56,20 @@ impl VM {
&self,
opcode: OpCode,
stack: &mut Stack<CAP>,
env: &mut Env,
env: Arc<Env>,
) -> Result<usize> {
match opcode {
OpCode::NoOp => (),
OpCode::Illegal => return Err(anyhow!("illegal opcode")),
OpCode::Const { value } => stack.push(Value::Const(value))?,
OpCode::LoadThunk { idx } => stack.push(Value::Thunk(Thunk::new(idx)))?,
OpCode::LoadThunk { idx } => {
self.thunks[idx].capture(env);
stack.push(Value::Thunk(Thunk::new(idx)))?
}
OpCode::LoadValue { idx } => {
stack.push(self.get_thunk_value(idx, env)?)?;
stack.push(self.get_thunk_value(idx)?)?;
}
OpCode::ForceValue => {
stack.tos_mut()?.force(self, env)?;
stack.tos_mut()?.force(self)?;
}
OpCode::Jmp { step } => return Ok(step),
OpCode::JmpIfTrue { step } => {
@@ -78,11 +87,15 @@ impl VM {
for _ in 0..arity {
args.insert(0, stack.pop()?);
}
let func = stack.pop()?;
let mut func = stack.pop()?;
func.force(self)?;
stack.push(func.call(self, args))?;
}
OpCode::Func { idx } => {
stack.push(Value::Func(Func::new(env.locked(), self.thunks[idx].unwrap_code())))?;
stack.push(Value::Func(Func::new(
env.captured(),
self.thunks[idx].unwrap_code(),
)))?;
}
OpCode::PushIdentParam { sym } => {
stack
@@ -113,15 +126,18 @@ impl VM {
}
OpCode::UnOp { op } => {
use UnOp::*;
let value = stack.pop()?;
let mut value = stack.pop()?;
value.force(self)?;
stack.push(match op {
Not => value.not(),
})?;
}
OpCode::BinOp { op } => {
use BinOp::*;
let rhs = stack.pop()?;
let lhs = stack.pop()?;
let mut rhs = stack.pop()?;
let mut lhs = stack.pop()?;
lhs.force(self)?;
rhs.force(self)?;
stack.push(match op {
Add => lhs.add(rhs),
And => lhs.and(rhs),
@@ -132,7 +148,8 @@ impl VM {
})?;
}
OpCode::ConcatString => {
let rhs = stack.pop()?;
let mut rhs = stack.pop()?;
rhs.force(self)?;
stack.tos_mut()?.concat_string(rhs);
}
OpCode::Path => {
@@ -148,6 +165,10 @@ impl VM {
OpCode::AttrSet => {
stack.push(Value::AttrSet(AttrSet::empty()))?;
}
OpCode::RecAttrSet => {
let new = env.enter_rec();
stack.push(Value::RecAttrSet(RecAttrSet::new(new)))?;
}
OpCode::PushStaticAttr { name } => {
let val = stack.pop()?;
stack.tos_mut()?.push_attr(Symbol::new(name), val);
@@ -160,7 +181,7 @@ impl VM {
stack.tos_mut()?.push_attr(sym, val);
}
OpCode::Select { sym } => {
stack.tos_mut()?.select(Symbol::new(sym)).force(self, env)?;
stack.tos_mut()?.force(self)?.select(Symbol::new(sym));
}
OpCode::SelectOrDefault { sym } => {
let default = stack.pop()?;
@@ -170,13 +191,15 @@ impl VM {
}
OpCode::SelectDynamic => {
let mut val = stack.pop().unwrap();
val.force(self)?;
val.coerce_to_string();
let sym = val.unwrap_const().unwrap_string().into();
stack.tos_mut()?.select(sym);
stack.tos_mut()?.force(self)?.select(sym);
}
OpCode::SelectDynamicOrDefault => {
let default = stack.pop()?;
let mut val = stack.pop().unwrap();
val.force(self)?;
val.coerce_to_string();
let sym = val.unwrap_const().unwrap_string().into();
stack.tos_mut()?.select_with_default(sym, default);
@@ -196,9 +219,11 @@ impl VM {
.ok_or(anyhow!(r#""{sym}" not found"#))?,
)?;
}
OpCode::EnterEnv => {
env.enter(stack.pop()?.unwrap_attr_set().into_inner());
}
OpCode::EnterEnv => match stack.pop()? {
Value::AttrSet(attrs) => env.enter(attrs.into_inner()),
Value::RecAttrSet(attrs) => env.enter(attrs.into_inner()),
_ => unreachable!(),
},
OpCode::LeaveEnv => {
env.leave();
}

View File

@@ -1,5 +1,5 @@
use std::cell::RefCell;
use std::sync::RwLock;
use std::sync::Arc;
use anyhow::{Result, anyhow};
use derive_more::{IsVariant, Unwrap};
@@ -7,12 +7,12 @@ use derive_more::{IsVariant, Unwrap};
use crate::bytecode::OpCodes;
use super::env::Env;
use crate::ty::internal::Value;
use super::vm::VM;
use crate::ty::internal::Value;
pub struct VmThunk {
thunk: RefCell<_VmThunk>,
lock: RwLock<()>,
env: RefCell<Option<Arc<Env>>>,
}
#[derive(IsVariant, Unwrap, Clone)]
@@ -26,18 +26,20 @@ impl VmThunk {
pub fn new(opcodes: OpCodes) -> VmThunk {
VmThunk {
thunk: RefCell::new(_VmThunk::Code(opcodes)),
lock: RwLock::new(()),
env: RefCell::new(None),
}
}
pub fn unwrap_code(&self) -> OpCodes {
let _guard = self.lock.read().unwrap();
self.thunk.borrow().clone().unwrap_code()
}
pub fn force(&self, vm: &VM, env: &mut Env) -> Result<Value> {
pub fn capture(&self, env: Arc<Env>) {
*self.env.borrow_mut() = Some(env);
}
pub fn force(&self, vm: &VM) -> Result<Value> {
{
let _guard = self.lock.read().unwrap();
match &*self.thunk.borrow() {
_VmThunk::Value(value) => return Ok(value.clone()),
_VmThunk::SuspendedFrom(from) => {
@@ -48,13 +50,14 @@ impl VmThunk {
_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 value = vm
.eval(opcodes, self.env.borrow().clone().unwrap())
.unwrap();
let _ = std::mem::replace(
&mut *self.thunk.borrow_mut(),
_VmThunk::Value(value.clone()),
@@ -63,7 +66,6 @@ impl VmThunk {
}
pub fn value(&self) -> Option<Value> {
let _guard = self.lock.read();
match &*self.thunk.borrow() {
_VmThunk::Value(value) => Some(value.clone()),
_ => None,