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,13 +1,24 @@
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::ops::Deref;
use ecow::EcoString;
use derive_more::Constructor;
use ecow::EcoString;
#[derive(Clone, Debug, PartialEq, Constructor)]
pub struct Catchable {
msg: Option<String>,
}
impl Display for Catchable {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
if let Some(ref msg) = self.msg {
write!(f, "<error: {msg}>")
} else {
write!(f, "<error>")
}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Constructor)]
pub struct Symbol(EcoString);
@@ -17,6 +28,12 @@ impl<T: Into<EcoString>> From<T> for Symbol {
}
}
impl Display for Symbol {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
write!(f, r#"Sym({})"#, self.0)
}
}
impl Deref for Symbol {
type Target = str;
fn deref(&self) -> &Self::Target {

View File

@@ -1,11 +1,15 @@
use std::cell::RefCell;
use std::sync::Arc;
use anyhow::Result;
use derive_more::Constructor;
use rpds::HashTrieMapSync;
use super::super::public as p;
use super::super::common::Symbol;
use super::super::public as p;
use crate::vm::VM;
use super::{ToPublic, Value};
use crate::vm::VM;
#[derive(Debug, Constructor, Clone, PartialEq)]
pub struct AttrSet {
@@ -14,7 +18,9 @@ pub struct AttrSet {
impl AttrSet {
pub fn empty() -> AttrSet {
AttrSet { data: HashTrieMapSync::new_sync() }
AttrSet {
data: HashTrieMapSync::new_sync(),
}
}
pub fn push_attr_force(&mut self, sym: Symbol, val: Value) {
@@ -43,6 +49,13 @@ impl AttrSet {
self
}
pub fn update_rec(mut self, other: RecAttrSet) -> AttrSet {
for (k, v) in other.data.borrow().iter() {
self.push_attr_force(k.clone(), v.clone())
}
self
}
pub fn into_inner(self) -> HashTrieMapSync<Symbol, Value> {
self.data
}
@@ -50,6 +63,20 @@ impl AttrSet {
pub fn as_inner(&self) -> &HashTrieMapSync<Symbol, Value> {
&self.data
}
pub fn force_deep(&mut self, vm: &VM) -> Result<()> {
let mut map: Vec<_> = self
.data
.into_iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
map.iter_mut()
.map(|(_, v)| v.force_deep(vm).map(|_| ()))
.find(|v| matches!(v, Err(_)))
.map_or(Ok(()), |err| err)?;
self.data = map.into_iter().collect();
Ok(())
}
}
impl ToPublic for AttrSet {
@@ -57,12 +84,91 @@ impl ToPublic for AttrSet {
p::Value::AttrSet(p::AttrSet::new(
self.data
.iter()
.map(|(sym, value)| {
(
sym.clone(),
value.clone().to_public(vm),
)
})
.map(|(sym, value)| (sym.clone(), value.clone().to_public(vm)))
.collect(),
))
}
}
#[derive(Debug, Constructor, Clone, PartialEq)]
pub struct RecAttrSet {
data: Arc<RefCell<HashTrieMapSync<Symbol, Value>>>,
}
impl RecAttrSet {
pub fn empty() -> RecAttrSet {
RecAttrSet {
data: Arc::default(),
}
}
pub fn push_attr_force(&mut self, sym: Symbol, val: Value) {
self.data.borrow_mut().insert_mut(sym, val);
}
pub fn push_attr(&mut self, sym: Symbol, val: Value) {
if self.data.borrow().get(&sym).is_some() {
todo!()
}
self.data.borrow_mut().insert_mut(sym, val);
}
pub fn select(&self, sym: Symbol) -> Option<Value> {
self.data.borrow().get(&sym).cloned()
}
pub fn has_attr(&self, sym: Symbol) -> bool {
self.data.borrow().get(&sym).is_some()
}
pub fn update(mut self, other: RecAttrSet) -> RecAttrSet {
for (k, v) in other.data.borrow().iter() {
self.push_attr_force(k.clone(), v.clone())
}
self
}
pub fn update_normal(self, other: AttrSet) -> AttrSet {
let map = self
.data
.borrow()
.into_iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let mut new = AttrSet::new(map);
for (k, v) in other.data.iter() {
new.push_attr_force(k.clone(), v.clone())
}
new
}
pub fn into_inner(self) -> HashTrieMapSync<Symbol, Value> {
self.data.borrow().clone()
}
pub fn force_deep(&mut self, vm: &VM) -> Result<()> {
let mut map: Vec<_> = self
.data
.borrow()
.into_iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
map.iter_mut()
.map(|(_, v)| v.force_deep(vm).map(|_| ()))
.find(|v| matches!(v, Err(_)))
.map_or(Ok(()), |err| err)?;
*self.data.borrow_mut() = map.into_iter().collect();
Ok(())
}
}
impl ToPublic for RecAttrSet {
fn to_public(self, vm: &VM) -> p::Value {
p::Value::AttrSet(p::AttrSet::new(
self.data
.borrow()
.iter()
.map(|(sym, value)| (sym.clone(), value.clone().to_public(vm)))
.collect(),
))
}

View File

@@ -5,7 +5,7 @@ use rpds::HashTrieMap;
use crate::bytecode::{OpCodes, ThunkIdx};
use crate::ty::internal::{Thunk, Value};
use crate::vm::{LockedEnv, VM};
use crate::vm::{CapturedEnv, VM};
#[derive(Debug, Clone)]
pub enum Param {
@@ -19,13 +19,13 @@ pub enum Param {
#[derive(Debug, Clone)]
pub struct Func {
pub env: LockedEnv,
pub env: CapturedEnv,
pub param: Option<Param>,
pub opcodes: OpCodes,
}
impl Func {
pub fn new(env: LockedEnv, opcodes: OpCodes) -> Func {
pub fn new(env: CapturedEnv, opcodes: OpCodes) -> Func {
Func {
env,
opcodes,
@@ -36,7 +36,7 @@ impl Func {
pub fn call(self, vm: &VM, arg: Value) -> Value {
use Param::*;
let mut env = self.env.unlocked();
let env = self.env.released();
match self.param.unwrap() {
Ident(ident) => env.enter(HashTrieMap::new_sync().insert(ident.into(), arg)),
@@ -58,9 +58,6 @@ impl Func {
todo!()
}
for (formal, default) in formals {
// let arg = if let Some(default) = default {
// arg.select(format)
// }
let arg = arg
.select(formal.clone().into())
.or_else(|| default.map(|idx| Value::Thunk(Thunk(idx))))
@@ -74,7 +71,7 @@ impl Func {
}
}
vm.eval(self.opcodes, &mut env).unwrap()
vm.eval(self.opcodes, env).unwrap()
}
pub fn push_ident_param(&mut self, param: EcoString) {

View File

@@ -1,10 +1,11 @@
use anyhow::Result;
use derive_more::Constructor;
use rpds::VectorSync;
use crate::ty::public as p;
use crate::vm::VM;
use super::{ToPublic, Value};
use crate::vm::VM;
#[derive(Debug, Constructor, Clone, PartialEq)]
pub struct List {
@@ -14,7 +15,7 @@ pub struct List {
impl List {
pub fn empty() -> List {
List {
data: VectorSync::new_sync()
data: VectorSync::new_sync(),
}
}
@@ -28,6 +29,16 @@ impl List {
}
self
}
pub fn force_deep(&mut self, vm: &VM) -> Result<()> {
let mut vec: Vec<_> = self.data.iter().cloned().collect();
vec.iter_mut()
.map(|v| v.force_deep(vm).map(|_| ()))
.find(|v| matches!(v, Err(_)))
.map_or(Ok(()), |err| err)?;
self.data = vec.into_iter().collect();
Ok(())
}
}
impl ToPublic for List {

View File

@@ -1,27 +1,26 @@
use anyhow::Result;
use derive_more::{Constructor, IsVariant, Unwrap};
use super::public as p;
use super::common as c;
use super::public as p;
use c::Symbol;
use crate::vm::Env;
use crate::vm::VM;
mod attrset;
mod list;
mod string;
mod func;
mod cnst;
mod func;
mod list;
mod primop;
mod string;
pub use attrset::AttrSet;
pub use list::List;
pub use string::ContextfulString;
pub use func::*;
pub use primop::*;
pub use attrset::*;
pub use cnst::Const;
pub use func::*;
pub use list::List;
pub use primop::*;
pub use string::ContextfulString;
pub trait ToPublic {
fn to_public(self, vm: &VM) -> p::Value;
@@ -35,12 +34,12 @@ pub enum Value {
Const(Const),
Thunk(Thunk),
AttrSet(AttrSet),
RecAttrSet(RecAttrSet),
List(List),
Catchable(c::Catchable),
PrimOp(PrimOp),
PartialPrimOp(PartialPrimOp),
Func(Func),
// FuncWithEnv(Func)
}
#[derive(Debug, IsVariant, Unwrap, Clone, PartialEq)]
@@ -48,6 +47,7 @@ pub enum ValueAsRef<'a> {
Const(&'a Const),
Thunk(&'a Thunk),
AttrSet(&'a AttrSet),
RecAttrSet(&'a RecAttrSet),
List(&'a List),
Catchable(&'a c::Catchable),
PrimOp(&'a PrimOp),
@@ -60,6 +60,7 @@ pub enum ValueAsMut<'a> {
Const(&'a mut Const),
Thunk(&'a mut Thunk),
AttrSet(&'a mut AttrSet),
RecAttrSet(&'a mut RecAttrSet),
List(&'a mut List),
Catchable(&'a mut c::Catchable),
PrimOp(&'a mut PrimOp),
@@ -75,6 +76,7 @@ impl Value {
Const(x) => R::Const(x),
Thunk(x) => R::Thunk(x),
AttrSet(x) => R::AttrSet(x),
RecAttrSet(x) => R::RecAttrSet(x),
List(x) => R::List(x),
Catchable(x) => R::Catchable(x),
PrimOp(x) => R::PrimOp(x),
@@ -90,6 +92,7 @@ impl Value {
Const(x) => M::Const(x),
Thunk(x) => M::Thunk(x),
AttrSet(x) => M::AttrSet(x),
RecAttrSet(x) => M::RecAttrSet(x),
List(x) => M::List(x),
Catchable(x) => M::Catchable(x),
PrimOp(x) => M::PrimOp(x),
@@ -104,7 +107,7 @@ impl Value {
pub fn callable(&self) -> bool {
match self {
Value::PrimOp(_) | Value::PartialPrimOp(_) | Value::Func(_) => true,
Value::AttrSet(_) => todo!(),
Value::AttrSet(_) | Value::RecAttrSet(_) => todo!(),
_ => false,
}
}
@@ -112,16 +115,20 @@ impl Value {
pub fn call(self, vm: &VM, args: Vec<Value>) -> Value {
use Value::*;
match self {
PrimOp(func) => func.call(args),
PartialPrimOp(func) => func.call(args),
PrimOp(func) => func.call(vm, args),
PartialPrimOp(func) => func.call(vm, args),
mut func @ Value::Func(_) => {
let mut iter = args.into_iter();
while let Some(arg) = iter.next() {
func = match func {
PrimOp(func) => return func.call([arg].into_iter().chain(iter).collect()),
PartialPrimOp(func) => return func.call([arg].into_iter().chain(iter).collect()),
PrimOp(func) => {
return func.call(vm, [arg].into_iter().chain(iter).collect());
}
PartialPrimOp(func) => {
return func.call(vm, [arg].into_iter().chain(iter).collect());
}
Func(func) => func.call(vm, arg),
_ => todo!()
_ => todo!(),
}
}
func
@@ -251,6 +258,8 @@ impl Value {
pub fn push_attr(&mut self, sym: Symbol, val: Value) -> &mut Self {
if let Value::AttrSet(attrs) = self {
attrs.push_attr(sym, val)
} else if let Value::RecAttrSet(attrs) = self {
attrs.push_attr(sym, val)
} else {
todo!()
}
@@ -258,10 +267,11 @@ impl Value {
}
pub fn update(self, other: Value) -> Value {
if let (Value::AttrSet(a), Value::AttrSet(b)) = (self, other) {
Value::AttrSet(a.update(b))
} else {
todo!()
match (self, other) {
(Value::AttrSet(a), Value::AttrSet(b)) => Value::AttrSet(a.update(b)),
(Value::RecAttrSet(a), Value::AttrSet(b)) => Value::AttrSet(a.update_normal(b)),
(Value::AttrSet(a), Value::RecAttrSet(b)) => Value::AttrSet(a.update_rec(b)),
_ => todo!(),
}
}
@@ -273,6 +283,13 @@ impl Value {
"{sym:?} not found"
)))));
*self = val;
} else if let Value::RecAttrSet(attrs) = self {
let val = attrs
.select(sym.clone())
.unwrap_or(Value::Catchable(c::Catchable::new(Some(format!(
"{sym:?} not found"
)))));
*self = val;
} else {
todo!()
}
@@ -283,6 +300,9 @@ impl Value {
if let Value::AttrSet(attrs) = self {
let val = attrs.select(sym).unwrap_or(default);
*self = val;
} else if let Value::RecAttrSet(attrs) = self {
let val = attrs.select(sym).unwrap_or(default);
*self = val;
} else {
todo!()
}
@@ -293,6 +313,9 @@ impl Value {
if let Value::AttrSet(attrs) = self {
let val = VmConst(Const::Bool(attrs.has_attr(sym)));
*self = val;
} else if let Value::RecAttrSet(attrs) = self {
let val = VmConst(Const::Bool(attrs.has_attr(sym)));
*self = val;
} else {
*self = VmConst(Const::Bool(false));
}
@@ -308,19 +331,35 @@ impl Value {
self
}
pub fn force(&mut self, vm: &VM, env: &mut Env) -> Result<&mut Self> {
pub fn force(&mut self, vm: &VM) -> Result<&mut Self> {
if let Value::Thunk(thunk) = self {
let value = vm.get_thunk_value(thunk.0, env)?;
let value = vm.get_thunk_value(thunk.0)?;
*self = value
}
Ok(self)
}
pub fn force_deep(&mut self, vm: &VM) -> Result<&mut Self> {
match self {
Value::Thunk(thunk) => {
let mut value = vm.get_thunk_value(thunk.0)?;
value.force_deep(vm)?;
*self = value;
}
Value::List(list) => list.force_deep(vm)?,
Value::AttrSet(attrs) => attrs.force_deep(vm)?,
Value::RecAttrSet(attrs) => attrs.force_deep(vm)?,
_ => (),
}
Ok(self)
}
}
impl ToPublic for Value {
fn to_public(self, vm: &VM) -> p::Value {
match self {
Value::AttrSet(attrs) => attrs.to_public(vm),
Value::RecAttrSet(attrs) => attrs.to_public(vm),
Value::List(list) => list.to_public(vm),
Value::Catchable(catchable) => p::Value::Catchable(catchable),
Value::Const(cnst) => p::Value::Const(cnst.into()),

View File

@@ -1,12 +1,14 @@
use derive_more::Constructor;
use crate::vm::VM;
use super::Value;
#[derive(Debug, Clone, Constructor)]
pub struct PrimOp {
pub name: &'static str,
arity: u8,
func: fn(Vec<Value>) -> Value,
func: fn(&VM, Vec<Value>) -> Value,
}
impl PartialEq for PrimOp {
@@ -16,7 +18,7 @@ impl PartialEq for PrimOp {
}
impl PrimOp {
pub fn call(self, args: Vec<Value>) -> Value {
pub fn call(self, vm: &VM, args: Vec<Value>) -> Value {
if (args.len() as u8) < self.arity {
Value::PartialPrimOp(PartialPrimOp {
name: self.name,
@@ -25,7 +27,7 @@ impl PrimOp {
func: self.func,
})
} else if args.len() as u8 == self.arity {
(self.func)(args)
(self.func)(vm, args)
} else {
unimplemented!()
}
@@ -37,7 +39,7 @@ pub struct PartialPrimOp {
pub name: &'static str,
arity: u8,
args: Vec<Value>,
func: fn(Vec<Value>) -> Value,
func: fn(&VM, Vec<Value>) -> Value,
}
impl PartialEq for PartialPrimOp {
@@ -47,7 +49,7 @@ impl PartialEq for PartialPrimOp {
}
impl PartialPrimOp {
pub fn call(mut self, args: Vec<Value>) -> Value {
pub fn call(mut self, vm: &VM, args: Vec<Value>) -> Value {
let len = args.len() as u8;
self.args.extend(args);
if len < self.arity {
@@ -58,10 +60,9 @@ impl PartialPrimOp {
func: self.func,
})
} else if len == self.arity {
(self.func)(self.args)
(self.func)(vm, self.args)
} else {
unimplemented!()
}
}
}

View File

@@ -1,3 +1,3 @@
pub mod public;
pub mod internal;
pub mod common;
pub mod internal;
pub mod public;

View File

@@ -1,3 +1,5 @@
use std::fmt::{Display, Formatter, Result as FmtResult};
use anyhow::Error;
use derive_more::{IsVariant, Unwrap};
use ecow::EcoString;
@@ -12,6 +14,18 @@ pub enum Const {
String(EcoString),
}
impl Display for Const {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
use Const::*;
match self {
Bool(b) => write!(f, "{b}"),
Int(i) => write!(f, "{i}"),
Float(float) => write!(f, "{float}"),
String(s) => write!(f, "{s}"),
}
}
}
impl From<i::Const> for Const {
fn from(value: i::Const) -> Self {
use i::Const::*;

View File

@@ -1,4 +1,4 @@
use std::fmt::{Debug, Formatter, Result as FmtResult};
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use derive_more::{Constructor, IsVariant, Unwrap};
use rpds::{HashTrieMapSync, VectorSync};
@@ -24,11 +24,30 @@ impl Debug for AttrSet {
}
}
impl Display for AttrSet {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
write!(f, "{{ ")?;
for (k, v) in self.data.iter() {
write!(f, "{k} = {v}; ")?;
}
write!(f, "}}")
}
}
#[derive(Constructor, Clone, Debug, PartialEq)]
pub struct List {
data: VectorSync<Value>,
}
impl Display for List {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
write!(f, "[ ")?;
for v in self.data.iter() {
write!(f, "{v} ")?;
}
write!(f, "]")
}
}
#[derive(IsVariant, Unwrap, Clone, Debug, PartialEq)]
pub enum Value {
@@ -41,3 +60,19 @@ pub enum Value {
PrimOp(&'static str),
PartialPrimOp(&'static str),
}
impl Display for Value {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
use Value::*;
match self {
Const(x) => write!(f, "{x}"),
AttrSet(x) => write!(f, "{x}"),
List(x) => write!(f, "{x}"),
Catchable(x) => write!(f, "{x}"),
Thunk => write!(f, "<CODE>"),
Func => write!(f, "<LAMBDA>"),
PrimOp(x) => write!(f, "<PRIMOP {x}>"),
PartialPrimOp(x) => write!(f, "<PARTIAL PRIMOP {x}>"),
}
}
}