rudus/src/process.rs
2024-12-11 17:22:37 -05:00

588 lines
22 KiB
Rust

use crate::base::*;
use crate::parser::*;
use crate::spans::*;
use crate::validator::FnInfo;
use crate::value::Value;
use imbl::HashMap;
use imbl::Vector;
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug)]
pub struct LErr {
pub msg: String,
pub trace: Vec<String>,
}
impl LErr {
pub fn new(msg: String) -> LErr {
LErr {
msg: msg.to_string(),
trace: vec![],
}
}
pub fn add_trace(mut self, fn_name: String) -> LErr {
self.trace.push(fn_name);
self
}
}
type LResult<'src> = Result<Value<'src>, LErr>;
#[derive(Debug)]
pub struct Process<'src> {
pub locals: Vec<(String, Value<'src>)>,
pub prelude: Vec<(String, Value<'src>)>,
pub ast: &'src Ast,
pub fn_info: std::collections::HashMap<*const Ast, FnInfo>,
}
impl<'src> Process<'src> {
pub fn resolve(&self, word: &String) -> LResult<'src> {
let resolved_local = self.locals.iter().rev().find(|(name, _)| word == name);
match resolved_local {
Some((_, value)) => Ok(value.clone()),
None => {
let resolved_prelude = self.prelude.iter().rev().find(|(name, _)| word == name);
match resolved_prelude {
Some((_, value)) => Ok(value.clone()),
None => Err(LErr::new(format!("unbound name {word}"))),
}
}
}
}
pub fn bind(&mut self, word: String, value: &Value<'src>) {
self.locals.push((word, value.clone()));
}
pub fn pop_to(&mut self, n: usize) {
while self.locals.len() > n {
self.locals.pop();
}
}
pub fn match_eq<T>(&self, x: T, y: T) -> Option<&Process<'src>>
where
T: PartialEq,
{
if x == y {
Some(self)
} else {
None
}
}
pub fn match_pattern(&mut self, patt: &Ast, val: &Value<'src>) -> Option<&Process<'src>> {
use Ast::*;
match (patt, val) {
(NilPattern, Value::Nil) => Some(self),
(PlaceholderPattern, _) => Some(self),
(NumberPattern(x), Value::Number(y)) => self.match_eq(x, y),
(BooleanPattern(x), Value::Boolean(y)) => self.match_eq(x, y),
(KeywordPattern(x), Value::Keyword(y)) => self.match_eq(x, y),
(StringPattern(x), Value::InternedString(y)) => self.match_eq(x, y),
(StringPattern(x), Value::AllocatedString(y)) => self.match_eq(&x.to_string(), y),
(InterpolatedPattern(_, StringMatcher(matcher)), Value::InternedString(y)) => {
match matcher(y.to_string()) {
Some(matches) => {
let mut matches = matches
.iter()
.map(|(word, string)| {
(
word.clone(),
Value::AllocatedString(Rc::new(string.clone())),
)
})
.collect::<Vec<_>>();
self.locals.append(&mut matches);
Some(self)
}
None => None,
}
}
(WordPattern(w), val) => {
self.bind(w.to_string(), val);
Some(self)
}
(AsPattern(word, type_str), value) => {
let ludus_type = r#type(value);
let type_kw = Value::Keyword(type_str);
if type_kw == ludus_type {
self.bind(word.to_string(), value);
Some(self)
} else {
None
}
}
(TuplePattern(x), Value::Tuple(y)) => {
let has_splat = x.iter().any(|patt| matches!(patt, (Splattern(_), _)));
if x.len() > y.len() || (!has_splat && x.len() != y.len()) {
return None;
};
let to = self.locals.len();
for i in 0..x.len() {
if let Splattern(patt) = &x[i].0 {
let mut list = Vector::new();
for i in i..y.len() {
list.push_back(y[i].clone())
}
let list = Value::List(list);
self.match_pattern(&patt.0, &list);
} else if self.match_pattern(&x[i].0, &y[i]).is_none() {
self.pop_to(to);
return None;
}
}
Some(self)
}
(ListPattern(x), Value::List(y)) => {
let has_splat = x.iter().any(|patt| matches!(patt, (Splattern(_), _)));
if x.len() > y.len() || (!has_splat && x.len() != y.len()) {
return None;
};
let to = self.locals.len();
for (i, (patt, _)) in x.iter().enumerate() {
if let Splattern(patt) = &patt {
let list = Value::List(y.skip(i));
self.match_pattern(&patt.0, &list);
} else if self.match_pattern(patt, y.get(i).unwrap()).is_none() {
self.pop_to(to);
return None;
}
}
Some(self)
}
// TODO: optimize this on several levels
// - [ ] opportunistic mutation
// - [ ] get rid of all the pointer indirection in word splats
(DictPattern(x), Value::Dict(y)) => {
let has_splat = x.iter().any(|patt| matches!(patt, (Splattern(_), _)));
if x.len() > y.len() || (!has_splat && x.len() != y.len()) {
return None;
};
let to = self.locals.len();
let mut matched = vec![];
for (pattern, _) in x {
match pattern {
PairPattern(key, patt) => {
if let Some(val) = y.get(key) {
if self.match_pattern(&patt.0, val).is_none() {
self.pop_to(to);
return None;
} else {
matched.push(key);
}
} else {
return None;
};
}
Splattern(pattern) => match pattern.0 {
WordPattern(w) => {
// TODO: find a way to take ownership
// this will ALWAYS make structural changes, because of this clone
// we want opportunistic mutation if possible
let mut unmatched = y.clone();
for key in matched.iter() {
unmatched.remove(*key);
}
self.bind(w.to_string(), &Value::Dict(unmatched));
}
PlaceholderPattern => (),
_ => unreachable!(),
},
_ => unreachable!(),
}
}
Some(self)
}
_ => None,
}
}
pub fn match_clauses(
&mut self,
value: &Value<'src>,
clauses: &'src [Spanned<Ast>],
) -> LResult<'src> {
{
let parent = self.ast;
let to = self.locals.len();
let mut clauses = clauses.iter();
while let Some((Ast::MatchClause(patt, guard, body), _)) = clauses.next() {
if self.match_pattern(&patt.0, value).is_some() {
let pass_guard = match guard.as_ref() {
None => true,
Some((ast, _)) => {
self.ast = ast;
let guard_res = self.eval();
match &guard_res {
Err(_) => return guard_res,
Ok(val) => val.bool(),
}
}
};
if !pass_guard {
self.pop_to(to);
continue;
}
self.ast = &body.0;
let res = self.eval();
self.pop_to(to);
self.ast = parent;
return res;
}
}
Err(LErr::new("no match".to_string()))
}
}
pub fn apply(&mut self, callee: Value<'src>, caller: Value<'src>) -> LResult<'src> {
use Value::*;
match (callee, caller) {
(Keyword(kw), Dict(dict)) => {
if let Some(val) = dict.get(kw) {
Ok(val.clone())
} else {
Ok(Nil)
}
}
(Dict(dict), Keyword(kw)) => {
if let Some(val) = dict.get(kw) {
Ok(val.clone())
} else {
Ok(Nil)
}
}
(Fn(f), Tuple(args)) => {
let args = Tuple(args);
let to = self.locals.len();
let mut enclosing = f.enclosing.clone();
self.locals.append(&mut enclosing);
let result = self.match_clauses(&args, f.body);
self.locals.truncate(to);
result
}
// TODO: partially applied functions shnould work! In #15
(Fn(_f), Args(_args)) => todo!(),
(_, Keyword(_)) => Ok(Nil),
(_, Args(_)) => Err(LErr::new("you may only call a function".to_string())),
(Base(f), Tuple(args)) => match f {
BaseFn::Nullary(f) => {
let num_args = args.len();
if num_args != 0 {
Err(LErr::new(format!(
"wrong arity: expected 0 arguments, got {num_args}"
)))
} else {
Ok(f())
}
}
BaseFn::Unary(f) => {
let num_args = args.len();
if num_args != 1 {
Err(LErr::new(format!(
"wrong arity: expected 1 argument, got {num_args}"
)))
} else {
Ok(f(&args[0]))
}
}
BaseFn::Binary(r#fn) => {
let num_args = args.len();
if num_args != 2 {
Err(LErr::new(format!(
"wrong arity: expected 2 arguments, got {num_args}"
)))
} else {
Ok(r#fn(&args[0], &args[1]))
}
}
BaseFn::Ternary(f) => {
let num_args = args.len();
if num_args != 3 {
Err(LErr::new(format!(
"wrong arity: expected 3 arguments, got {num_args}"
)))
} else {
Ok(f(&args[0], &args[1], &args[2]))
}
}
},
_ => unreachable!(),
}
}
pub fn eval(&mut self) -> LResult<'src> {
use Ast::*;
let root = self.ast;
let result = match self.ast {
Nil => Ok(Value::Nil),
Boolean(b) => Ok(Value::Boolean(*b)),
Number(n) => Ok(Value::Number(*n)),
Keyword(k) => Ok(Value::Keyword(k)),
String(s) => Ok(Value::InternedString(s)),
Interpolated(parts) => {
let mut interpolated = std::string::String::new();
for part in parts {
match &part.0 {
StringPart::Data(s) => interpolated.push_str(s.as_str()),
StringPart::Word(w) => {
let val = self.resolve(w)?;
interpolated.push_str(val.interpolate().as_str())
}
StringPart::Inline(_) => unreachable!(),
}
}
Ok(Value::AllocatedString(Rc::new(interpolated)))
}
Block(exprs) => {
let parent = self.ast;
let to = self.locals.len();
let mut result = Value::Nil;
for (expr, _) in exprs {
self.ast = expr;
result = self.eval()?;
}
self.pop_to(to);
self.ast = parent;
Ok(result)
}
If(cond, if_true, if_false) => {
let parent = self.ast;
self.ast = &cond.0;
let truthy = self.eval()?.bool();
self.ast = if truthy { &if_true.0 } else { &if_false.0 };
let result = self.eval();
self.ast = parent;
result
}
List(members) => {
let parent = self.ast;
let mut vect = Vector::new();
for member in members {
self.ast = &member.0;
if let Ast::Splat(_) = self.ast {
let to_splat = self.eval()?;
match to_splat {
Value::List(list) => vect.append(list),
_ => {
return Err(LErr::new(
"only lists may be splatted into lists".to_string(),
))
}
}
} else {
vect.push_back(self.eval()?)
}
}
self.ast = parent;
Ok(Value::List(vect))
}
Tuple(members) => {
let parent = self.ast;
let mut vect = Vec::new();
for member in members {
self.ast = &member.0;
vect.push(self.eval()?);
}
self.ast = parent;
Ok(Value::Tuple(Rc::new(vect)))
}
Word(w) | Ast::Splat(w) => {
let val = self.resolve(&w.to_string())?;
Ok(val)
}
Let(patt, expr) => {
let parent = self.ast;
self.ast = &expr.0;
let val = self.eval()?;
let result = match self.match_pattern(&patt.0, &val) {
Some(_) => Ok(val),
None => Err(LErr::new("no match".to_string())),
};
self.ast = parent;
result
}
Placeholder => Ok(Value::Placeholder),
Arguments(a) => {
let parent = self.ast;
let mut args = vec![];
for (arg, _) in a.iter() {
self.ast = arg;
let arg = self.eval()?;
args.push(arg);
}
let result = if args.iter().any(|arg| matches!(arg, Value::Placeholder)) {
Ok(Value::Args(Rc::new(args)))
} else {
Ok(Value::Tuple(Rc::new(args)))
};
self.ast = parent;
result
}
Dict(terms) => {
let parent = self.ast;
let mut dict = HashMap::new();
for term in terms {
let (term, _) = term;
match term {
Ast::Pair(key, value) => {
self.ast = &value.0;
let value = self.eval()?;
dict.insert(*key, value);
}
Ast::Splat(_) => {
self.ast = term;
let resolved = self.eval()?;
let Value::Dict(to_splat) = resolved else {
return Err(LErr::new(
"cannot splat non-dict into dict".to_string(),
));
};
dict = to_splat.union(dict);
}
_ => unreachable!(),
}
}
self.ast = parent;
Ok(Value::Dict(dict))
}
LBox(name, expr) => {
let parent = self.ast;
self.ast = &expr.0;
let val = self.eval()?;
let boxed = Value::Box(name, Rc::new(RefCell::new(val)));
self.bind(name.to_string(), &boxed);
self.ast = parent;
Ok(boxed)
}
Synthetic(root, first, rest) => {
let parent = self.ast;
self.ast = &root.0;
let root = self.eval()?;
self.ast = &first.0;
let first = self.eval()?;
let mut curr = self.apply(root, first)?;
for term in rest.iter() {
self.ast = &term.0;
let next = self.eval()?;
curr = self.apply(curr, next)?;
}
self.ast = parent;
Ok(curr)
}
When(clauses) => {
let parent = self.ast;
for clause in clauses.iter() {
let WhenClause(cond, body) = &clause.0 else {
unreachable!()
};
self.ast = &cond.0;
if self.eval()?.bool() {
self.ast = &body.0;
let result = self.eval();
self.ast = parent;
return result;
};
}
Err(LErr::new("no match".to_string()))
}
Match(value, clauses) => {
let parent = self.ast;
self.ast = &value.0;
let value = self.eval()?;
let result = self.match_clauses(&value, clauses);
self.ast = parent;
result
}
Fn(name, clauses, doc) => {
let doc = doc.map(|s| s.to_string());
let ptr: *const Ast = root;
// dbg!(&root);
// dbg!(&ptr);
// dbg!(&self.fn_info);
let info = self.fn_info.get(&ptr).unwrap();
let FnInfo::Defined(_, _, enclosing) = info else {
unreachable!()
};
let enclosing = enclosing
.iter()
.filter(|binding| binding != name)
.map(|binding| (binding.clone(), self.resolve(binding).unwrap().clone()))
.collect();
let the_fn = Value::Fn::<'src>(Rc::new(crate::value::Fn::<'src> {
name: name.to_string(),
body: clauses,
doc,
enclosing,
}));
self.bind(name.to_string(), &the_fn);
Ok(the_fn)
}
FnDeclaration(_name) => Ok(Value::Nil),
Panic(msg) => {
self.ast = &msg.0;
let msg = self.eval()?;
Err(LErr::new(format!("{msg}")))
}
Repeat(times, body) => {
let parent = self.ast;
self.ast = &times.0;
let times_num = match self.eval() {
Ok(Value::Number(n)) => n as usize,
_ => return Err(LErr::new("`repeat` may only take numbers".to_string())),
};
self.ast = &body.0;
for _ in 0..times_num {
self.eval()?;
}
self.ast = parent;
Ok(Value::Nil)
}
Do(terms) => {
let parent = self.ast;
self.ast = &terms[0].0;
let mut result = self.eval()?;
for (term, _) in terms.iter().skip(1) {
self.ast = term;
let next = self.eval()?;
let arg = Value::Tuple(Rc::new(vec![result]));
result = self.apply(next, arg)?;
}
self.ast = parent;
Ok(result)
}
Loop(init, clauses) => {
let parent = self.ast;
self.ast = &init.0;
let mut args = self.eval()?;
loop {
let result = self.match_clauses(&args, clauses)?;
if let Value::Recur(recur_args) = result {
args = Value::Tuple(Rc::new(recur_args));
} else {
self.ast = parent;
return Ok(result);
}
}
}
Recur(args) => {
let parent = self.ast;
let mut vect = Vec::new();
for arg in args {
self.ast = &arg.0;
vect.push(self.eval()?);
}
self.ast = parent;
Ok(Value::Recur(vect))
}
_ => unreachable!(),
};
self.ast = root;
result
}
}