feat: error handling
This commit is contained in:
@@ -21,8 +21,6 @@ pub mod builtins {
|
||||
(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),
|
||||
(a @ Value::Catchable(_), _) => a,
|
||||
(_, b @ Value::Catchable(_)) => b,
|
||||
_ => return Err(Error::EvalError(format!(""))),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -205,7 +205,7 @@ impl Context {
|
||||
}
|
||||
let root = root.tree().expr().unwrap().downgrade(&mut self)?;
|
||||
self.resolve(root)?;
|
||||
Ok(EvalContext::eval(&mut self, root)?.to_public(&mut HashSet::new()))
|
||||
Ok(EvalContext::eval(&mut self, root)?.to_public())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,6 +361,10 @@ impl EvalContext for Context {
|
||||
self.stack.pop().unwrap()
|
||||
}
|
||||
|
||||
fn lookup_stack<'a>(&'a self, offoset: usize) -> &'a Value {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn lookup_with<'a>(&'a self, ident: &str) -> Option<&'a nixjit_eval::Value> {
|
||||
for scope in self.with_scopes.iter().rev() {
|
||||
if let Some(val) = scope.get(ident) {
|
||||
@@ -406,15 +410,6 @@ impl EvalContext for Context {
|
||||
}
|
||||
|
||||
impl JITContext for Context {
|
||||
fn lookup_arg(&self, offset: usize) -> &nixjit_eval::Value {
|
||||
let values = self.stack.last().unwrap();
|
||||
&values[values.len() - offset - 1]
|
||||
}
|
||||
|
||||
fn lookup_stack(&self, offset: usize) -> &nixjit_eval::Value {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn enter_with(&mut self, namespace: std::rc::Rc<HashMap<String, nixjit_eval::Value>>) {
|
||||
self.with_scopes.push(namespace);
|
||||
}
|
||||
|
||||
@@ -32,11 +32,17 @@ pub enum Error {
|
||||
ResolutionError(String),
|
||||
|
||||
/// An error occurred during the final evaluation of the LIR. This covers
|
||||
/// all runtime errors, such as type mismatches (e.g., adding a string to
|
||||
/// an integer), division by zero, or failed `assert` statements.
|
||||
/// all unrecoverable runtime errors, such as type mismatches (e.g., adding
|
||||
/// a string to an integer), division by zero, or primitive operation
|
||||
/// argument arity mismatch
|
||||
#[error("error occurred during evaluation stage: {0}")]
|
||||
EvalError(String),
|
||||
|
||||
/// Represents an error that can be generated by `throw` or `assert`, and
|
||||
/// can be caught by `builtins.tryEval`.
|
||||
#[error("{0}")]
|
||||
Catchable(String),
|
||||
|
||||
/// A catch-all for any error that does not fit into the other categories.
|
||||
#[error("an unknown or unexpected error occurred")]
|
||||
Unknown,
|
||||
|
||||
@@ -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!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add(&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),
|
||||
_ => return Err(Error::EvalError(format!("expected an integer but found {}", self.typename())))
|
||||
};
|
||||
(Ok(()), val)
|
||||
},
|
||||
)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn mul(&mut self, other: Self) {
|
||||
pub fn add(mut self: &mut Self, other: Self) -> Result<()> {
|
||||
use Value::*;
|
||||
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) -> 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 {
|
||||
} else {
|
||||
todo!()
|
||||
}
|
||||
Ok(self)
|
||||
} else {
|
||||
Err(Error::EvalError(format!("cannot coerce {} to string", self.typename())))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 leftover = args.split_off(self.arity);
|
||||
for arg in self.args.iter().rev().cloned() {
|
||||
args.insert(0, arg);
|
||||
}
|
||||
let mut ret = ctx.call_primop(self.id, args)?;
|
||||
ret.call(leftover.into_iter().map(Ok), ctx)?;
|
||||
return Ok(ret);
|
||||
}
|
||||
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)))
|
||||
ctx.call_primop(self_mut.id, std::mem::take(&mut self_mut.args))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}) else {
|
||||
return Value::PrimOpApp(self.clone()).ok();
|
||||
};
|
||||
ret
|
||||
Ok(Value::PrimOpApp(self.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ use std::ptr::NonNull;
|
||||
use hashbrown::HashMap;
|
||||
|
||||
use nixjit_eval::{AttrSet, EvalContext, List, Value};
|
||||
use nixjit_ir::ArgIdx;
|
||||
|
||||
use super::JITContext;
|
||||
|
||||
@@ -34,7 +35,7 @@ pub extern "C" fn helper_call<Ctx: JITContext>(
|
||||
/// Helper function to look up a value in the evaluation stack.
|
||||
///
|
||||
/// This function is called from JIT-compiled code to access values in the evaluation stack.
|
||||
pub extern "C" fn helper_lookup_stack<Ctx: JITContext>(
|
||||
pub extern "C" fn helper_lookup_stack<Ctx: JITContext + EvalContext>(
|
||||
ctx: &Ctx,
|
||||
offset: usize,
|
||||
ret: &mut MaybeUninit<Value>,
|
||||
@@ -45,12 +46,12 @@ pub extern "C" fn helper_lookup_stack<Ctx: JITContext>(
|
||||
/// Helper function to look up a function argument.
|
||||
///
|
||||
/// This function is called from JIT-compiled code to access function arguments.
|
||||
pub extern "C" fn helper_lookup_arg<Ctx: JITContext>(
|
||||
pub extern "C" fn helper_lookup_arg<Ctx: EvalContext>(
|
||||
ctx: &Ctx,
|
||||
offset: usize,
|
||||
idx: ArgIdx,
|
||||
ret: &mut MaybeUninit<Value>,
|
||||
) {
|
||||
ret.write(JITContext::lookup_arg(ctx, offset).clone());
|
||||
ret.write(ctx.lookup_arg(idx).clone());
|
||||
}
|
||||
|
||||
/// Helper function to look up a variable by name.
|
||||
@@ -87,7 +88,7 @@ pub extern "C" fn helper_select<Ctx: JITContext>(
|
||||
let path = core::ptr::slice_from_raw_parts_mut(path_ptr, path_len);
|
||||
let path = unsafe { Box::from_raw(path) };
|
||||
val.select(path.into_iter().map(|mut val| {
|
||||
val.coerce_to_string();
|
||||
val.coerce_to_string().unwrap();
|
||||
Ok(val.unwrap_string())
|
||||
}))
|
||||
.unwrap();
|
||||
@@ -107,7 +108,7 @@ pub extern "C" fn helper_select_with_default<Ctx: JITContext>(
|
||||
let path = unsafe { Box::from_raw(path) };
|
||||
val.select_with_default(
|
||||
path.into_iter().map(|mut val| {
|
||||
val.coerce_to_string();
|
||||
val.coerce_to_string().unwrap();
|
||||
Ok(val.unwrap_string())
|
||||
}),
|
||||
unsafe { default.read() },
|
||||
@@ -119,7 +120,7 @@ pub extern "C" fn helper_select_with_default<Ctx: JITContext>(
|
||||
///
|
||||
/// This function is called from JIT-compiled code to perform equality comparisons.
|
||||
pub extern "C" fn helper_eq<Ctx: JITContext>(lhs: &mut Value, rhs: &Value) {
|
||||
lhs.eq(rhs);
|
||||
lhs.eq(unsafe { core::ptr::read(rhs) });
|
||||
}
|
||||
|
||||
/// Helper function to create a string value.
|
||||
|
||||
@@ -32,13 +32,8 @@ use helpers::*;
|
||||
/// A trait that provides the execution context for JIT-compiled code.
|
||||
///
|
||||
/// This trait extends `EvalContext` with additional methods needed
|
||||
/// for JIT compilation, such as stack and argument lookups, and
|
||||
/// managing `with` expression scopes.
|
||||
/// for JIT compilation, such as managing `with` expression scopes directly.
|
||||
pub trait JITContext: EvalContext {
|
||||
/// Looks up a value in the evaluation stack by offset.
|
||||
fn lookup_stack(&self, offset: usize) -> &Value;
|
||||
/// Looks up a function argument by offset.
|
||||
fn lookup_arg(&self, offset: usize) -> &Value;
|
||||
/// Enters a `with` expression scope with the given namespace.
|
||||
fn enter_with(&mut self, namespace: Rc<HashMap<String, Value>>);
|
||||
/// Exits the current `with` expression scope.
|
||||
|
||||
@@ -15,26 +15,6 @@ use std::sync::LazyLock;
|
||||
use derive_more::{Constructor, IsVariant, Unwrap};
|
||||
use regex::Regex;
|
||||
|
||||
/// Represents errors thrown by `assert` and `throw` expressions in Nix.
|
||||
/// These errors can potentially be caught and handled by `builtins.tryEval`.
|
||||
#[derive(Clone, Debug, PartialEq, Constructor, Hash)]
|
||||
pub struct Catchable {
|
||||
/// The error message.
|
||||
msg: String,
|
||||
}
|
||||
|
||||
impl<T: Into<String>> From<T> for Catchable {
|
||||
fn from(value: T) -> Self {
|
||||
Catchable { msg: value.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Catchable {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||
write!(f, "<error: {}>", self.msg)
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a constant, primitive value in Nix.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, IsVariant, Unwrap)]
|
||||
pub enum Const {
|
||||
@@ -206,8 +186,6 @@ pub enum Value {
|
||||
AttrSet(AttrSet),
|
||||
/// A list.
|
||||
List(List),
|
||||
/// A catchable error.
|
||||
Catchable(Catchable),
|
||||
/// A thunk, representing a delayed computation.
|
||||
Thunk,
|
||||
/// A function (lambda).
|
||||
@@ -229,7 +207,6 @@ impl Display for Value {
|
||||
String(x) => write!(f, r#""{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}>"),
|
||||
|
||||
Reference in New Issue
Block a user