feat: stack var (WIP)
This commit is contained in:
@@ -8,6 +8,7 @@ derive_more = { version = "2.0", features = ["full"] }
|
||||
hashbrown = "0.15"
|
||||
itertools = "0.14"
|
||||
replace_with = "0.1"
|
||||
smallvec = { version = "1.15", features = ["union"] }
|
||||
|
||||
nixjit_error = { path = "../nixjit_error" }
|
||||
nixjit_ir = { path = "../nixjit_ir" }
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::rc::Rc;
|
||||
use hashbrown::HashMap;
|
||||
|
||||
use nixjit_error::{Error, Result};
|
||||
use nixjit_ir::{self as ir, ArgIdx, ExprId, PrimOpId};
|
||||
use nixjit_ir::{self as ir, ExprId, PrimOpId, StackIdx};
|
||||
use nixjit_lir as lir;
|
||||
use nixjit_value::{Const, format_symbol};
|
||||
|
||||
@@ -21,10 +21,14 @@ pub use crate::value::*;
|
||||
mod value;
|
||||
|
||||
/// A trait defining the context in which LIR expressions are evaluated.
|
||||
pub trait EvalContext: Sized {
|
||||
pub trait EvalContext {
|
||||
fn eval_root(self, expr: ExprId) -> Result<Value>;
|
||||
|
||||
|
||||
/// Evaluates an expression by its ID.
|
||||
fn eval(&mut self, expr: ExprId) -> Result<Value>;
|
||||
|
||||
fn call(&mut self, func: ExprId, arg: Option<Value>, frame: StackFrame) -> Result<Value>;
|
||||
/// Enters a `with` scope for the duration of a closure's execution.
|
||||
fn with_with_env<T>(
|
||||
&mut self,
|
||||
@@ -32,27 +36,18 @@ pub trait EvalContext: Sized {
|
||||
f: impl FnOnce(&mut Self) -> T,
|
||||
) -> T;
|
||||
|
||||
/// Pushes a new set of arguments onto the stack for a function call.
|
||||
fn with_args_env<T>(
|
||||
&mut self,
|
||||
args: Vec<Value>,
|
||||
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;
|
||||
fn lookup_stack(&self, idx: StackIdx) -> &Value;
|
||||
|
||||
fn capture_stack(&self) -> &StackFrame;
|
||||
|
||||
/// Looks up an identifier in the current `with` scope chain.
|
||||
fn lookup_with<'a>(&'a self, ident: &str) -> Option<&'a Value>;
|
||||
|
||||
/// Looks up a function argument by its index on the current stack frame.
|
||||
fn lookup_arg<'a>(&'a self, idx: ArgIdx) -> &'a Value;
|
||||
|
||||
/// Pops the current stack frame, returning the arguments.
|
||||
fn pop_frame(&mut self) -> Vec<Value>;
|
||||
|
||||
/// Calls a primitive operation (builtin) by its ID.
|
||||
fn call_primop(&mut self, id: PrimOpId, args: Vec<Value>) -> Result<Value>;
|
||||
fn call_primop(&mut self, id: PrimOpId, args: Args) -> Result<Value>;
|
||||
|
||||
fn get_primop_arity(&self, id: PrimOpId) -> usize;
|
||||
}
|
||||
|
||||
/// A trait for types that can be evaluated within an `EvalContext`.
|
||||
@@ -88,10 +83,12 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for lir::Lir {
|
||||
Str(x) => x.eval(ctx),
|
||||
Var(x) => x.eval(ctx),
|
||||
Path(x) => x.eval(ctx),
|
||||
&StackRef(idx) => Ok(ctx.lookup_stack(idx).clone()),
|
||||
&ExprRef(expr) => ctx.eval(expr),
|
||||
&FuncRef(func) => Ok(Value::Func(func)),
|
||||
&ArgRef(idx) => Ok(ctx.lookup_arg(idx).clone()),
|
||||
&FuncRef(body) => Ok(Value::Closure(Closure::new(body, ctx.capture_stack().clone()).into())),
|
||||
&Arg(_) => unreachable!(),
|
||||
&PrimOp(primop) => Ok(Value::PrimOp(primop)),
|
||||
&Thunk(id) => Ok(Value::Thunk(id)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -109,10 +106,8 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::AttrSet {
|
||||
.collect::<Result<_>>()?,
|
||||
);
|
||||
for (k, v) in self.dyns.iter() {
|
||||
let mut k = k.eval(ctx)?;
|
||||
k.coerce_to_string()?;
|
||||
let v_eval_result = v.eval(ctx)?;
|
||||
attrs.push_attr(k.unwrap_string(), v_eval_result)?;
|
||||
let v = v.eval(ctx)?;
|
||||
attrs.push_attr(k.eval(ctx)?.force_string_no_ctx()?, v)?;
|
||||
}
|
||||
let result = Value::AttrSet(attrs.into());
|
||||
Ok(result)
|
||||
@@ -137,11 +132,9 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::HasAttr {
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
use ir::Attr::*;
|
||||
let mut val = self.lhs.eval(ctx)?;
|
||||
val.has_attr(self.rhs.iter().map(|attr| {
|
||||
match attr {
|
||||
Str(ident) => Ok(Value::String(ident.clone())),
|
||||
Dynamic(expr) => expr.eval(ctx)
|
||||
}
|
||||
val.has_attr(self.rhs.iter().map(|attr| match attr {
|
||||
Str(ident) => Ok(Value::String(ident.clone())),
|
||||
Dynamic(expr) => expr.eval(ctx),
|
||||
}))?;
|
||||
Ok(val)
|
||||
}
|
||||
@@ -155,7 +148,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::BinOp {
|
||||
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))
|
||||
return Ok(Value::Bool(true));
|
||||
}
|
||||
let mut rhs = self.rhs.eval(ctx)?;
|
||||
match self.kind {
|
||||
@@ -193,9 +186,9 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::BinOp {
|
||||
}
|
||||
Con => lhs.concat(rhs)?,
|
||||
Upd => lhs.update(rhs)?,
|
||||
PipeL => lhs.call(core::iter::once(Ok(rhs)), ctx)?,
|
||||
PipeL => lhs.call(rhs, ctx)?,
|
||||
PipeR => {
|
||||
rhs.call(core::iter::once(Ok(lhs)), ctx)?;
|
||||
rhs.call(lhs, ctx)?;
|
||||
lhs = rhs;
|
||||
}
|
||||
}
|
||||
@@ -226,32 +219,20 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Select {
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
use ir::Attr::*;
|
||||
let mut val = self.expr.eval(ctx)?;
|
||||
if let Some(default) = &self.default {
|
||||
let default = default.eval(ctx)?;
|
||||
val.select_with_default(
|
||||
self.attrpath.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()
|
||||
}
|
||||
})
|
||||
}),
|
||||
default,
|
||||
)?;
|
||||
} else {
|
||||
val.select(self.attrpath.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()
|
||||
}
|
||||
})
|
||||
}))?;
|
||||
for attr in self.attrpath.iter() {
|
||||
let name_val;
|
||||
let name = match attr {
|
||||
Str(name) => name,
|
||||
Dynamic(expr) => {
|
||||
name_val = expr.eval(ctx)?;
|
||||
&*name_val.force_string_no_ctx()?
|
||||
}
|
||||
};
|
||||
if let Some(default) = self.default {
|
||||
val.select_or(name, default, ctx)
|
||||
} else {
|
||||
val.select(name, ctx)
|
||||
}?
|
||||
}
|
||||
Ok(val)
|
||||
}
|
||||
@@ -260,9 +241,9 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Select {
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::If {
|
||||
/// Evaluates an `If` by evaluating the condition and then either the consequence or the alternative.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
let cond = self.cond.eval(ctx)?;
|
||||
let cond = cond.as_ref().try_unwrap_bool().map_err(|_| {
|
||||
Error::EvalError(format!(
|
||||
let cond = &self.cond.eval(ctx)?;
|
||||
let &cond = cond.try_into().map_err(|_| {
|
||||
Error::eval_error(format!(
|
||||
"if-condition must be a boolean, but got {}",
|
||||
cond.typename()
|
||||
))
|
||||
@@ -277,11 +258,9 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::If {
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Call {
|
||||
/// Evaluates a `Call` by evaluating the function and its arguments, then performing the call.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
let mut func = self.func.eval(ctx)?;
|
||||
let ctx_mut = unsafe { &mut *(ctx as *mut Ctx) };
|
||||
func.call(self.args.iter().map(|arg| arg.eval(ctx)), ctx_mut)?;
|
||||
func.call(self.arg.eval(ctx)?, ctx)?;
|
||||
Ok(func)
|
||||
}
|
||||
}
|
||||
@@ -296,7 +275,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::With {
|
||||
namespace
|
||||
.try_unwrap_attr_set()
|
||||
.map_err(|_| {
|
||||
Error::EvalError(format!("'with' expects a set, but got {}", typename))
|
||||
Error::eval_error(format!("'with' expects a set, but got {}", typename))
|
||||
})?
|
||||
.into_inner(),
|
||||
|ctx| self.expr.eval(ctx),
|
||||
@@ -308,9 +287,9 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Assert {
|
||||
/// Evaluates an `Assert` by evaluating the condition. If true, it evaluates and
|
||||
/// returns the body; otherwise, it returns an error.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
let cond = self.assertion.eval(ctx)?;
|
||||
let cond = cond.as_ref().try_unwrap_bool().map_err(|_| {
|
||||
Error::EvalError(format!(
|
||||
let cond = &self.assertion.eval(ctx)?;
|
||||
let &cond = cond.try_into().map_err(|_| {
|
||||
Error::eval_error(format!(
|
||||
"assertion condition must be a boolean, but got {}",
|
||||
cond.typename()
|
||||
))
|
||||
@@ -318,7 +297,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Assert {
|
||||
if cond {
|
||||
self.expr.eval(ctx)
|
||||
} else {
|
||||
Err(Error::Catchable("assertion failed".into()))
|
||||
Err(Error::catchable("assertion failed".into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -329,7 +308,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::ConcatStrings {
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
let mut buf = String::new();
|
||||
for part in self.parts.iter() {
|
||||
buf.push_str(part.eval(ctx)?.coerce_to_string()?.as_ref().unwrap_string());
|
||||
buf.push_str(&part.eval(ctx)?.force_string_no_ctx()?);
|
||||
}
|
||||
Ok(Value::String(buf))
|
||||
}
|
||||
@@ -361,7 +340,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Var {
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
ctx.lookup_with(&self.sym)
|
||||
.ok_or_else(|| {
|
||||
Error::EvalError(format!("undefined variable '{}'", format_symbol(&self.sym)))
|
||||
Error::eval_error(format!("undefined variable '{}'", format_symbol(&self.sym)))
|
||||
})
|
||||
.map(|val| val.clone())
|
||||
}
|
||||
|
||||
@@ -5,14 +5,16 @@ use std::fmt::Debug;
|
||||
use std::rc::Rc;
|
||||
|
||||
use derive_more::Constructor;
|
||||
use hashbrown::hash_map::Entry;
|
||||
use hashbrown::HashMap;
|
||||
use hashbrown::hash_map::Entry;
|
||||
use itertools::Itertools;
|
||||
|
||||
use nixjit_error::{Error, Result};
|
||||
use nixjit_value::Symbol;
|
||||
use nixjit_ir::ExprId;
|
||||
use nixjit_value::{self as p, format_symbol};
|
||||
|
||||
use crate::EvalContext;
|
||||
|
||||
use super::Value;
|
||||
|
||||
/// A wrapper around a `HashMap` representing a Nix attribute set.
|
||||
@@ -20,7 +22,7 @@ use super::Value;
|
||||
/// It uses `#[repr(transparent)]` to ensure it has the same memory layout
|
||||
/// as `HashMap<String, Value>`.
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Constructor, PartialEq)]
|
||||
#[derive(Clone, Constructor)]
|
||||
pub struct AttrSet {
|
||||
data: HashMap<String, Value>,
|
||||
}
|
||||
@@ -31,9 +33,9 @@ impl Debug for AttrSet {
|
||||
write!(f, "{{ ")?;
|
||||
for (k, v) in self.data.iter() {
|
||||
match v {
|
||||
List(_) => write!(f, "{k:?} = [ ... ]; ")?,
|
||||
AttrSet(_) => write!(f, "{k:?} = {{ ... }}; ")?,
|
||||
v => write!(f, "{k:?} = {v:?}; ")?,
|
||||
List(_) => write!(f, "{} = [ ... ]; ", format_symbol(k))?,
|
||||
AttrSet(_) => write!(f, "{} = {{ ... }}; ", format_symbol(k))?,
|
||||
v => write!(f, "{} = {v:?}; ", format_symbol(k))?,
|
||||
}
|
||||
}
|
||||
write!(f, "}}")
|
||||
@@ -69,7 +71,7 @@ impl AttrSet {
|
||||
/// 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!(
|
||||
Entry::Occupied(occupied) => Err(Error::eval_error(format!(
|
||||
"attribute '{}' already defined",
|
||||
format_symbol(occupied.key())
|
||||
))),
|
||||
@@ -80,30 +82,32 @@ impl AttrSet {
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs a deep selection of an attribute from a nested set.
|
||||
///
|
||||
/// It traverses the attribute path and returns the final value, or an error
|
||||
/// if any intermediate attribute does not exist or is not a set.
|
||||
pub fn select(
|
||||
pub fn select(&self, name: &str, ctx: &mut impl EvalContext) -> Result<Value> {
|
||||
self.data
|
||||
.get(name)
|
||||
.cloned()
|
||||
.map(|attr| match attr {
|
||||
Value::Thunk(id) => ctx.eval(id),
|
||||
val => Ok(val),
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
Error::eval_error(format!("attribute '{}' not found", format_symbol(name)))
|
||||
})?
|
||||
}
|
||||
|
||||
pub fn select_or(
|
||||
&self,
|
||||
mut path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||
name: &str,
|
||||
default: ExprId,
|
||||
ctx: &mut impl EvalContext,
|
||||
) -> Result<Value> {
|
||||
let mut data = &self.data;
|
||||
let last = path.nth_back(0).unwrap();
|
||||
for item in path {
|
||||
let item = item?;
|
||||
let Some(Value::AttrSet(attrs)) = data.get(&item) else {
|
||||
return Err(Error::EvalError(format!(
|
||||
"attribute '{}' not found",
|
||||
format_symbol(item)
|
||||
)));
|
||||
};
|
||||
data = attrs.as_inner();
|
||||
}
|
||||
let last = last?;
|
||||
data.get(&last).cloned().ok_or_else(|| {
|
||||
Error::EvalError(format!("attribute '{}' not found", Symbol::from(last)))
|
||||
})
|
||||
self.data
|
||||
.get(name)
|
||||
.map(|attr| match attr {
|
||||
&Value::Thunk(id) => ctx.eval(id),
|
||||
val => Ok(val.clone()),
|
||||
})
|
||||
.unwrap_or_else(|| ctx.eval(default))
|
||||
}
|
||||
|
||||
/// Checks if an attribute path exists within the set.
|
||||
@@ -114,16 +118,14 @@ impl AttrSet {
|
||||
let mut data = &self.data;
|
||||
let last = path.nth_back(0).unwrap();
|
||||
for item in path {
|
||||
let Some(Value::AttrSet(attrs)) =
|
||||
data.get(item.unwrap().coerce_to_string()?.as_ref().unwrap_string())
|
||||
let Some(Value::AttrSet(attrs)) = data.get(&item.unwrap().force_string_no_ctx()?)
|
||||
else {
|
||||
return Ok(Value::Bool(false));
|
||||
};
|
||||
data = attrs.as_inner();
|
||||
}
|
||||
Ok(Value::Bool(
|
||||
data.get(last.unwrap().coerce_to_string()?.as_ref().unwrap_string())
|
||||
.is_some(),
|
||||
data.get(&last.unwrap().force_string_no_ctx()?).is_some(),
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
25
evaluator/nixjit_eval/src/value/closure.rs
Normal file
25
evaluator/nixjit_eval/src/value/closure.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
//! Defines the runtime representation of a partially applied function.
|
||||
use std::rc::Rc;
|
||||
|
||||
use derive_more::Constructor;
|
||||
|
||||
use nixjit_error::Result;
|
||||
use nixjit_ir::ExprId;
|
||||
|
||||
use super::Value;
|
||||
use crate::EvalContext;
|
||||
|
||||
pub type StackFrame = smallvec::SmallVec<[Value; 5]>;
|
||||
|
||||
#[derive(Debug, Clone, Constructor)]
|
||||
pub struct Closure {
|
||||
pub body: ExprId,
|
||||
pub frame: StackFrame,
|
||||
}
|
||||
|
||||
impl Closure {
|
||||
pub fn call<Ctx: EvalContext>(self: Rc<Self>, arg: Option<Value>, ctx: &mut Ctx) -> Result<Value> {
|
||||
let Self { body: func, frame } = Rc::unwrap_or_clone(self);
|
||||
ctx.call(func, arg, frame)
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
//! Defines the runtime representation of a partially applied function.
|
||||
use std::rc::Rc;
|
||||
|
||||
use derive_more::Constructor;
|
||||
|
||||
use nixjit_error::Result;
|
||||
use nixjit_ir::ExprId;
|
||||
|
||||
use super::Value;
|
||||
use crate::EvalContext;
|
||||
|
||||
/// Represents a partially applied user-defined function.
|
||||
///
|
||||
/// This struct captures the state of a function that has received some, but not
|
||||
/// all, of its expected arguments.
|
||||
#[derive(Debug, Clone, Constructor)]
|
||||
pub struct FuncApp {
|
||||
/// The expression ID of the function body to be executed.
|
||||
pub body: ExprId,
|
||||
/// The arguments that have already been applied to the function.
|
||||
pub args: Vec<Value>,
|
||||
/// The lexical scope (stack frame) captured at the time of the initial call.
|
||||
pub frame: Vec<Value>,
|
||||
}
|
||||
|
||||
impl FuncApp {
|
||||
/// Applies more arguments to a partially applied function.
|
||||
///
|
||||
/// It takes an iterator of new arguments, appends them to the existing ones,
|
||||
/// and re-evaluates the function body within its captured environment.
|
||||
pub fn call<Ctx: EvalContext>(
|
||||
self: &mut Rc<Self>,
|
||||
mut iter: impl Iterator<Item = Result<Value>> + ExactSizeIterator,
|
||||
ctx: &mut Ctx,
|
||||
) -> Result<Value> {
|
||||
let FuncApp {
|
||||
body: expr,
|
||||
args,
|
||||
frame,
|
||||
} = Rc::make_mut(self);
|
||||
let mut val;
|
||||
let mut args = core::mem::take(args);
|
||||
args.push(iter.next().unwrap()?);
|
||||
let (ret_args, ret) = ctx.with_args_env(args, |ctx| ctx.eval(*expr));
|
||||
args = ret_args;
|
||||
val = ret?;
|
||||
loop {
|
||||
if !matches!(val, Value::Func(_) | Value::FuncApp(_)) {
|
||||
break;
|
||||
}
|
||||
let Some(arg) = iter.next() else {
|
||||
break;
|
||||
};
|
||||
args.push(arg?);
|
||||
if let Value::Func(expr) = val {
|
||||
let (ret_args, ret) = ctx.with_args_env(args, |ctx| ctx.eval(expr));
|
||||
args = ret_args;
|
||||
val = ret?;
|
||||
} else if let Value::FuncApp(func) = val {
|
||||
let mut func = Rc::unwrap_or_clone(func);
|
||||
func.args.push(args.pop().unwrap());
|
||||
let (ret_args, ret) = ctx.with_args_env(func.args, |ctx| ctx.eval(func.body));
|
||||
args = ret_args;
|
||||
val = ret?;
|
||||
}
|
||||
}
|
||||
Ok(val)
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,12 @@
|
||||
use std::fmt::Debug;
|
||||
use std::ops::Deref;
|
||||
|
||||
use hashbrown::HashSet;
|
||||
|
||||
use nixjit_error::{Error, Result};
|
||||
use nixjit_value::List as PubList;
|
||||
use nixjit_value::Value as PubValue;
|
||||
|
||||
use crate::EvalContext;
|
||||
|
||||
use super::Value;
|
||||
|
||||
/// A wrapper around a `Vec<Value>` representing a Nix list.
|
||||
@@ -65,6 +66,21 @@ impl List {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn elem_at(&self, idx: usize, ctx: &mut impl EvalContext) -> Result<Value> {
|
||||
self.data
|
||||
.get(idx)
|
||||
.map(|elem| match elem {
|
||||
&Value::Thunk(id) => ctx.eval(id),
|
||||
val => Ok(val.clone()),
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
Error::eval_error(format!(
|
||||
"'builtins.elemAt' called with index {idx} on a list of size {}",
|
||||
self.len()
|
||||
))
|
||||
})?
|
||||
}
|
||||
|
||||
/// Consumes the `List` and returns the inner `Vec<Value>`.
|
||||
pub fn into_inner(self) -> Vec<Value> {
|
||||
self.data
|
||||
|
||||
@@ -4,33 +4,30 @@
|
||||
//! interpreter's runtime. It represents all possible data types that can exist
|
||||
//! during the evaluation of a Nix expression. This is an internal, mutable
|
||||
//! representation, distinct from the public-facing `nixjit_value::Value`.
|
||||
//!
|
||||
//! The module also provides `ValueAsRef` for non-owning references and
|
||||
//! implementations for various operations like arithmetic, comparison, and
|
||||
//! function calls.
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::hash::Hash;
|
||||
use std::rc::Rc;
|
||||
|
||||
use derive_more::TryUnwrap;
|
||||
use derive_more::{IsVariant, Unwrap};
|
||||
use nixjit_ir::{ExprId, PrimOp};
|
||||
use derive_more::{IsVariant, TryInto, TryUnwrap, Unwrap};
|
||||
use nixjit_ir::ExprId;
|
||||
use nixjit_ir::PrimOpId;
|
||||
|
||||
use nixjit_error::{Error, Result};
|
||||
use nixjit_value::Const;
|
||||
use nixjit_value::Value as PubValue;
|
||||
use replace_with::replace_with_and_return;
|
||||
use smallvec::smallvec;
|
||||
|
||||
use crate::EvalContext;
|
||||
|
||||
mod attrset;
|
||||
mod func;
|
||||
mod closure;
|
||||
mod list;
|
||||
mod primop;
|
||||
mod string;
|
||||
|
||||
pub use attrset::*;
|
||||
pub use func::*;
|
||||
pub use attrset::AttrSet;
|
||||
pub use closure::*;
|
||||
pub use list::List;
|
||||
pub use primop::*;
|
||||
|
||||
@@ -40,20 +37,22 @@ pub use primop::*;
|
||||
/// JIT-compiled code. It uses `#[repr(C, u64)]` to ensure a predictable layout,
|
||||
/// with the discriminant serving as a type tag.
|
||||
#[repr(C, u64)]
|
||||
#[derive(IsVariant, Clone, TryUnwrap, Unwrap)]
|
||||
#[derive(IsVariant, Clone, Unwrap, TryUnwrap, TryInto)]
|
||||
#[try_into(owned, ref, ref_mut)]
|
||||
pub enum Value {
|
||||
Int(i64),
|
||||
Float(f64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
Null,
|
||||
Thunk(ExprId),
|
||||
AttrSet(Rc<AttrSet>),
|
||||
List(Rc<List>),
|
||||
PrimOp(PrimOp),
|
||||
PrimOpApp(Rc<PrimOpApp>),
|
||||
Func(ExprId),
|
||||
FuncApp(Rc<FuncApp>),
|
||||
Int(i64) = Self::INT,
|
||||
Float(f64) = Self::FLOAT,
|
||||
Bool(bool) = Self::BOOL,
|
||||
String(String) = Self::STRING,
|
||||
Null = Self::NULL,
|
||||
Thunk(ExprId) = Self::THUNK,
|
||||
ClosureThunk(Rc<Closure>) = Self::CLOSURE_THUNK,
|
||||
AttrSet(Rc<AttrSet>) = Self::ATTRSET,
|
||||
List(Rc<List>) = Self::LIST,
|
||||
PrimOp(PrimOpId) = Self::PRIMOP,
|
||||
PrimOpApp(Rc<PrimOpApp>) = Self::PRIMOP_APP,
|
||||
Closure(Rc<Closure>) = Self::CLOSURE,
|
||||
Blackhole,
|
||||
}
|
||||
|
||||
impl Debug for Value {
|
||||
@@ -64,26 +63,15 @@ impl Debug for Value {
|
||||
Float(x) => write!(f, "{x}"),
|
||||
Bool(x) => write!(f, "{x}"),
|
||||
Null => write!(f, "null"),
|
||||
String(x) => write!(f, "{x}"),
|
||||
String(x) => write!(f, "{x:?}"),
|
||||
AttrSet(x) => write!(f, "{x:?}"),
|
||||
List(x) => write!(f, "{x:?}"),
|
||||
Thunk(thunk) => write!(f, "<THUNK {thunk:?}>"),
|
||||
Func(func) => write!(f, "<LAMBDA {func:?}>"),
|
||||
FuncApp(func) => write!(f, "<LAMBDA-APP {:?}>", func.body),
|
||||
PrimOp(primop) => write!(f, "<PRIMOP {}>", primop.name),
|
||||
PrimOpApp(primop) => write!(f, "<PRIMOP-APP {}>", primop.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for Value {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
use Value::*;
|
||||
std::mem::discriminant(self).hash(state);
|
||||
match self {
|
||||
AttrSet(x) => Rc::as_ptr(x).hash(state),
|
||||
List(x) => x.as_ptr().hash(state),
|
||||
_ => 0.hash(state),
|
||||
ClosureThunk(_) => write!(f, "<THUNK>"),
|
||||
Closure(func) => write!(f, "<LAMBDA-APP {:?}>", func.body),
|
||||
PrimOp(_) => write!(f, "<PRIMOP>"),
|
||||
PrimOpApp(_) => write!(f, "<PRIMOP-APP>"),
|
||||
Blackhole => write!(f, "<BLACKHOLE>"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,13 +83,12 @@ impl Value {
|
||||
pub const STRING: u64 = 3;
|
||||
pub const NULL: u64 = 4;
|
||||
pub const THUNK: u64 = 5;
|
||||
pub const ATTRSET: u64 = 6;
|
||||
pub const LIST: u64 = 7;
|
||||
pub const CATCHABLE: u64 = 8;
|
||||
pub const CLOSURE_THUNK: u64 = 6;
|
||||
pub const ATTRSET: u64 = 7;
|
||||
pub const LIST: u64 = 8;
|
||||
pub const PRIMOP: u64 = 9;
|
||||
pub const PARTIAL_PRIMOP: u64 = 10;
|
||||
pub const FUNC: u64 = 11;
|
||||
pub const PARTIAL_FUNC: u64 = 12;
|
||||
pub const PRIMOP_APP: u64 = 10;
|
||||
pub const CLOSURE: u64 = 11;
|
||||
|
||||
fn eq_impl(&self, other: &Self) -> bool {
|
||||
use Value::*;
|
||||
@@ -120,59 +107,6 @@ impl Value {
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Value {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
use Value::*;
|
||||
match (self, other) {
|
||||
(AttrSet(a), AttrSet(b)) => Rc::as_ptr(a).eq(&Rc::as_ptr(b)),
|
||||
(List(a), List(b)) => a.as_ptr().eq(&b.as_ptr()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Value {}
|
||||
|
||||
/// A non-owning reference to a `Value`.
|
||||
///
|
||||
/// This is used to avoid unnecessary cloning when inspecting values.
|
||||
#[derive(IsVariant, TryUnwrap, Unwrap, Clone)]
|
||||
pub enum ValueAsRef<'v> {
|
||||
Int(i64),
|
||||
Float(f64),
|
||||
Bool(bool),
|
||||
String(&'v String),
|
||||
Null,
|
||||
Thunk(&'v ExprId),
|
||||
AttrSet(&'v AttrSet),
|
||||
List(&'v List),
|
||||
PrimOp(&'v PrimOp),
|
||||
PartialPrimOp(&'v PrimOpApp),
|
||||
Func(&'v ExprId),
|
||||
PartialFunc(&'v FuncApp),
|
||||
}
|
||||
|
||||
impl Value {
|
||||
/// Returns a `ValueAsRef`, providing a non-owning view of the value.
|
||||
pub fn as_ref(&self) -> ValueAsRef<'_> {
|
||||
use Value::*;
|
||||
use ValueAsRef as R;
|
||||
match self {
|
||||
Int(x) => R::Int(*x),
|
||||
Float(x) => R::Float(*x),
|
||||
Bool(x) => R::Bool(*x),
|
||||
String(x) => R::String(x),
|
||||
Null => R::Null,
|
||||
Thunk(x) => R::Thunk(x),
|
||||
AttrSet(x) => R::AttrSet(x),
|
||||
List(x) => R::List(x),
|
||||
PrimOp(x) => R::PrimOp(x),
|
||||
PrimOpApp(x) => R::PartialPrimOp(x),
|
||||
Func(x) => R::Func(x),
|
||||
FuncApp(x) => R::PartialFunc(x),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Value {
|
||||
/// Returns the name of the value's type.
|
||||
pub fn typename(&self) -> &'static str {
|
||||
@@ -184,82 +118,72 @@ impl Value {
|
||||
String(_) => "string",
|
||||
Null => "null",
|
||||
Thunk(_) => "thunk",
|
||||
ClosureThunk(_) => "thunk",
|
||||
AttrSet(_) => "set",
|
||||
List(_) => "list",
|
||||
PrimOp(_) => "lambda",
|
||||
PrimOpApp(_) => "lambda",
|
||||
Func(_) => "lambda",
|
||||
FuncApp(..) => "lambda",
|
||||
Closure(..) => "lambda",
|
||||
Blackhole => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn force(&mut self, ctx: &mut impl EvalContext) -> Result<()> {
|
||||
let map = |result| match result {
|
||||
Ok(ok) => (Ok(()), ok),
|
||||
Err(err) => (Err(err), Value::Null),
|
||||
};
|
||||
replace_with_and_return(
|
||||
self,
|
||||
|| Value::Null,
|
||||
|val| match val {
|
||||
Value::Thunk(id) => map(ctx.eval(id)),
|
||||
Value::ClosureThunk(thunk) => map(thunk.call(None, ctx)),
|
||||
val => (Ok(()), val),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Performs a function call on the `Value`.
|
||||
///
|
||||
/// This method handles calling functions, primops, and their partially
|
||||
/// applied variants. It manages argument application and delegates to the
|
||||
/// `EvalContext` for the actual execution.
|
||||
pub fn call<Ctx: EvalContext>(
|
||||
&mut self,
|
||||
mut iter: impl Iterator<Item = Result<Value>> + ExactSizeIterator,
|
||||
ctx: &mut Ctx,
|
||||
) -> Result<()> {
|
||||
pub fn call<Ctx: EvalContext>(&mut self, arg: Value, ctx: &mut Ctx) -> Result<()> {
|
||||
use Value::*;
|
||||
*self = match self {
|
||||
&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<_>>()?,
|
||||
))))
|
||||
} else {
|
||||
ctx.call_primop(primop.id, iter.collect::<Result<_>>()?)
|
||||
}
|
||||
}
|
||||
&mut Func(expr) => {
|
||||
let mut val;
|
||||
let mut args = Vec::with_capacity(iter.len());
|
||||
args.push(iter.next().unwrap()?);
|
||||
let (ret_args, ret) = ctx.with_args_env(args, |ctx| ctx.eval(expr));
|
||||
args = ret_args;
|
||||
val = ret?;
|
||||
loop {
|
||||
if !matches!(val, Value::Func(_) | Value::FuncApp(_)) {
|
||||
break;
|
||||
}
|
||||
let Some(arg) = iter.next() else {
|
||||
break;
|
||||
};
|
||||
args.push(arg?);
|
||||
if let Value::Func(expr) = val {
|
||||
let (ret_args, ret) = ctx.with_args_env(args, |ctx| ctx.eval(expr));
|
||||
args = ret_args;
|
||||
val = ret?;
|
||||
} else if let Value::FuncApp(func) = val {
|
||||
let mut func = Rc::unwrap_or_clone(func);
|
||||
func.args.push(args.pop().unwrap());
|
||||
let (ret_args, ret) =
|
||||
ctx.with_args_env(func.args, |ctx| ctx.eval(func.body));
|
||||
args = ret_args;
|
||||
val = ret?;
|
||||
let map = |result| match result {
|
||||
Ok(ok) => (Ok(()), ok),
|
||||
Err(err) => (Err(err), Null),
|
||||
};
|
||||
replace_with_and_return(
|
||||
self,
|
||||
|| Null,
|
||||
|func| match func {
|
||||
PrimOp(id) => {
|
||||
let arity = ctx.get_primop_arity(id);
|
||||
if arity == 1 {
|
||||
map(ctx.call_primop(id, smallvec![arg]))
|
||||
} else {
|
||||
(
|
||||
Ok(()),
|
||||
Value::PrimOpApp(Rc::new(self::PrimOpApp::new(
|
||||
arity - 1,
|
||||
id,
|
||||
smallvec![arg],
|
||||
))),
|
||||
)
|
||||
}
|
||||
}
|
||||
Ok(val)
|
||||
}
|
||||
PrimOpApp(func) => func.call(iter.collect::<Result<_>>()?, ctx),
|
||||
FuncApp(func) => func.call(iter, ctx),
|
||||
_ => Err(Error::EvalError(
|
||||
"attempt to call something which is not a function but ...".to_string(),
|
||||
)),
|
||||
}?;
|
||||
Ok(())
|
||||
PrimOpApp(func) => map(func.call(arg, ctx)),
|
||||
Closure(func) => map(func.call(Some(arg), ctx)),
|
||||
_ => (
|
||||
Err(Error::eval_error(
|
||||
"attempt to call something which is not a function but ...".to_string(),
|
||||
)),
|
||||
Null,
|
||||
),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn not(&mut self) -> Result<()> {
|
||||
@@ -269,7 +193,10 @@ impl Value {
|
||||
*self = Bool(!bool);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(Error::EvalError(format!("expected a boolean but found {}", self.typename()))),
|
||||
_ => Err(Error::eval_error(format!(
|
||||
"expected a boolean but found {}",
|
||||
self.typename()
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,7 +207,10 @@ impl Value {
|
||||
*self = Bool(a && b);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(Error::EvalError(format!("expected a boolean but found {}", self.typename()))),
|
||||
_ => Err(Error::eval_error(format!(
|
||||
"expected a boolean but found {}",
|
||||
self.typename()
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +221,10 @@ impl Value {
|
||||
*self = Bool(a || b);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(Error::EvalError(format!("expected a boolean but found {}", self.typename()))),
|
||||
_ => Err(Error::eval_error(format!(
|
||||
"expected a boolean but found {}",
|
||||
self.typename()
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,7 +243,13 @@ 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(),
|
||||
(a, b) => return Err(Error::EvalError(format!("cannot compare {} with {}", a.typename(), b.typename()))),
|
||||
(a, b) => {
|
||||
return Err(Error::eval_error(format!(
|
||||
"cannot compare {} with {}",
|
||||
a.typename(),
|
||||
b.typename()
|
||||
)));
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
@@ -320,7 +259,12 @@ impl Value {
|
||||
*self = match &*self {
|
||||
Int(int) => Int(-int),
|
||||
Float(float) => Float(-float),
|
||||
_ => return Err(Error::EvalError(format!("expected an integer but found {}", self.typename())))
|
||||
_ => {
|
||||
return Err(Error::eval_error(format!(
|
||||
"expected an integer but found {}",
|
||||
self.typename()
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
@@ -336,7 +280,13 @@ impl Value {
|
||||
(&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())))
|
||||
(a, b) => {
|
||||
return Err(Error::eval_error(format!(
|
||||
"cannot add {} to {}",
|
||||
a.typename(),
|
||||
b.typename()
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
@@ -348,7 +298,13 @@ 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),
|
||||
(a, b) => return Err(Error::EvalError(format!("cannot multiply {} with {}", a.typename(), b.typename())))
|
||||
(a, b) => {
|
||||
return Err(Error::eval_error(format!(
|
||||
"cannot multiply {} with {}",
|
||||
a.typename(),
|
||||
b.typename()
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
@@ -356,15 +312,21 @@ impl Value {
|
||||
pub fn div(&mut self, other: Self) -> Result<()> {
|
||||
use Value::*;
|
||||
*self = match (&*self, other) {
|
||||
(_, Int(0)) => return Err(Error::EvalError("division by zero".to_string())),
|
||||
(_, Int(0)) => return Err(Error::eval_error("division by zero".to_string())),
|
||||
(_, Float(0.)) => {
|
||||
return Err(Error::EvalError("division by zero".to_string()));
|
||||
return Err(Error::eval_error("division by zero".to_string()));
|
||||
}
|
||||
(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),
|
||||
(a, b) => return Err(Error::EvalError(format!("cannot divide {} with {}", a.typename(), b.typename())))
|
||||
(a, b) => {
|
||||
return Err(Error::eval_error(format!(
|
||||
"cannot divide {} with {}",
|
||||
a.typename(),
|
||||
b.typename()
|
||||
)));
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
@@ -376,8 +338,15 @@ impl Value {
|
||||
Rc::make_mut(a).concat(&b);
|
||||
Ok(())
|
||||
}
|
||||
(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()))), }
|
||||
(List(_), b) => Err(Error::eval_error(format!(
|
||||
"expected a list but found {}",
|
||||
b.typename()
|
||||
))),
|
||||
(a, _) => Err(Error::eval_error(format!(
|
||||
"expected a list but found {}",
|
||||
a.typename()
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(mut self: &mut Self, other: Self) -> Result<()> {
|
||||
@@ -387,20 +356,23 @@ impl Value {
|
||||
Rc::make_mut(a).update(&b);
|
||||
Ok(())
|
||||
}
|
||||
(AttrSet(_), other) => Err(Error::EvalError(format!("expected a set but found {}", other.typename()))),
|
||||
_ => Err(Error::EvalError(format!("expected a set but found {}", self.typename()))),
|
||||
(AttrSet(_), other) => Err(Error::eval_error(format!(
|
||||
"expected a set but found {}",
|
||||
other.typename()
|
||||
))),
|
||||
_ => Err(Error::eval_error(format!(
|
||||
"expected a set but found {}",
|
||||
self.typename()
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn select(
|
||||
&mut self,
|
||||
path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||
) -> Result<()> {
|
||||
pub fn select(&mut self, name: &str, ctx: &mut impl EvalContext) -> Result<()> {
|
||||
use Value::*;
|
||||
let val = match self {
|
||||
AttrSet(attrs) => attrs.select(path),
|
||||
_ => Err(Error::EvalError(format!(
|
||||
"can not select from {:?}",
|
||||
AttrSet(attrs) => attrs.select(name, ctx),
|
||||
_ => Err(Error::eval_error(format!(
|
||||
"expected a set but found {}",
|
||||
self.typename()
|
||||
))),
|
||||
}?;
|
||||
@@ -408,17 +380,18 @@ impl Value {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn select_with_default(
|
||||
pub fn select_or<Ctx: EvalContext>(
|
||||
&mut self,
|
||||
path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||
default: Self,
|
||||
name: &str,
|
||||
default: ExprId,
|
||||
ctx: &mut Ctx,
|
||||
) -> Result<()> {
|
||||
use Value::*;
|
||||
let val = match self {
|
||||
AttrSet(attrs) => attrs.select(path).unwrap_or(default),
|
||||
AttrSet(attrs) => attrs.select_or(name, default, ctx)?,
|
||||
_ => {
|
||||
return Err(Error::EvalError(format!(
|
||||
"can not select from {:?}",
|
||||
return Err(Error::eval_error(format!(
|
||||
"expected a set but found {}",
|
||||
self.typename()
|
||||
)));
|
||||
}
|
||||
@@ -427,10 +400,7 @@ impl Value {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn has_attr(
|
||||
&mut self,
|
||||
path: impl DoubleEndedIterator<Item = Result<Value>>,
|
||||
) -> Result<()> {
|
||||
pub fn has_attr(&mut self, path: impl DoubleEndedIterator<Item = Result<Value>>) -> Result<()> {
|
||||
use Value::*;
|
||||
if let AttrSet(attrs) = self {
|
||||
let val = attrs.has_attr(path)?;
|
||||
@@ -441,40 +411,36 @@ impl Value {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn coerce_to_string(&mut self) -> Result<&mut Self> {
|
||||
pub fn force_string_no_ctx(self) -> Result<String> {
|
||||
use Value::*;
|
||||
if let String(_) = self {
|
||||
Ok(self)
|
||||
if let String(string) = self {
|
||||
Ok(string)
|
||||
} else {
|
||||
Err(Error::EvalError(format!("cannot coerce {} to string", self.typename())))
|
||||
Err(Error::eval_error(format!(
|
||||
"cannot coerce {} to string",
|
||||
self.typename()
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the internal `Value` to its public-facing, serializable
|
||||
/// representation from the `nixjit_value` crate.
|
||||
///
|
||||
/// 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) -> PubValue {
|
||||
use Value::*;
|
||||
match self {
|
||||
AttrSet(attrs) => {
|
||||
Rc::unwrap_or_clone(attrs).to_public()
|
||||
}
|
||||
List(list) => {
|
||||
Rc::unwrap_or_clone(list.clone()).to_public()
|
||||
}
|
||||
AttrSet(attrs) => Rc::unwrap_or_clone(attrs).to_public(),
|
||||
List(list) => Rc::unwrap_or_clone(list.clone()).to_public(),
|
||||
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),
|
||||
PrimOpApp(primop) => PubValue::PrimOpApp(primop.name),
|
||||
Func(_) => PubValue::Func,
|
||||
FuncApp(..) => PubValue::Func,
|
||||
ClosureThunk(_) => PubValue::Thunk,
|
||||
PrimOp(_) => PubValue::PrimOp,
|
||||
PrimOpApp(_) => PubValue::PrimOpApp,
|
||||
Closure(..) => PubValue::Func,
|
||||
Blackhole => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,20 +10,20 @@ use nixjit_ir::PrimOpId;
|
||||
use super::Value;
|
||||
use crate::EvalContext;
|
||||
|
||||
pub type Args = smallvec::SmallVec<[Value; 2]>;
|
||||
|
||||
/// Represents a partially applied primitive operation (builtin function).
|
||||
///
|
||||
/// This struct holds the state of a primop that has received some, but not
|
||||
/// all, of its required arguments.
|
||||
#[derive(Debug, Clone, Constructor)]
|
||||
pub struct PrimOpApp {
|
||||
/// The name of the primitive operation.
|
||||
pub name: &'static str,
|
||||
/// The number of remaining arguments the primop expects.
|
||||
arity: usize,
|
||||
/// The unique ID of the primop.
|
||||
id: PrimOpId,
|
||||
/// The arguments that have already been applied.
|
||||
args: Vec<Value>,
|
||||
args: Args,
|
||||
}
|
||||
|
||||
impl PrimOpApp {
|
||||
@@ -32,27 +32,15 @@ impl PrimOpApp {
|
||||
/// If enough arguments are provided to satisfy the primop's arity, it is
|
||||
/// executed. Otherwise, it returns a new `PrimOpApp` with the combined
|
||||
/// arguments.
|
||||
pub fn call(
|
||||
self: &mut Rc<Self>,
|
||||
mut args: Vec<Value>,
|
||||
ctx: &mut impl EvalContext,
|
||||
) -> Result<Value> {
|
||||
if self.arity < args.len() {
|
||||
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 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))
|
||||
pub fn call(self: Rc<Self>, arg: Value, ctx: &mut impl EvalContext) -> Result<Value> {
|
||||
let mut primop = Rc::unwrap_or_clone(self);
|
||||
if primop.arity == 1 {
|
||||
primop.args.push(arg);
|
||||
ctx.call_primop(primop.id, primop.args)
|
||||
} else {
|
||||
Ok(Value::PrimOpApp(self.clone()))
|
||||
primop.args.push(arg);
|
||||
primop.arity -= 1;
|
||||
Ok(Value::PrimOpApp(primop.into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user