feat: error handling
This commit is contained in:
@@ -14,7 +14,7 @@ use hashbrown::HashMap;
|
||||
use nixjit_error::{Error, Result};
|
||||
use nixjit_ir::{self as ir, ArgIdx, ExprId, PrimOpId};
|
||||
use nixjit_lir as lir;
|
||||
use nixjit_value::{Const, Symbol, format_symbol};
|
||||
use nixjit_value::{Const, format_symbol};
|
||||
|
||||
pub use crate::value::*;
|
||||
|
||||
@@ -39,6 +39,9 @@ pub trait EvalContext: Sized {
|
||||
f: impl FnOnce(&mut Self) -> T,
|
||||
) -> (Vec<Value>, T);
|
||||
|
||||
/// Looks up a stack slot on the current stack frame.
|
||||
fn lookup_stack<'a>(&'a self, idx: usize) -> &'a Value;
|
||||
|
||||
/// Looks up an identifier in the current `with` scope chain.
|
||||
fn lookup_with<'a>(&'a self, ident: &str) -> Option<&'a Value>;
|
||||
|
||||
@@ -107,7 +110,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::AttrSet {
|
||||
);
|
||||
for (k, v) in self.dyns.iter() {
|
||||
let mut k = k.eval(ctx)?;
|
||||
k.coerce_to_string();
|
||||
k.coerce_to_string()?;
|
||||
let v_eval_result = v.eval(ctx)?;
|
||||
attrs.push_attr(k.unwrap_string(), v_eval_result)?;
|
||||
}
|
||||
@@ -135,14 +138,10 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::HasAttr {
|
||||
use ir::Attr::*;
|
||||
let mut val = self.lhs.eval(ctx)?;
|
||||
val.has_attr(self.rhs.iter().map(|attr| {
|
||||
Ok(match attr {
|
||||
Str(ident) => ident.clone(),
|
||||
Dynamic(expr) => {
|
||||
let mut val = expr.eval(ctx)?;
|
||||
val.coerce_to_string();
|
||||
val.unwrap_string()
|
||||
}
|
||||
})
|
||||
match attr {
|
||||
Str(ident) => Ok(Value::String(ident.clone())),
|
||||
Dynamic(expr) => expr.eval(ctx)
|
||||
}
|
||||
}))?;
|
||||
Ok(val)
|
||||
}
|
||||
@@ -153,42 +152,47 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::BinOp {
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
use ir::BinOpKind::*;
|
||||
let mut lhs = self.lhs.eval(ctx)?;
|
||||
if matches!((&self.kind, &lhs), (And, Value::Bool(false))) {
|
||||
return Ok(Value::Bool(false));
|
||||
} else if matches!((&self.kind, &lhs), (Or, Value::Bool(true))) {
|
||||
return Ok(Value::Bool(true))
|
||||
}
|
||||
let mut rhs = self.rhs.eval(ctx)?;
|
||||
match self.kind {
|
||||
Add => lhs.add(rhs)?,
|
||||
Sub => {
|
||||
rhs.neg();
|
||||
rhs.neg()?;
|
||||
lhs.add(rhs)?;
|
||||
}
|
||||
Mul => lhs.mul(rhs),
|
||||
Mul => lhs.mul(rhs)?,
|
||||
Div => lhs.div(rhs)?,
|
||||
Eq => Value::eq(&mut lhs, &rhs),
|
||||
Eq => Value::eq(&mut lhs, rhs),
|
||||
Neq => {
|
||||
Value::eq(&mut lhs, &rhs);
|
||||
lhs.not();
|
||||
Value::eq(&mut lhs, rhs);
|
||||
let _ = lhs.not();
|
||||
}
|
||||
Lt => lhs.lt(rhs),
|
||||
Lt => lhs.lt(rhs)?,
|
||||
Gt => {
|
||||
rhs.lt(lhs);
|
||||
rhs.lt(lhs)?;
|
||||
lhs = rhs;
|
||||
}
|
||||
Leq => {
|
||||
rhs.lt(lhs);
|
||||
rhs.not();
|
||||
rhs.lt(lhs)?;
|
||||
let _ = rhs.not();
|
||||
lhs = rhs;
|
||||
}
|
||||
Geq => {
|
||||
lhs.lt(rhs);
|
||||
lhs.not();
|
||||
lhs.lt(rhs)?;
|
||||
let _ = lhs.not()?;
|
||||
}
|
||||
And => lhs.and(rhs),
|
||||
Or => lhs.or(rhs),
|
||||
And => lhs.and(rhs)?,
|
||||
Or => lhs.or(rhs)?,
|
||||
Impl => {
|
||||
lhs.not();
|
||||
lhs.or(rhs);
|
||||
let _ = lhs.not();
|
||||
lhs.or(rhs)?;
|
||||
}
|
||||
Con => lhs.concat(rhs),
|
||||
Upd => lhs.update(rhs),
|
||||
Con => lhs.concat(rhs)?,
|
||||
Upd => lhs.update(rhs)?,
|
||||
PipeL => lhs.call(core::iter::once(Ok(rhs)), ctx)?,
|
||||
PipeR => {
|
||||
rhs.call(core::iter::once(Ok(lhs)), ctx)?;
|
||||
@@ -206,10 +210,10 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::UnOp {
|
||||
let mut rhs = self.rhs.eval(ctx)?;
|
||||
match self.kind {
|
||||
Neg => {
|
||||
rhs.neg();
|
||||
rhs.neg()?;
|
||||
}
|
||||
Not => {
|
||||
rhs.not();
|
||||
rhs.not()?;
|
||||
}
|
||||
};
|
||||
Ok(rhs)
|
||||
@@ -230,7 +234,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Select {
|
||||
Str(ident) => ident.clone(),
|
||||
Dynamic(expr) => {
|
||||
let mut val = expr.eval(ctx)?;
|
||||
val.coerce_to_string();
|
||||
val.coerce_to_string()?;
|
||||
val.unwrap_string()
|
||||
}
|
||||
})
|
||||
@@ -243,7 +247,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Select {
|
||||
Str(ident) => ident.clone(),
|
||||
Dynamic(expr) => {
|
||||
let mut val = expr.eval(ctx)?;
|
||||
val.coerce_to_string();
|
||||
val.coerce_to_string()?;
|
||||
val.unwrap_string()
|
||||
}
|
||||
})
|
||||
@@ -314,7 +318,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Assert {
|
||||
if cond {
|
||||
self.expr.eval(ctx)
|
||||
} else {
|
||||
Ok(Value::Catchable("assertion failed".to_string()))
|
||||
Err(Error::Catchable("assertion failed".into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -323,22 +327,11 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::ConcatStrings {
|
||||
/// Evaluates a `ConcatStrings` by evaluating each part, coercing it to a string,
|
||||
/// and then concatenating the results.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
let mut parts = self
|
||||
.parts
|
||||
.iter()
|
||||
.map(|part| {
|
||||
let mut part = part.eval(ctx)?;
|
||||
part.coerce_to_string();
|
||||
Ok(part)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?
|
||||
.into_iter();
|
||||
let init = parts.next().unwrap();
|
||||
let result = parts.fold(init, |mut a, b| {
|
||||
a.concat_string(b);
|
||||
a
|
||||
});
|
||||
Ok(result)
|
||||
let mut buf = String::new();
|
||||
for part in self.parts.iter() {
|
||||
buf.push_str(part.eval(ctx)?.coerce_to_string()?.as_ref().unwrap_string());
|
||||
}
|
||||
Ok(Value::String(buf))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -376,7 +369,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Var {
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Path {
|
||||
/// Evaluates a `Path`. (Currently a TODO).
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
fn eval(&self, _ctx: &mut Ctx) -> Result<Value> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::rc::Rc;
|
||||
|
||||
use derive_more::Constructor;
|
||||
use hashbrown::hash_map::Entry;
|
||||
use hashbrown::{HashMap, HashSet};
|
||||
use hashbrown::HashMap;
|
||||
use itertools::Itertools;
|
||||
|
||||
use nixjit_error::{Error, Result};
|
||||
@@ -66,12 +66,7 @@ impl AttrSet {
|
||||
self.data.insert(sym, val);
|
||||
}
|
||||
|
||||
/// Inserts an attribute.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This method currently uses `todo!()` and will panic if the attribute
|
||||
/// already exists, indicating that duplicate attribute handling is not yet implemented.
|
||||
/// Inserts an attribute, returns an error if the attribute is already defined.
|
||||
pub fn push_attr(&mut self, sym: String, val: Value) -> Result<()> {
|
||||
match self.data.entry(sym) {
|
||||
Entry::Occupied(occupied) => Err(Error::EvalError(format!(
|
||||
@@ -114,17 +109,22 @@ impl AttrSet {
|
||||
/// Checks if an attribute path exists within the set.
|
||||
pub fn has_attr(
|
||||
&self,
|
||||
mut path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||
) -> Result<bool> {
|
||||
mut path: impl DoubleEndedIterator<Item = Result<Value>>,
|
||||
) -> Result<Value> {
|
||||
let mut data = &self.data;
|
||||
let last = path.nth_back(0).unwrap();
|
||||
for item in path {
|
||||
let Some(Value::AttrSet(attrs)) = data.get(&item?) else {
|
||||
return Ok(false);
|
||||
let Some(Value::AttrSet(attrs)) =
|
||||
data.get(item.unwrap().coerce_to_string()?.as_ref().unwrap_string())
|
||||
else {
|
||||
return Ok(Value::Bool(false));
|
||||
};
|
||||
data = attrs.as_inner();
|
||||
}
|
||||
Ok(data.get(&last?).is_some())
|
||||
Ok(Value::Bool(
|
||||
data.get(last.unwrap().coerce_to_string()?.as_ref().unwrap_string())
|
||||
.is_some(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Merges another `AttrSet` into this one, with attributes from `other`
|
||||
@@ -169,11 +169,11 @@ impl AttrSet {
|
||||
}
|
||||
|
||||
/// Converts the `AttrSet` to its public-facing representation.
|
||||
pub fn to_public(&self, seen: &mut HashSet<Value>) -> p::Value {
|
||||
pub fn to_public(self) -> p::Value {
|
||||
p::Value::AttrSet(p::AttrSet::new(
|
||||
self.data
|
||||
.iter()
|
||||
.map(|(sym, value)| (sym.as_str().into(), value.to_public(seen)))
|
||||
.into_iter()
|
||||
.map(|(sym, value)| (sym.into(), value.to_public()))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -64,6 +64,6 @@ impl FuncApp {
|
||||
val = ret?;
|
||||
}
|
||||
}
|
||||
val.ok()
|
||||
Ok(val)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,11 +77,11 @@ impl List {
|
||||
}
|
||||
|
||||
/// Converts the `List` to its public-facing representation.
|
||||
pub fn to_public(&self, seen: &mut HashSet<Value>) -> PubValue {
|
||||
pub fn to_public(&self) -> PubValue {
|
||||
PubValue::List(PubList::new(
|
||||
self.data
|
||||
.iter()
|
||||
.map(|value| value.clone().to_public(seen))
|
||||
.map(|value| value.clone().to_public())
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -11,14 +11,11 @@
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::hash::Hash;
|
||||
use std::process::abort;
|
||||
use std::rc::Rc;
|
||||
|
||||
use derive_more::TryUnwrap;
|
||||
use derive_more::{IsVariant, Unwrap};
|
||||
use hashbrown::HashSet;
|
||||
use nixjit_ir::{ExprId, PrimOp};
|
||||
use replace_with::replace_with_and_return;
|
||||
|
||||
use nixjit_error::{Error, Result};
|
||||
use nixjit_value::Const;
|
||||
@@ -53,7 +50,6 @@ pub enum Value {
|
||||
Thunk(ExprId),
|
||||
AttrSet(Rc<AttrSet>),
|
||||
List(Rc<List>),
|
||||
Catchable(String),
|
||||
PrimOp(PrimOp),
|
||||
PrimOpApp(Rc<PrimOpApp>),
|
||||
Func(ExprId),
|
||||
@@ -71,7 +67,6 @@ impl Debug for Value {
|
||||
String(x) => write!(f, "{x}"),
|
||||
AttrSet(x) => write!(f, "{x:?}"),
|
||||
List(x) => write!(f, "{x:?}"),
|
||||
Catchable(x) => write!(f, "{x}"),
|
||||
Thunk(thunk) => write!(f, "<THUNK {thunk:?}>"),
|
||||
Func(func) => write!(f, "<LAMBDA {func:?}>"),
|
||||
FuncApp(func) => write!(f, "<LAMBDA-APP {:?}>", func.body),
|
||||
@@ -151,7 +146,6 @@ pub enum ValueAsRef<'v> {
|
||||
Thunk(&'v ExprId),
|
||||
AttrSet(&'v AttrSet),
|
||||
List(&'v List),
|
||||
Catchable(&'v str),
|
||||
PrimOp(&'v PrimOp),
|
||||
PartialPrimOp(&'v PrimOpApp),
|
||||
Func(&'v ExprId),
|
||||
@@ -172,7 +166,6 @@ impl Value {
|
||||
Thunk(x) => R::Thunk(x),
|
||||
AttrSet(x) => R::AttrSet(x),
|
||||
List(x) => R::List(x),
|
||||
Catchable(x) => R::Catchable(x),
|
||||
PrimOp(x) => R::PrimOp(x),
|
||||
PrimOpApp(x) => R::PartialPrimOp(x),
|
||||
Func(x) => R::Func(x),
|
||||
@@ -181,11 +174,6 @@ impl Value {
|
||||
}
|
||||
}
|
||||
impl Value {
|
||||
/// Wraps the `Value` in a `Result::Ok`.
|
||||
pub fn ok(self) -> Result<Self> {
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Returns the name of the value's type.
|
||||
pub fn typename(&self) -> &'static str {
|
||||
use Value::*;
|
||||
@@ -198,7 +186,6 @@ impl Value {
|
||||
Thunk(_) => "thunk",
|
||||
AttrSet(_) => "set",
|
||||
List(_) => "list",
|
||||
Catchable(_) => unreachable!(),
|
||||
PrimOp(_) => "lambda",
|
||||
PrimOpApp(_) => "lambda",
|
||||
Func(_) => "lambda",
|
||||
@@ -206,15 +193,6 @@ impl Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if the value is a callable entity (a function or primop).
|
||||
pub fn callable(&self) -> bool {
|
||||
match self {
|
||||
Value::PrimOp(_) | Value::PrimOpApp(_) | Value::Func(_) => true,
|
||||
Value::AttrSet(_) => todo!(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs a function call on the `Value`.
|
||||
///
|
||||
/// This method handles calling functions, primops, and their partially
|
||||
@@ -227,20 +205,22 @@ impl Value {
|
||||
) -> Result<()> {
|
||||
use Value::*;
|
||||
*self = match self {
|
||||
&mut PrimOp(func) => {
|
||||
if iter.len() > func.arity {
|
||||
todo!()
|
||||
}
|
||||
if func.arity > iter.len() {
|
||||
Value::PrimOpApp(Rc::new(self::PrimOpApp::new(
|
||||
func.name,
|
||||
func.arity - iter.len(),
|
||||
func.id,
|
||||
&mut PrimOp(primop) => {
|
||||
if iter.len() > primop.arity {
|
||||
let mut args = iter.collect::<Result<Vec<_>>>()?;
|
||||
let leftover = args.split_off(primop.arity);
|
||||
let mut ret = ctx.call_primop(primop.id, args)?;
|
||||
ret.call(leftover.into_iter().map(Ok), ctx)?;
|
||||
Ok(ret)
|
||||
} else if primop.arity > iter.len() {
|
||||
Ok(Value::PrimOpApp(Rc::new(self::PrimOpApp::new(
|
||||
primop.name,
|
||||
primop.arity - iter.len(),
|
||||
primop.id,
|
||||
iter.collect::<Result<_>>()?,
|
||||
)))
|
||||
.ok()
|
||||
))))
|
||||
} else {
|
||||
ctx.call_primop(func.id, iter.collect::<Result<_>>()?)
|
||||
ctx.call_primop(primop.id, iter.collect::<Result<_>>()?)
|
||||
}
|
||||
}
|
||||
&mut Func(expr) => {
|
||||
@@ -271,11 +251,10 @@ impl Value {
|
||||
val = ret?;
|
||||
}
|
||||
}
|
||||
val.ok()
|
||||
Ok(val)
|
||||
}
|
||||
PrimOpApp(func) => func.call(iter.collect::<Result<_>>()?, ctx),
|
||||
FuncApp(func) => func.call(iter, ctx),
|
||||
Catchable(_) => return Ok(()),
|
||||
_ => Err(Error::EvalError(
|
||||
"attempt to call something which is not a function but ...".to_string(),
|
||||
)),
|
||||
@@ -283,45 +262,47 @@ impl Value {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn not(&mut self) {
|
||||
pub fn not(&mut self) -> Result<()> {
|
||||
use Value::*;
|
||||
*self = match &*self {
|
||||
Bool(bool) => Bool(!bool),
|
||||
Value::Catchable(_) => return,
|
||||
_ => todo!(),
|
||||
match &*self {
|
||||
Bool(bool) => {
|
||||
*self = Bool(!bool);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(Error::EvalError(format!("expected a boolean but found {}", self.typename()))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn and(&mut self, other: Self) {
|
||||
pub fn and(&mut self, other: Self) -> Result<()> {
|
||||
use Value::*;
|
||||
*self = match (&*self, other) {
|
||||
(Bool(a), Bool(b)) => Bool(*a && b),
|
||||
(Value::Catchable(_), _) => return,
|
||||
(_, x @ Value::Catchable(_)) => x,
|
||||
_ => todo!(),
|
||||
match (&*self, other) {
|
||||
(&Bool(a), Bool(b)) => {
|
||||
*self = Bool(a && b);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(Error::EvalError(format!("expected a boolean but found {}", self.typename()))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn or(&mut self, other: Self) {
|
||||
pub fn or(&mut self, other: Self) -> Result<()> {
|
||||
use Value::*;
|
||||
*self = match (&*self, other) {
|
||||
(Bool(a), Bool(b)) => Bool(*a || b),
|
||||
(Value::Catchable(_), _) => return,
|
||||
(_, x @ Value::Catchable(_)) => x,
|
||||
_ => todo!(),
|
||||
match (&*self, other) {
|
||||
(&Bool(a), Bool(b)) => {
|
||||
*self = Bool(a || b);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(Error::EvalError(format!("expected a boolean but found {}", self.typename()))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eq(&mut self, other: &Self) {
|
||||
pub fn eq(&mut self, other: Self) {
|
||||
use Value::Bool;
|
||||
*self = match (&*self, other) {
|
||||
(Value::Catchable(_), _) => return,
|
||||
(_, x @ Value::Catchable(_)) => x.clone(),
|
||||
(s, other) => Bool(s.eq_impl(other)),
|
||||
(s, other) => Bool(s.eq_impl(&other)),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn lt(&mut self, other: Self) {
|
||||
pub fn lt(&mut self, other: Self) -> Result<()> {
|
||||
use Value::*;
|
||||
*self = Bool(match (&*self, other) {
|
||||
(Int(a), Int(b)) => *a < b,
|
||||
@@ -329,60 +310,47 @@ impl Value {
|
||||
(Float(a), Int(b)) => *a < b as f64,
|
||||
(Float(a), Float(b)) => *a < b,
|
||||
(String(a), String(b)) => a.as_str() < b.as_str(),
|
||||
(Value::Catchable(_), _) => return,
|
||||
(_, x @ Value::Catchable(_)) => {
|
||||
*self = x;
|
||||
return;
|
||||
}
|
||||
_ => todo!(),
|
||||
})
|
||||
(a, b) => return Err(Error::EvalError(format!("cannot compare {} with {}", a.typename(), b.typename()))),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn neg(&mut self) {
|
||||
pub fn neg(&mut self) -> Result<()> {
|
||||
use Value::*;
|
||||
*self = match &*self {
|
||||
Int(int) => Int(-int),
|
||||
Float(float) => Float(-float),
|
||||
Value::Catchable(_) => return,
|
||||
_ => todo!(),
|
||||
}
|
||||
_ => return Err(Error::EvalError(format!("expected an integer but found {}", self.typename())))
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn add(&mut self, other: Self) -> Result<()> {
|
||||
pub fn add(mut self: &mut Self, other: Self) -> Result<()> {
|
||||
use Value::*;
|
||||
replace_with_and_return(
|
||||
self,
|
||||
|| abort(),
|
||||
|a| {
|
||||
let val = match (a, other) {
|
||||
(Int(a), Int(b)) => Int(a + b),
|
||||
(Int(a), Float(b)) => Float(a as f64 + b),
|
||||
(Float(a), Int(b)) => Float(a + b as f64),
|
||||
(Float(a), Float(b)) => Float(a + b),
|
||||
(String(mut a), String(b)) => {
|
||||
a.push_str(&b);
|
||||
String(a)
|
||||
}
|
||||
(a @ Value::Catchable(_), _) => a,
|
||||
(_, x @ Value::Catchable(_)) => x,
|
||||
_ => return (Err(Error::EvalError(format!(""))), Value::Null),
|
||||
};
|
||||
(Ok(()), val)
|
||||
},
|
||||
)
|
||||
if let (String(a), String(b)) = (&mut self, &other) {
|
||||
a.push_str(b.as_str());
|
||||
return Ok(());
|
||||
}
|
||||
*self = match (&mut self, other) {
|
||||
(Int(a), Int(b)) => Int(*a + b),
|
||||
(&mut Int(a), Float(b)) => Float(*a as f64 + b),
|
||||
(&mut Float(a), Int(b)) => Float(*a + b as f64),
|
||||
(&mut Float(a), Float(b)) => Float(*a + b),
|
||||
(a, b) => return Err(Error::EvalError(format!("cannot add {} to {}", a.typename(), b.typename())))
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn mul(&mut self, other: Self) {
|
||||
pub fn mul(&mut self, other: Self) -> Result<()> {
|
||||
use Value::*;
|
||||
*self = match (&*self, other) {
|
||||
(Int(a), Int(b)) => Int(a * b),
|
||||
(Int(a), Float(b)) => Float(*a as f64 * b),
|
||||
(Float(a), Int(b)) => Float(a * b as f64),
|
||||
(Float(a), Float(b)) => Float(a * b),
|
||||
(Value::Catchable(_), _) => return,
|
||||
(_, x @ Value::Catchable(_)) => x,
|
||||
_ => todo!(),
|
||||
}
|
||||
(a, b) => return Err(Error::EvalError(format!("cannot multiply {} with {}", a.typename(), b.typename())))
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn div(&mut self, other: Self) -> Result<()> {
|
||||
@@ -396,108 +364,58 @@ impl Value {
|
||||
(Int(a), Float(b)) => Float(*a as f64 / b),
|
||||
(Float(a), Int(b)) => Float(a / b as f64),
|
||||
(Float(a), Float(b)) => Float(a / b),
|
||||
(Catchable(_), _) => return Ok(()),
|
||||
(_, x @ Catchable(_)) => x,
|
||||
_ => todo!(),
|
||||
(a, b) => return Err(Error::EvalError(format!("cannot divide {} with {}", a.typename(), b.typename())))
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn concat_string(&mut self, mut other: Self) -> &mut Self {
|
||||
pub fn concat(mut self: &mut Self, other: Self) -> Result<()> {
|
||||
use Value::*;
|
||||
match (self.coerce_to_string(), other.coerce_to_string()) {
|
||||
(String(a), String(b)) => {
|
||||
a.push_str(b.as_str());
|
||||
}
|
||||
(_, Catchable(_)) => *self = other,
|
||||
(Catchable(_), _) => (),
|
||||
_ => todo!(),
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn push(&mut self, elem: Self) -> &mut Self {
|
||||
use Value::*;
|
||||
if let List(list) = self {
|
||||
Rc::make_mut(list).push(elem);
|
||||
} else if let Catchable(_) = self {
|
||||
} else if let Catchable(_) = elem {
|
||||
*self = elem;
|
||||
} else {
|
||||
todo!()
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn concat(&mut self, other: Self) {
|
||||
use Value::*;
|
||||
if let x @ Catchable(_) = other {
|
||||
*self = x;
|
||||
return;
|
||||
}
|
||||
match (self, other) {
|
||||
match (&mut self, other) {
|
||||
(List(a), List(b)) => {
|
||||
Rc::make_mut(a).concat(&b);
|
||||
Ok(())
|
||||
}
|
||||
(Catchable(_), _) => (),
|
||||
_ => todo!(),
|
||||
}
|
||||
(List(_), b) => Err(Error::EvalError(format!("expected a list but found {}", b.typename()))),
|
||||
(a, _) => Err(Error::EvalError(format!("expected a list but found {}", a.typename()))), }
|
||||
}
|
||||
|
||||
pub fn push_attr(&mut self, sym: String, val: Self) -> &mut Self {
|
||||
pub fn update(mut self: &mut Self, other: Self) -> Result<()> {
|
||||
use Value::*;
|
||||
if let AttrSet(attrs) = self {
|
||||
Rc::make_mut(attrs).push_attr(sym, val);
|
||||
} else if let Catchable(_) = self {
|
||||
} else if let Catchable(_) = val {
|
||||
*self = val
|
||||
} else {
|
||||
todo!()
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn update(&mut self, other: Self) {
|
||||
use Value::*;
|
||||
if let x @ Catchable(_) = other {
|
||||
*self = x;
|
||||
return;
|
||||
}
|
||||
match (self, other) {
|
||||
match (&mut self, other) {
|
||||
(AttrSet(a), AttrSet(b)) => {
|
||||
Rc::make_mut(a).update(&b);
|
||||
Ok(())
|
||||
}
|
||||
(Catchable(_), _) => (),
|
||||
_ => todo!(),
|
||||
(AttrSet(_), other) => Err(Error::EvalError(format!("expected a set but found {}", other.typename()))),
|
||||
_ => Err(Error::EvalError(format!("expected a set but found {}", self.typename()))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn select(
|
||||
&mut self,
|
||||
path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||
) -> Result<&mut Self> {
|
||||
) -> Result<()> {
|
||||
use Value::*;
|
||||
let val = match self {
|
||||
AttrSet(attrs) => attrs.select(path),
|
||||
Catchable(_) => return Ok(self),
|
||||
_ => Err(Error::EvalError(format!(
|
||||
"can not select from {:?}",
|
||||
self.typename()
|
||||
))),
|
||||
}?;
|
||||
*self = val;
|
||||
Ok(self)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn select_with_default(
|
||||
&mut self,
|
||||
path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||
default: Self,
|
||||
) -> Result<&mut Self> {
|
||||
) -> Result<()> {
|
||||
use Value::*;
|
||||
let val = match self {
|
||||
AttrSet(attrs) => attrs.select(path).unwrap_or(default),
|
||||
Catchable(_) => return Ok(self),
|
||||
_ => {
|
||||
return Err(Error::EvalError(format!(
|
||||
"can not select from {:?}",
|
||||
@@ -506,18 +424,17 @@ impl Value {
|
||||
}
|
||||
};
|
||||
*self = val;
|
||||
Ok(self)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn has_attr(
|
||||
&mut self,
|
||||
path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||
path: impl DoubleEndedIterator<Item = Result<Value>>,
|
||||
) -> Result<()> {
|
||||
use Value::*;
|
||||
if let AttrSet(attrs) = self {
|
||||
let val = Bool(attrs.has_attr(path)?);
|
||||
let val = attrs.has_attr(path)?;
|
||||
*self = val;
|
||||
} else if let Catchable(_) = self {
|
||||
} else {
|
||||
*self = Bool(false);
|
||||
}
|
||||
@@ -527,11 +444,10 @@ impl Value {
|
||||
pub fn coerce_to_string(&mut self) -> Result<&mut Self> {
|
||||
use Value::*;
|
||||
if let String(_) = self {
|
||||
} else if let Catchable(_) = self {
|
||||
Ok(self)
|
||||
} else {
|
||||
todo!()
|
||||
Err(Error::EvalError(format!("cannot coerce {} to string", self.typename())))
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Converts the internal `Value` to its public-facing, serializable
|
||||
@@ -540,25 +456,19 @@ impl Value {
|
||||
/// The `seen` set is used to detect and handle cycles in data structures
|
||||
/// like attribute sets and lists, replacing subsequent encounters with
|
||||
/// `PubValue::Repeated`.
|
||||
pub fn to_public(&self, seen: &mut HashSet<Value>) -> PubValue {
|
||||
pub fn to_public(self) -> PubValue {
|
||||
use Value::*;
|
||||
if seen.contains(self) {
|
||||
return PubValue::Repeated;
|
||||
}
|
||||
match self {
|
||||
AttrSet(attrs) => {
|
||||
seen.insert(self.clone());
|
||||
attrs.to_public(seen)
|
||||
Rc::unwrap_or_clone(attrs).to_public()
|
||||
}
|
||||
List(list) => {
|
||||
seen.insert(self.clone());
|
||||
list.to_public(seen)
|
||||
Rc::unwrap_or_clone(list.clone()).to_public()
|
||||
}
|
||||
Catchable(catchable) => PubValue::Catchable(catchable.clone().into()),
|
||||
Int(x) => PubValue::Const(Const::Int(*x)),
|
||||
Float(x) => PubValue::Const(Const::Float(*x)),
|
||||
Bool(x) => PubValue::Const(Const::Bool(*x)),
|
||||
String(x) => PubValue::String(x.clone()),
|
||||
Int(x) => PubValue::Const(Const::Int(x)),
|
||||
Float(x) => PubValue::Const(Const::Float(x)),
|
||||
Bool(x) => PubValue::Const(Const::Bool(x)),
|
||||
String(x) => PubValue::String(x),
|
||||
Null => PubValue::Const(Const::Null),
|
||||
Thunk(_) => PubValue::Thunk,
|
||||
PrimOp(primop) => PubValue::PrimOp(primop.name),
|
||||
|
||||
@@ -34,24 +34,25 @@ impl PrimOpApp {
|
||||
/// arguments.
|
||||
pub fn call(
|
||||
self: &mut Rc<Self>,
|
||||
args: Vec<Value>,
|
||||
mut args: Vec<Value>,
|
||||
ctx: &mut impl EvalContext,
|
||||
) -> Result<Value> {
|
||||
if self.arity < args.len() {
|
||||
todo!()
|
||||
}
|
||||
let Some(ret) = ({
|
||||
let self_mut = Rc::make_mut(self);
|
||||
self_mut.arity -= args.len();
|
||||
self_mut.args.extend(args);
|
||||
if self_mut.arity == 0 {
|
||||
Some(ctx.call_primop(self_mut.id, std::mem::take(&mut self_mut.args)))
|
||||
} else {
|
||||
None
|
||||
let leftover = args.split_off(self.arity);
|
||||
for arg in self.args.iter().rev().cloned() {
|
||||
args.insert(0, arg);
|
||||
}
|
||||
}) else {
|
||||
return Value::PrimOpApp(self.clone()).ok();
|
||||
};
|
||||
ret
|
||||
let mut ret = ctx.call_primop(self.id, args)?;
|
||||
ret.call(leftover.into_iter().map(Ok), ctx)?;
|
||||
return Ok(ret);
|
||||
}
|
||||
let self_mut = Rc::make_mut(self);
|
||||
self_mut.arity -= args.len();
|
||||
self_mut.args.extend(args);
|
||||
if self_mut.arity == 0 {
|
||||
ctx.call_primop(self_mut.id, std::mem::take(&mut self_mut.args))
|
||||
} else {
|
||||
Ok(Value::PrimOpApp(self.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user