feat: error handling
This commit is contained in:
@@ -21,8 +21,6 @@ pub mod builtins {
|
|||||||
(Int(a), Float(b)) => Float(a as f64 + b),
|
(Int(a), Float(b)) => Float(a as f64 + b),
|
||||||
(Float(a), Int(b)) => Float(a + b as f64),
|
(Float(a), Int(b)) => Float(a + b as f64),
|
||||||
(Float(a), Float(b)) => Float(a + b),
|
(Float(a), Float(b)) => Float(a + b),
|
||||||
(a @ Value::Catchable(_), _) => a,
|
|
||||||
(_, b @ Value::Catchable(_)) => b,
|
|
||||||
_ => return Err(Error::EvalError(format!(""))),
|
_ => return Err(Error::EvalError(format!(""))),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ impl Context {
|
|||||||
}
|
}
|
||||||
let root = root.tree().expr().unwrap().downgrade(&mut self)?;
|
let root = root.tree().expr().unwrap().downgrade(&mut self)?;
|
||||||
self.resolve(root)?;
|
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()
|
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> {
|
fn lookup_with<'a>(&'a self, ident: &str) -> Option<&'a nixjit_eval::Value> {
|
||||||
for scope in self.with_scopes.iter().rev() {
|
for scope in self.with_scopes.iter().rev() {
|
||||||
if let Some(val) = scope.get(ident) {
|
if let Some(val) = scope.get(ident) {
|
||||||
@@ -406,15 +410,6 @@ impl EvalContext for Context {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl JITContext 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>>) {
|
fn enter_with(&mut self, namespace: std::rc::Rc<HashMap<String, nixjit_eval::Value>>) {
|
||||||
self.with_scopes.push(namespace);
|
self.with_scopes.push(namespace);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,11 +32,17 @@ pub enum Error {
|
|||||||
ResolutionError(String),
|
ResolutionError(String),
|
||||||
|
|
||||||
/// An error occurred during the final evaluation of the LIR. This covers
|
/// 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
|
/// all unrecoverable runtime errors, such as type mismatches (e.g., adding
|
||||||
/// an integer), division by zero, or failed `assert` statements.
|
/// a string to an integer), division by zero, or primitive operation
|
||||||
|
/// argument arity mismatch
|
||||||
#[error("error occurred during evaluation stage: {0}")]
|
#[error("error occurred during evaluation stage: {0}")]
|
||||||
EvalError(String),
|
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.
|
/// A catch-all for any error that does not fit into the other categories.
|
||||||
#[error("an unknown or unexpected error occurred")]
|
#[error("an unknown or unexpected error occurred")]
|
||||||
Unknown,
|
Unknown,
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ use hashbrown::HashMap;
|
|||||||
use nixjit_error::{Error, Result};
|
use nixjit_error::{Error, Result};
|
||||||
use nixjit_ir::{self as ir, ArgIdx, ExprId, PrimOpId};
|
use nixjit_ir::{self as ir, ArgIdx, ExprId, PrimOpId};
|
||||||
use nixjit_lir as lir;
|
use nixjit_lir as lir;
|
||||||
use nixjit_value::{Const, Symbol, format_symbol};
|
use nixjit_value::{Const, format_symbol};
|
||||||
|
|
||||||
pub use crate::value::*;
|
pub use crate::value::*;
|
||||||
|
|
||||||
@@ -39,6 +39,9 @@ pub trait EvalContext: Sized {
|
|||||||
f: impl FnOnce(&mut Self) -> T,
|
f: impl FnOnce(&mut Self) -> T,
|
||||||
) -> (Vec<Value>, 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.
|
/// Looks up an identifier in the current `with` scope chain.
|
||||||
fn lookup_with<'a>(&'a self, ident: &str) -> Option<&'a Value>;
|
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() {
|
for (k, v) in self.dyns.iter() {
|
||||||
let mut k = k.eval(ctx)?;
|
let mut k = k.eval(ctx)?;
|
||||||
k.coerce_to_string();
|
k.coerce_to_string()?;
|
||||||
let v_eval_result = v.eval(ctx)?;
|
let v_eval_result = v.eval(ctx)?;
|
||||||
attrs.push_attr(k.unwrap_string(), v_eval_result)?;
|
attrs.push_attr(k.unwrap_string(), v_eval_result)?;
|
||||||
}
|
}
|
||||||
@@ -135,14 +138,10 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::HasAttr {
|
|||||||
use ir::Attr::*;
|
use ir::Attr::*;
|
||||||
let mut val = self.lhs.eval(ctx)?;
|
let mut val = self.lhs.eval(ctx)?;
|
||||||
val.has_attr(self.rhs.iter().map(|attr| {
|
val.has_attr(self.rhs.iter().map(|attr| {
|
||||||
Ok(match attr {
|
match attr {
|
||||||
Str(ident) => ident.clone(),
|
Str(ident) => Ok(Value::String(ident.clone())),
|
||||||
Dynamic(expr) => {
|
Dynamic(expr) => expr.eval(ctx)
|
||||||
let mut val = expr.eval(ctx)?;
|
}
|
||||||
val.coerce_to_string();
|
|
||||||
val.unwrap_string()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}))?;
|
}))?;
|
||||||
Ok(val)
|
Ok(val)
|
||||||
}
|
}
|
||||||
@@ -153,42 +152,47 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::BinOp {
|
|||||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||||
use ir::BinOpKind::*;
|
use ir::BinOpKind::*;
|
||||||
let mut lhs = self.lhs.eval(ctx)?;
|
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)?;
|
let mut rhs = self.rhs.eval(ctx)?;
|
||||||
match self.kind {
|
match self.kind {
|
||||||
Add => lhs.add(rhs)?,
|
Add => lhs.add(rhs)?,
|
||||||
Sub => {
|
Sub => {
|
||||||
rhs.neg();
|
rhs.neg()?;
|
||||||
lhs.add(rhs)?;
|
lhs.add(rhs)?;
|
||||||
}
|
}
|
||||||
Mul => lhs.mul(rhs),
|
Mul => lhs.mul(rhs)?,
|
||||||
Div => lhs.div(rhs)?,
|
Div => lhs.div(rhs)?,
|
||||||
Eq => Value::eq(&mut lhs, &rhs),
|
Eq => Value::eq(&mut lhs, rhs),
|
||||||
Neq => {
|
Neq => {
|
||||||
Value::eq(&mut lhs, &rhs);
|
Value::eq(&mut lhs, rhs);
|
||||||
lhs.not();
|
let _ = lhs.not();
|
||||||
}
|
}
|
||||||
Lt => lhs.lt(rhs),
|
Lt => lhs.lt(rhs)?,
|
||||||
Gt => {
|
Gt => {
|
||||||
rhs.lt(lhs);
|
rhs.lt(lhs)?;
|
||||||
lhs = rhs;
|
lhs = rhs;
|
||||||
}
|
}
|
||||||
Leq => {
|
Leq => {
|
||||||
rhs.lt(lhs);
|
rhs.lt(lhs)?;
|
||||||
rhs.not();
|
let _ = rhs.not();
|
||||||
lhs = rhs;
|
lhs = rhs;
|
||||||
}
|
}
|
||||||
Geq => {
|
Geq => {
|
||||||
lhs.lt(rhs);
|
lhs.lt(rhs)?;
|
||||||
lhs.not();
|
let _ = lhs.not()?;
|
||||||
}
|
}
|
||||||
And => lhs.and(rhs),
|
And => lhs.and(rhs)?,
|
||||||
Or => lhs.or(rhs),
|
Or => lhs.or(rhs)?,
|
||||||
Impl => {
|
Impl => {
|
||||||
lhs.not();
|
let _ = lhs.not();
|
||||||
lhs.or(rhs);
|
lhs.or(rhs)?;
|
||||||
}
|
}
|
||||||
Con => lhs.concat(rhs),
|
Con => lhs.concat(rhs)?,
|
||||||
Upd => lhs.update(rhs),
|
Upd => lhs.update(rhs)?,
|
||||||
PipeL => lhs.call(core::iter::once(Ok(rhs)), ctx)?,
|
PipeL => lhs.call(core::iter::once(Ok(rhs)), ctx)?,
|
||||||
PipeR => {
|
PipeR => {
|
||||||
rhs.call(core::iter::once(Ok(lhs)), ctx)?;
|
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)?;
|
let mut rhs = self.rhs.eval(ctx)?;
|
||||||
match self.kind {
|
match self.kind {
|
||||||
Neg => {
|
Neg => {
|
||||||
rhs.neg();
|
rhs.neg()?;
|
||||||
}
|
}
|
||||||
Not => {
|
Not => {
|
||||||
rhs.not();
|
rhs.not()?;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Ok(rhs)
|
Ok(rhs)
|
||||||
@@ -230,7 +234,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Select {
|
|||||||
Str(ident) => ident.clone(),
|
Str(ident) => ident.clone(),
|
||||||
Dynamic(expr) => {
|
Dynamic(expr) => {
|
||||||
let mut val = expr.eval(ctx)?;
|
let mut val = expr.eval(ctx)?;
|
||||||
val.coerce_to_string();
|
val.coerce_to_string()?;
|
||||||
val.unwrap_string()
|
val.unwrap_string()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -243,7 +247,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Select {
|
|||||||
Str(ident) => ident.clone(),
|
Str(ident) => ident.clone(),
|
||||||
Dynamic(expr) => {
|
Dynamic(expr) => {
|
||||||
let mut val = expr.eval(ctx)?;
|
let mut val = expr.eval(ctx)?;
|
||||||
val.coerce_to_string();
|
val.coerce_to_string()?;
|
||||||
val.unwrap_string()
|
val.unwrap_string()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -314,7 +318,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Assert {
|
|||||||
if cond {
|
if cond {
|
||||||
self.expr.eval(ctx)
|
self.expr.eval(ctx)
|
||||||
} else {
|
} 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,
|
/// Evaluates a `ConcatStrings` by evaluating each part, coercing it to a string,
|
||||||
/// and then concatenating the results.
|
/// and then concatenating the results.
|
||||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||||
let mut parts = self
|
let mut buf = String::new();
|
||||||
.parts
|
for part in self.parts.iter() {
|
||||||
.iter()
|
buf.push_str(part.eval(ctx)?.coerce_to_string()?.as_ref().unwrap_string());
|
||||||
.map(|part| {
|
}
|
||||||
let mut part = part.eval(ctx)?;
|
Ok(Value::String(buf))
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -376,7 +369,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Var {
|
|||||||
|
|
||||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Path {
|
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Path {
|
||||||
/// Evaluates a `Path`. (Currently a TODO).
|
/// Evaluates a `Path`. (Currently a TODO).
|
||||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
fn eval(&self, _ctx: &mut Ctx) -> Result<Value> {
|
||||||
todo!()
|
todo!()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use std::rc::Rc;
|
|||||||
|
|
||||||
use derive_more::Constructor;
|
use derive_more::Constructor;
|
||||||
use hashbrown::hash_map::Entry;
|
use hashbrown::hash_map::Entry;
|
||||||
use hashbrown::{HashMap, HashSet};
|
use hashbrown::HashMap;
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
|
|
||||||
use nixjit_error::{Error, Result};
|
use nixjit_error::{Error, Result};
|
||||||
@@ -66,12 +66,7 @@ impl AttrSet {
|
|||||||
self.data.insert(sym, val);
|
self.data.insert(sym, val);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inserts an attribute.
|
/// Inserts an attribute, returns an error if the attribute is already defined.
|
||||||
///
|
|
||||||
/// # Panics
|
|
||||||
///
|
|
||||||
/// This method currently uses `todo!()` and will panic if the attribute
|
|
||||||
/// already exists, indicating that duplicate attribute handling is not yet implemented.
|
|
||||||
pub fn push_attr(&mut self, sym: String, val: Value) -> Result<()> {
|
pub fn push_attr(&mut self, sym: String, val: Value) -> Result<()> {
|
||||||
match self.data.entry(sym) {
|
match self.data.entry(sym) {
|
||||||
Entry::Occupied(occupied) => Err(Error::EvalError(format!(
|
Entry::Occupied(occupied) => Err(Error::EvalError(format!(
|
||||||
@@ -114,17 +109,22 @@ impl AttrSet {
|
|||||||
/// Checks if an attribute path exists within the set.
|
/// Checks if an attribute path exists within the set.
|
||||||
pub fn has_attr(
|
pub fn has_attr(
|
||||||
&self,
|
&self,
|
||||||
mut path: impl DoubleEndedIterator<Item = Result<String>>,
|
mut path: impl DoubleEndedIterator<Item = Result<Value>>,
|
||||||
) -> Result<bool> {
|
) -> Result<Value> {
|
||||||
let mut data = &self.data;
|
let mut data = &self.data;
|
||||||
let last = path.nth_back(0).unwrap();
|
let last = path.nth_back(0).unwrap();
|
||||||
for item in path {
|
for item in path {
|
||||||
let Some(Value::AttrSet(attrs)) = data.get(&item?) else {
|
let Some(Value::AttrSet(attrs)) =
|
||||||
return Ok(false);
|
data.get(item.unwrap().coerce_to_string()?.as_ref().unwrap_string())
|
||||||
|
else {
|
||||||
|
return Ok(Value::Bool(false));
|
||||||
};
|
};
|
||||||
data = attrs.as_inner();
|
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`
|
/// Merges another `AttrSet` into this one, with attributes from `other`
|
||||||
@@ -169,11 +169,11 @@ impl AttrSet {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Converts the `AttrSet` to its public-facing representation.
|
/// 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(
|
p::Value::AttrSet(p::AttrSet::new(
|
||||||
self.data
|
self.data
|
||||||
.iter()
|
.into_iter()
|
||||||
.map(|(sym, value)| (sym.as_str().into(), value.to_public(seen)))
|
.map(|(sym, value)| (sym.into(), value.to_public()))
|
||||||
.collect(),
|
.collect(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,6 +64,6 @@ impl FuncApp {
|
|||||||
val = ret?;
|
val = ret?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val.ok()
|
Ok(val)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -77,11 +77,11 @@ impl List {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Converts the `List` to its public-facing representation.
|
/// 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(
|
PubValue::List(PubList::new(
|
||||||
self.data
|
self.data
|
||||||
.iter()
|
.iter()
|
||||||
.map(|value| value.clone().to_public(seen))
|
.map(|value| value.clone().to_public())
|
||||||
.collect(),
|
.collect(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,14 +11,11 @@
|
|||||||
|
|
||||||
use std::fmt::Debug;
|
use std::fmt::Debug;
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::process::abort;
|
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use derive_more::TryUnwrap;
|
use derive_more::TryUnwrap;
|
||||||
use derive_more::{IsVariant, Unwrap};
|
use derive_more::{IsVariant, Unwrap};
|
||||||
use hashbrown::HashSet;
|
|
||||||
use nixjit_ir::{ExprId, PrimOp};
|
use nixjit_ir::{ExprId, PrimOp};
|
||||||
use replace_with::replace_with_and_return;
|
|
||||||
|
|
||||||
use nixjit_error::{Error, Result};
|
use nixjit_error::{Error, Result};
|
||||||
use nixjit_value::Const;
|
use nixjit_value::Const;
|
||||||
@@ -53,7 +50,6 @@ pub enum Value {
|
|||||||
Thunk(ExprId),
|
Thunk(ExprId),
|
||||||
AttrSet(Rc<AttrSet>),
|
AttrSet(Rc<AttrSet>),
|
||||||
List(Rc<List>),
|
List(Rc<List>),
|
||||||
Catchable(String),
|
|
||||||
PrimOp(PrimOp),
|
PrimOp(PrimOp),
|
||||||
PrimOpApp(Rc<PrimOpApp>),
|
PrimOpApp(Rc<PrimOpApp>),
|
||||||
Func(ExprId),
|
Func(ExprId),
|
||||||
@@ -71,7 +67,6 @@ impl Debug for Value {
|
|||||||
String(x) => write!(f, "{x}"),
|
String(x) => write!(f, "{x}"),
|
||||||
AttrSet(x) => write!(f, "{x:?}"),
|
AttrSet(x) => write!(f, "{x:?}"),
|
||||||
List(x) => write!(f, "{x:?}"),
|
List(x) => write!(f, "{x:?}"),
|
||||||
Catchable(x) => write!(f, "{x}"),
|
|
||||||
Thunk(thunk) => write!(f, "<THUNK {thunk:?}>"),
|
Thunk(thunk) => write!(f, "<THUNK {thunk:?}>"),
|
||||||
Func(func) => write!(f, "<LAMBDA {func:?}>"),
|
Func(func) => write!(f, "<LAMBDA {func:?}>"),
|
||||||
FuncApp(func) => write!(f, "<LAMBDA-APP {:?}>", func.body),
|
FuncApp(func) => write!(f, "<LAMBDA-APP {:?}>", func.body),
|
||||||
@@ -151,7 +146,6 @@ pub enum ValueAsRef<'v> {
|
|||||||
Thunk(&'v ExprId),
|
Thunk(&'v ExprId),
|
||||||
AttrSet(&'v AttrSet),
|
AttrSet(&'v AttrSet),
|
||||||
List(&'v List),
|
List(&'v List),
|
||||||
Catchable(&'v str),
|
|
||||||
PrimOp(&'v PrimOp),
|
PrimOp(&'v PrimOp),
|
||||||
PartialPrimOp(&'v PrimOpApp),
|
PartialPrimOp(&'v PrimOpApp),
|
||||||
Func(&'v ExprId),
|
Func(&'v ExprId),
|
||||||
@@ -172,7 +166,6 @@ impl Value {
|
|||||||
Thunk(x) => R::Thunk(x),
|
Thunk(x) => R::Thunk(x),
|
||||||
AttrSet(x) => R::AttrSet(x),
|
AttrSet(x) => R::AttrSet(x),
|
||||||
List(x) => R::List(x),
|
List(x) => R::List(x),
|
||||||
Catchable(x) => R::Catchable(x),
|
|
||||||
PrimOp(x) => R::PrimOp(x),
|
PrimOp(x) => R::PrimOp(x),
|
||||||
PrimOpApp(x) => R::PartialPrimOp(x),
|
PrimOpApp(x) => R::PartialPrimOp(x),
|
||||||
Func(x) => R::Func(x),
|
Func(x) => R::Func(x),
|
||||||
@@ -181,11 +174,6 @@ impl Value {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
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.
|
/// Returns the name of the value's type.
|
||||||
pub fn typename(&self) -> &'static str {
|
pub fn typename(&self) -> &'static str {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
@@ -198,7 +186,6 @@ impl Value {
|
|||||||
Thunk(_) => "thunk",
|
Thunk(_) => "thunk",
|
||||||
AttrSet(_) => "set",
|
AttrSet(_) => "set",
|
||||||
List(_) => "list",
|
List(_) => "list",
|
||||||
Catchable(_) => unreachable!(),
|
|
||||||
PrimOp(_) => "lambda",
|
PrimOp(_) => "lambda",
|
||||||
PrimOpApp(_) => "lambda",
|
PrimOpApp(_) => "lambda",
|
||||||
Func(_) => "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`.
|
/// Performs a function call on the `Value`.
|
||||||
///
|
///
|
||||||
/// This method handles calling functions, primops, and their partially
|
/// This method handles calling functions, primops, and their partially
|
||||||
@@ -227,20 +205,22 @@ impl Value {
|
|||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
*self = match self {
|
*self = match self {
|
||||||
&mut PrimOp(func) => {
|
&mut PrimOp(primop) => {
|
||||||
if iter.len() > func.arity {
|
if iter.len() > primop.arity {
|
||||||
todo!()
|
let mut args = iter.collect::<Result<Vec<_>>>()?;
|
||||||
}
|
let leftover = args.split_off(primop.arity);
|
||||||
if func.arity > iter.len() {
|
let mut ret = ctx.call_primop(primop.id, args)?;
|
||||||
Value::PrimOpApp(Rc::new(self::PrimOpApp::new(
|
ret.call(leftover.into_iter().map(Ok), ctx)?;
|
||||||
func.name,
|
Ok(ret)
|
||||||
func.arity - iter.len(),
|
} else if primop.arity > iter.len() {
|
||||||
func.id,
|
Ok(Value::PrimOpApp(Rc::new(self::PrimOpApp::new(
|
||||||
|
primop.name,
|
||||||
|
primop.arity - iter.len(),
|
||||||
|
primop.id,
|
||||||
iter.collect::<Result<_>>()?,
|
iter.collect::<Result<_>>()?,
|
||||||
)))
|
))))
|
||||||
.ok()
|
|
||||||
} else {
|
} else {
|
||||||
ctx.call_primop(func.id, iter.collect::<Result<_>>()?)
|
ctx.call_primop(primop.id, iter.collect::<Result<_>>()?)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
&mut Func(expr) => {
|
&mut Func(expr) => {
|
||||||
@@ -271,11 +251,10 @@ impl Value {
|
|||||||
val = ret?;
|
val = ret?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val.ok()
|
Ok(val)
|
||||||
}
|
}
|
||||||
PrimOpApp(func) => func.call(iter.collect::<Result<_>>()?, ctx),
|
PrimOpApp(func) => func.call(iter.collect::<Result<_>>()?, ctx),
|
||||||
FuncApp(func) => func.call(iter, ctx),
|
FuncApp(func) => func.call(iter, ctx),
|
||||||
Catchable(_) => return Ok(()),
|
|
||||||
_ => Err(Error::EvalError(
|
_ => Err(Error::EvalError(
|
||||||
"attempt to call something which is not a function but ...".to_string(),
|
"attempt to call something which is not a function but ...".to_string(),
|
||||||
)),
|
)),
|
||||||
@@ -283,45 +262,47 @@ impl Value {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn not(&mut self) {
|
pub fn not(&mut self) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
*self = match &*self {
|
match &*self {
|
||||||
Bool(bool) => Bool(!bool),
|
Bool(bool) => {
|
||||||
Value::Catchable(_) => return,
|
*self = Bool(!bool);
|
||||||
_ => todo!(),
|
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::*;
|
use Value::*;
|
||||||
*self = match (&*self, other) {
|
match (&*self, other) {
|
||||||
(Bool(a), Bool(b)) => Bool(*a && b),
|
(&Bool(a), Bool(b)) => {
|
||||||
(Value::Catchable(_), _) => return,
|
*self = Bool(a && b);
|
||||||
(_, x @ Value::Catchable(_)) => x,
|
Ok(())
|
||||||
_ => todo!(),
|
}
|
||||||
|
_ => 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::*;
|
use Value::*;
|
||||||
*self = match (&*self, other) {
|
match (&*self, other) {
|
||||||
(Bool(a), Bool(b)) => Bool(*a || b),
|
(&Bool(a), Bool(b)) => {
|
||||||
(Value::Catchable(_), _) => return,
|
*self = Bool(a || b);
|
||||||
(_, x @ Value::Catchable(_)) => x,
|
Ok(())
|
||||||
_ => todo!(),
|
}
|
||||||
|
_ => 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;
|
use Value::Bool;
|
||||||
*self = match (&*self, other) {
|
*self = match (&*self, other) {
|
||||||
(Value::Catchable(_), _) => return,
|
(s, other) => Bool(s.eq_impl(&other)),
|
||||||
(_, x @ Value::Catchable(_)) => x.clone(),
|
|
||||||
(s, other) => Bool(s.eq_impl(other)),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn lt(&mut self, other: Self) {
|
pub fn lt(&mut self, other: Self) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
*self = Bool(match (&*self, other) {
|
*self = Bool(match (&*self, other) {
|
||||||
(Int(a), Int(b)) => *a < b,
|
(Int(a), Int(b)) => *a < b,
|
||||||
@@ -329,60 +310,47 @@ impl Value {
|
|||||||
(Float(a), Int(b)) => *a < b as f64,
|
(Float(a), Int(b)) => *a < b as f64,
|
||||||
(Float(a), Float(b)) => *a < b,
|
(Float(a), Float(b)) => *a < b,
|
||||||
(String(a), String(b)) => a.as_str() < b.as_str(),
|
(String(a), String(b)) => a.as_str() < b.as_str(),
|
||||||
(Value::Catchable(_), _) => return,
|
(a, b) => return Err(Error::EvalError(format!("cannot compare {} with {}", a.typename(), b.typename()))),
|
||||||
(_, x @ Value::Catchable(_)) => {
|
});
|
||||||
*self = x;
|
Ok(())
|
||||||
return;
|
|
||||||
}
|
|
||||||
_ => todo!(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn neg(&mut self) {
|
pub fn neg(&mut self) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
*self = match &*self {
|
*self = match &*self {
|
||||||
Int(int) => Int(-int),
|
Int(int) => Int(-int),
|
||||||
Float(float) => Float(-float),
|
Float(float) => Float(-float),
|
||||||
Value::Catchable(_) => return,
|
_ => return Err(Error::EvalError(format!("expected an integer but found {}", self.typename())))
|
||||||
_ => todo!(),
|
};
|
||||||
}
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add(&mut self, other: Self) -> Result<()> {
|
pub fn add(mut self: &mut Self, other: Self) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
replace_with_and_return(
|
if let (String(a), String(b)) = (&mut self, &other) {
|
||||||
self,
|
a.push_str(b.as_str());
|
||||||
|| abort(),
|
return Ok(());
|
||||||
|a| {
|
}
|
||||||
let val = match (a, other) {
|
*self = match (&mut self, other) {
|
||||||
(Int(a), Int(b)) => Int(a + b),
|
(Int(a), Int(b)) => Int(*a + b),
|
||||||
(Int(a), Float(b)) => Float(a as f64 + b),
|
(&mut Int(a), Float(b)) => Float(*a as f64 + b),
|
||||||
(Float(a), Int(b)) => Float(a + b as f64),
|
(&mut Float(a), Int(b)) => Float(*a + b as f64),
|
||||||
(Float(a), Float(b)) => Float(a + b),
|
(&mut Float(a), Float(b)) => Float(*a + b),
|
||||||
(String(mut a), String(b)) => {
|
(a, b) => return Err(Error::EvalError(format!("cannot add {} to {}", a.typename(), b.typename())))
|
||||||
a.push_str(&b);
|
};
|
||||||
String(a)
|
Ok(())
|
||||||
}
|
|
||||||
(a @ Value::Catchable(_), _) => a,
|
|
||||||
(_, x @ Value::Catchable(_)) => x,
|
|
||||||
_ => return (Err(Error::EvalError(format!(""))), Value::Null),
|
|
||||||
};
|
|
||||||
(Ok(()), val)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mul(&mut self, other: Self) {
|
pub fn mul(&mut self, other: Self) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
*self = match (&*self, other) {
|
*self = match (&*self, other) {
|
||||||
(Int(a), Int(b)) => Int(a * b),
|
(Int(a), Int(b)) => Int(a * b),
|
||||||
(Int(a), Float(b)) => Float(*a as f64 * b),
|
(Int(a), Float(b)) => Float(*a as f64 * b),
|
||||||
(Float(a), Int(b)) => Float(a * b as f64),
|
(Float(a), Int(b)) => Float(a * b as f64),
|
||||||
(Float(a), Float(b)) => Float(a * b),
|
(Float(a), Float(b)) => Float(a * b),
|
||||||
(Value::Catchable(_), _) => return,
|
(a, b) => return Err(Error::EvalError(format!("cannot multiply {} with {}", a.typename(), b.typename())))
|
||||||
(_, x @ Value::Catchable(_)) => x,
|
};
|
||||||
_ => todo!(),
|
Ok(())
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn div(&mut self, other: Self) -> Result<()> {
|
pub fn div(&mut self, other: Self) -> Result<()> {
|
||||||
@@ -396,108 +364,58 @@ impl Value {
|
|||||||
(Int(a), Float(b)) => Float(*a as f64 / b),
|
(Int(a), Float(b)) => Float(*a as f64 / b),
|
||||||
(Float(a), Int(b)) => Float(a / b as f64),
|
(Float(a), Int(b)) => Float(a / b as f64),
|
||||||
(Float(a), Float(b)) => Float(a / b),
|
(Float(a), Float(b)) => Float(a / b),
|
||||||
(Catchable(_), _) => return Ok(()),
|
(a, b) => return Err(Error::EvalError(format!("cannot divide {} with {}", a.typename(), b.typename())))
|
||||||
(_, x @ Catchable(_)) => x,
|
|
||||||
_ => todo!(),
|
|
||||||
};
|
};
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn concat_string(&mut self, mut other: Self) -> &mut Self {
|
pub fn concat(mut self: &mut Self, other: Self) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
match (self.coerce_to_string(), other.coerce_to_string()) {
|
match (&mut self, other) {
|
||||||
(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) {
|
|
||||||
(List(a), List(b)) => {
|
(List(a), List(b)) => {
|
||||||
Rc::make_mut(a).concat(&b);
|
Rc::make_mut(a).concat(&b);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
(Catchable(_), _) => (),
|
(List(_), b) => Err(Error::EvalError(format!("expected a list but found {}", b.typename()))),
|
||||||
_ => todo!(),
|
(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::*;
|
use Value::*;
|
||||||
if let AttrSet(attrs) = self {
|
match (&mut self, other) {
|
||||||
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) {
|
|
||||||
(AttrSet(a), AttrSet(b)) => {
|
(AttrSet(a), AttrSet(b)) => {
|
||||||
Rc::make_mut(a).update(&b);
|
Rc::make_mut(a).update(&b);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
(Catchable(_), _) => (),
|
(AttrSet(_), other) => Err(Error::EvalError(format!("expected a set but found {}", other.typename()))),
|
||||||
_ => todo!(),
|
_ => Err(Error::EvalError(format!("expected a set but found {}", self.typename()))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn select(
|
pub fn select(
|
||||||
&mut self,
|
&mut self,
|
||||||
path: impl DoubleEndedIterator<Item = Result<String>>,
|
path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||||
) -> Result<&mut Self> {
|
) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
let val = match self {
|
let val = match self {
|
||||||
AttrSet(attrs) => attrs.select(path),
|
AttrSet(attrs) => attrs.select(path),
|
||||||
Catchable(_) => return Ok(self),
|
|
||||||
_ => Err(Error::EvalError(format!(
|
_ => Err(Error::EvalError(format!(
|
||||||
"can not select from {:?}",
|
"can not select from {:?}",
|
||||||
self.typename()
|
self.typename()
|
||||||
))),
|
))),
|
||||||
}?;
|
}?;
|
||||||
*self = val;
|
*self = val;
|
||||||
Ok(self)
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn select_with_default(
|
pub fn select_with_default(
|
||||||
&mut self,
|
&mut self,
|
||||||
path: impl DoubleEndedIterator<Item = Result<String>>,
|
path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||||
default: Self,
|
default: Self,
|
||||||
) -> Result<&mut Self> {
|
) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
let val = match self {
|
let val = match self {
|
||||||
AttrSet(attrs) => attrs.select(path).unwrap_or(default),
|
AttrSet(attrs) => attrs.select(path).unwrap_or(default),
|
||||||
Catchable(_) => return Ok(self),
|
|
||||||
_ => {
|
_ => {
|
||||||
return Err(Error::EvalError(format!(
|
return Err(Error::EvalError(format!(
|
||||||
"can not select from {:?}",
|
"can not select from {:?}",
|
||||||
@@ -506,18 +424,17 @@ impl Value {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
*self = val;
|
*self = val;
|
||||||
Ok(self)
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn has_attr(
|
pub fn has_attr(
|
||||||
&mut self,
|
&mut self,
|
||||||
path: impl DoubleEndedIterator<Item = Result<String>>,
|
path: impl DoubleEndedIterator<Item = Result<Value>>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
if let AttrSet(attrs) = self {
|
if let AttrSet(attrs) = self {
|
||||||
let val = Bool(attrs.has_attr(path)?);
|
let val = attrs.has_attr(path)?;
|
||||||
*self = val;
|
*self = val;
|
||||||
} else if let Catchable(_) = self {
|
|
||||||
} else {
|
} else {
|
||||||
*self = Bool(false);
|
*self = Bool(false);
|
||||||
}
|
}
|
||||||
@@ -527,11 +444,10 @@ impl Value {
|
|||||||
pub fn coerce_to_string(&mut self) -> Result<&mut Self> {
|
pub fn coerce_to_string(&mut self) -> Result<&mut Self> {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
if let String(_) = self {
|
if let String(_) = self {
|
||||||
} else if let Catchable(_) = self {
|
Ok(self)
|
||||||
} else {
|
} else {
|
||||||
todo!()
|
Err(Error::EvalError(format!("cannot coerce {} to string", self.typename())))
|
||||||
}
|
}
|
||||||
Ok(self)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Converts the internal `Value` to its public-facing, serializable
|
/// 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
|
/// The `seen` set is used to detect and handle cycles in data structures
|
||||||
/// like attribute sets and lists, replacing subsequent encounters with
|
/// like attribute sets and lists, replacing subsequent encounters with
|
||||||
/// `PubValue::Repeated`.
|
/// `PubValue::Repeated`.
|
||||||
pub fn to_public(&self, seen: &mut HashSet<Value>) -> PubValue {
|
pub fn to_public(self) -> PubValue {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
if seen.contains(self) {
|
|
||||||
return PubValue::Repeated;
|
|
||||||
}
|
|
||||||
match self {
|
match self {
|
||||||
AttrSet(attrs) => {
|
AttrSet(attrs) => {
|
||||||
seen.insert(self.clone());
|
Rc::unwrap_or_clone(attrs).to_public()
|
||||||
attrs.to_public(seen)
|
|
||||||
}
|
}
|
||||||
List(list) => {
|
List(list) => {
|
||||||
seen.insert(self.clone());
|
Rc::unwrap_or_clone(list.clone()).to_public()
|
||||||
list.to_public(seen)
|
|
||||||
}
|
}
|
||||||
Catchable(catchable) => PubValue::Catchable(catchable.clone().into()),
|
Int(x) => PubValue::Const(Const::Int(x)),
|
||||||
Int(x) => PubValue::Const(Const::Int(*x)),
|
Float(x) => PubValue::Const(Const::Float(x)),
|
||||||
Float(x) => PubValue::Const(Const::Float(*x)),
|
Bool(x) => PubValue::Const(Const::Bool(x)),
|
||||||
Bool(x) => PubValue::Const(Const::Bool(*x)),
|
String(x) => PubValue::String(x),
|
||||||
String(x) => PubValue::String(x.clone()),
|
|
||||||
Null => PubValue::Const(Const::Null),
|
Null => PubValue::Const(Const::Null),
|
||||||
Thunk(_) => PubValue::Thunk,
|
Thunk(_) => PubValue::Thunk,
|
||||||
PrimOp(primop) => PubValue::PrimOp(primop.name),
|
PrimOp(primop) => PubValue::PrimOp(primop.name),
|
||||||
|
|||||||
@@ -34,24 +34,25 @@ impl PrimOpApp {
|
|||||||
/// arguments.
|
/// arguments.
|
||||||
pub fn call(
|
pub fn call(
|
||||||
self: &mut Rc<Self>,
|
self: &mut Rc<Self>,
|
||||||
args: Vec<Value>,
|
mut args: Vec<Value>,
|
||||||
ctx: &mut impl EvalContext,
|
ctx: &mut impl EvalContext,
|
||||||
) -> Result<Value> {
|
) -> Result<Value> {
|
||||||
if self.arity < args.len() {
|
if self.arity < args.len() {
|
||||||
todo!()
|
let leftover = args.split_off(self.arity);
|
||||||
}
|
for arg in self.args.iter().rev().cloned() {
|
||||||
let Some(ret) = ({
|
args.insert(0, arg);
|
||||||
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
|
|
||||||
}
|
}
|
||||||
}) else {
|
let mut ret = ctx.call_primop(self.id, args)?;
|
||||||
return Value::PrimOpApp(self.clone()).ok();
|
ret.call(leftover.into_iter().map(Ok), ctx)?;
|
||||||
};
|
return Ok(ret);
|
||||||
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()))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ use std::ptr::NonNull;
|
|||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
|
|
||||||
use nixjit_eval::{AttrSet, EvalContext, List, Value};
|
use nixjit_eval::{AttrSet, EvalContext, List, Value};
|
||||||
|
use nixjit_ir::ArgIdx;
|
||||||
|
|
||||||
use super::JITContext;
|
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.
|
/// 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.
|
/// 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,
|
ctx: &Ctx,
|
||||||
offset: usize,
|
offset: usize,
|
||||||
ret: &mut MaybeUninit<Value>,
|
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.
|
/// Helper function to look up a function argument.
|
||||||
///
|
///
|
||||||
/// This function is called from JIT-compiled code to access function arguments.
|
/// 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,
|
ctx: &Ctx,
|
||||||
offset: usize,
|
idx: ArgIdx,
|
||||||
ret: &mut MaybeUninit<Value>,
|
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.
|
/// 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 = core::ptr::slice_from_raw_parts_mut(path_ptr, path_len);
|
||||||
let path = unsafe { Box::from_raw(path) };
|
let path = unsafe { Box::from_raw(path) };
|
||||||
val.select(path.into_iter().map(|mut val| {
|
val.select(path.into_iter().map(|mut val| {
|
||||||
val.coerce_to_string();
|
val.coerce_to_string().unwrap();
|
||||||
Ok(val.unwrap_string())
|
Ok(val.unwrap_string())
|
||||||
}))
|
}))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -107,7 +108,7 @@ pub extern "C" fn helper_select_with_default<Ctx: JITContext>(
|
|||||||
let path = unsafe { Box::from_raw(path) };
|
let path = unsafe { Box::from_raw(path) };
|
||||||
val.select_with_default(
|
val.select_with_default(
|
||||||
path.into_iter().map(|mut val| {
|
path.into_iter().map(|mut val| {
|
||||||
val.coerce_to_string();
|
val.coerce_to_string().unwrap();
|
||||||
Ok(val.unwrap_string())
|
Ok(val.unwrap_string())
|
||||||
}),
|
}),
|
||||||
unsafe { default.read() },
|
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.
|
/// 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) {
|
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.
|
/// Helper function to create a string value.
|
||||||
|
|||||||
@@ -32,13 +32,8 @@ use helpers::*;
|
|||||||
/// A trait that provides the execution context for JIT-compiled code.
|
/// A trait that provides the execution context for JIT-compiled code.
|
||||||
///
|
///
|
||||||
/// This trait extends `EvalContext` with additional methods needed
|
/// This trait extends `EvalContext` with additional methods needed
|
||||||
/// for JIT compilation, such as stack and argument lookups, and
|
/// for JIT compilation, such as managing `with` expression scopes directly.
|
||||||
/// managing `with` expression scopes.
|
|
||||||
pub trait JITContext: EvalContext {
|
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.
|
/// Enters a `with` expression scope with the given namespace.
|
||||||
fn enter_with(&mut self, namespace: Rc<HashMap<String, Value>>);
|
fn enter_with(&mut self, namespace: Rc<HashMap<String, Value>>);
|
||||||
/// Exits the current `with` expression scope.
|
/// Exits the current `with` expression scope.
|
||||||
|
|||||||
@@ -15,26 +15,6 @@ use std::sync::LazyLock;
|
|||||||
use derive_more::{Constructor, IsVariant, Unwrap};
|
use derive_more::{Constructor, IsVariant, Unwrap};
|
||||||
use regex::Regex;
|
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.
|
/// Represents a constant, primitive value in Nix.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, IsVariant, Unwrap)]
|
#[derive(Debug, Clone, Copy, PartialEq, IsVariant, Unwrap)]
|
||||||
pub enum Const {
|
pub enum Const {
|
||||||
@@ -206,8 +186,6 @@ pub enum Value {
|
|||||||
AttrSet(AttrSet),
|
AttrSet(AttrSet),
|
||||||
/// A list.
|
/// A list.
|
||||||
List(List),
|
List(List),
|
||||||
/// A catchable error.
|
|
||||||
Catchable(Catchable),
|
|
||||||
/// A thunk, representing a delayed computation.
|
/// A thunk, representing a delayed computation.
|
||||||
Thunk,
|
Thunk,
|
||||||
/// A function (lambda).
|
/// A function (lambda).
|
||||||
@@ -229,7 +207,6 @@ impl Display for Value {
|
|||||||
String(x) => write!(f, r#""{x}""#),
|
String(x) => write!(f, r#""{x}""#),
|
||||||
AttrSet(x) => write!(f, "{x}"),
|
AttrSet(x) => write!(f, "{x}"),
|
||||||
List(x) => write!(f, "{x}"),
|
List(x) => write!(f, "{x}"),
|
||||||
Catchable(x) => write!(f, "{x}"),
|
|
||||||
Thunk => write!(f, "<CODE>"),
|
Thunk => write!(f, "<CODE>"),
|
||||||
Func => write!(f, "<LAMBDA>"),
|
Func => write!(f, "<LAMBDA>"),
|
||||||
PrimOp(x) => write!(f, "<PRIMOP {x}>"),
|
PrimOp(x) => write!(f, "<PRIMOP {x}>"),
|
||||||
|
|||||||
Reference in New Issue
Block a user