chore: comment
This commit is contained in:
@@ -1,3 +1,12 @@
|
||||
//! This module defines the core traits and logic for evaluating the LIR.
|
||||
//!
|
||||
//! The central components are:
|
||||
//! - `EvalContext`: A trait that defines the environment and operations needed for evaluation.
|
||||
//! It manages the evaluation stack, scopes, and primop calls.
|
||||
//! - `Evaluate`: A trait implemented by LIR nodes to define how they are evaluated.
|
||||
//! - `Value`: An enum representing all possible values during evaluation. This is an
|
||||
//! internal representation, distinct from the public-facing `nixjit_value::Value`.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use hashbrown::HashMap;
|
||||
@@ -5,37 +14,59 @@ 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};
|
||||
use nixjit_value::{Const, Symbol, format_symbol};
|
||||
|
||||
pub use crate::value::*;
|
||||
|
||||
mod value;
|
||||
|
||||
/// A trait defining the context in which LIR expressions are evaluated.
|
||||
pub trait EvalContext: Sized {
|
||||
/// Evaluates an expression by its ID.
|
||||
fn eval(&mut self, expr: &ExprId) -> Result<Value>;
|
||||
|
||||
/// Enters a `with` scope for the duration of a closure's execution.
|
||||
fn with_with_env<T>(
|
||||
&mut self,
|
||||
namespace: Rc<HashMap<String, Value>>,
|
||||
f: impl FnOnce(&mut Self) -> T,
|
||||
) -> T;
|
||||
fn with_args_env<T>(&mut self, args: Vec<Value>, f: impl FnOnce(&mut Self) -> T) -> (Vec<Value>, 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 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>;
|
||||
}
|
||||
|
||||
/// A trait for types that can be evaluated within an `EvalContext`.
|
||||
pub trait Evaluate<Ctx: EvalContext> {
|
||||
/// Performs the evaluation.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value>;
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ExprId {
|
||||
/// Evaluating an `ExprId` simply delegates to the context.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
ctx.eval(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for lir::Lir {
|
||||
/// Evaluates an LIR node by dispatching to the specific implementation for its variant.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
use lir::Lir::*;
|
||||
match self {
|
||||
@@ -63,6 +94,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for lir::Lir {
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::AttrSet {
|
||||
/// Evaluates an `AttrSet` by evaluating all its static and dynamic attributes.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
let mut attrs = AttrSet::new(
|
||||
self.stcs
|
||||
@@ -79,24 +111,26 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::AttrSet {
|
||||
let v_eval_result = v.eval(ctx)?;
|
||||
attrs.push_attr(k.unwrap_string(), v_eval_result);
|
||||
}
|
||||
let result = Value::AttrSet(attrs.into()).ok();
|
||||
Ok(result.unwrap())
|
||||
let result = Value::AttrSet(attrs.into());
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::List {
|
||||
/// Evaluates a `List` by evaluating all its items.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
let items = self
|
||||
.items
|
||||
.iter()
|
||||
.map(|val| val.eval(ctx))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let result = Value::List(List::from(items).into()).ok();
|
||||
Ok(result.unwrap())
|
||||
let result = Value::List(List::from(items).into());
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::HasAttr {
|
||||
/// Evaluates a `HasAttr` by evaluating the LHS and the attribute path, then performing the check.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
use ir::Attr::*;
|
||||
let mut val = self.lhs.eval(ctx)?;
|
||||
@@ -110,12 +144,12 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::HasAttr {
|
||||
}
|
||||
})
|
||||
}))?;
|
||||
let result = val.ok();
|
||||
Ok(result.unwrap())
|
||||
Ok(val)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::BinOp {
|
||||
/// Evaluates a `BinOp` by evaluating the LHS and RHS, then performing the operation.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
use ir::BinOpKind::*;
|
||||
let mut lhs = self.lhs.eval(ctx)?;
|
||||
@@ -166,6 +200,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::BinOp {
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::UnOp {
|
||||
/// Evaluates a `UnOp` by evaluating the RHS and performing the operation.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
use ir::UnOpKind::*;
|
||||
let mut rhs = self.rhs.eval(ctx)?;
|
||||
@@ -182,6 +217,8 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::UnOp {
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Select {
|
||||
/// Evaluates a `Select` by evaluating the expression, the path, and the default value (if any),
|
||||
/// then performing the selection.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
use ir::Attr::*;
|
||||
let mut val = self.expr.eval(ctx)?;
|
||||
@@ -212,18 +249,20 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Select {
|
||||
})
|
||||
}))?;
|
||||
}
|
||||
let result = val.ok();
|
||||
Ok(result.unwrap())
|
||||
Ok(val)
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
// TODO: Error Handling
|
||||
let cond = self.cond.eval(ctx)?;
|
||||
let cond = cond
|
||||
.try_unwrap_bool()
|
||||
.map_err(|_| Error::EvalError(format!("expected a boolean but found ...")))?;
|
||||
let cond = cond.as_ref().try_unwrap_bool().map_err(|_| {
|
||||
Error::EvalError(format!(
|
||||
"if-condition must be a boolean, but got {}",
|
||||
cond.typename()
|
||||
))
|
||||
})?;
|
||||
|
||||
if cond {
|
||||
self.consq.eval(ctx)
|
||||
@@ -234,27 +273,27 @@ 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)?;
|
||||
// FIXME: ?
|
||||
let ctx_mut = unsafe { &mut *(ctx as *mut Ctx) };
|
||||
func.call(
|
||||
self.args
|
||||
.iter()
|
||||
.map(|arg| arg.eval(ctx)),
|
||||
ctx_mut,
|
||||
)?;
|
||||
Ok(func.ok().unwrap())
|
||||
func.call(self.args.iter().map(|arg| arg.eval(ctx)), ctx_mut)?;
|
||||
Ok(func)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::With {
|
||||
/// Evaluates a `With` by evaluating the namespace, entering a `with` scope,
|
||||
/// and then evaluating the body.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
let namespace = self.namespace.eval(ctx)?;
|
||||
let typename = namespace.typename();
|
||||
ctx.with_with_env(
|
||||
namespace
|
||||
.try_unwrap_attr_set()
|
||||
.map_err(|_| Error::EvalError(format!("expected a set but found ...")))?
|
||||
.map_err(|_| {
|
||||
Error::EvalError(format!("'with' expects a set, but got {}", typename))
|
||||
})?
|
||||
.into_inner(),
|
||||
|ctx| self.expr.eval(ctx),
|
||||
)
|
||||
@@ -262,20 +301,27 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::With {
|
||||
}
|
||||
|
||||
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
|
||||
.try_unwrap_bool()
|
||||
.map_err(|_| Error::EvalError(format!("expected a boolean but found ...")))?;
|
||||
let cond = cond.as_ref().try_unwrap_bool().map_err(|_| {
|
||||
Error::EvalError(format!(
|
||||
"assertion condition must be a boolean, but got {}",
|
||||
cond.typename()
|
||||
))
|
||||
})?;
|
||||
if cond {
|
||||
self.expr.eval(ctx)
|
||||
} else {
|
||||
Err(Error::EvalError("assertion failed".to_string()))
|
||||
Ok(Value::Catchable("assertion failed".to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@@ -283,7 +329,7 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::ConcatStrings {
|
||||
.map(|part| {
|
||||
let mut part = part.eval(ctx)?;
|
||||
part.coerce_to_string();
|
||||
part.ok()
|
||||
Ok(part)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?
|
||||
.into_iter();
|
||||
@@ -292,44 +338,44 @@ impl<Ctx: EvalContext> Evaluate<Ctx> for ir::ConcatStrings {
|
||||
a.concat_string(b);
|
||||
a
|
||||
});
|
||||
Ok(result.ok().unwrap())
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Str {
|
||||
/// Evaluates a `Str` literal into a `Value::String`.
|
||||
fn eval(&self, _: &mut Ctx) -> Result<Value> {
|
||||
let result = Value::String(self.val.clone()).ok();
|
||||
Ok(result.unwrap())
|
||||
Ok(Value::String(self.val.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Const {
|
||||
/// Evaluates a `Const` literal into its corresponding `Value` variant.
|
||||
fn eval(&self, _: &mut Ctx) -> Result<Value> {
|
||||
let result = match self.val {
|
||||
Const::Null => Value::Null,
|
||||
Const::Int(x) => Value::Int(x),
|
||||
Const::Float(x) => Value::Float(x),
|
||||
Const::Bool(x) => Value::Bool(x),
|
||||
}
|
||||
.ok();
|
||||
Ok(result.unwrap())
|
||||
};
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Var {
|
||||
/// Evaluates a `Var` by looking it up in the `with` scope chain.
|
||||
/// This is for variables that could not be resolved statically.
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
ctx.lookup_with(&self.sym)
|
||||
.ok_or_else(|| {
|
||||
Error::EvalError(format!(
|
||||
"variable {} not found",
|
||||
Symbol::from(self.sym.clone())
|
||||
))
|
||||
Error::EvalError(format!("undefined variable '{}'", format_symbol(&self.sym)))
|
||||
})
|
||||
.map(|val| val.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: EvalContext> Evaluate<Ctx> for ir::Path {
|
||||
/// Evaluates a `Path`. (Currently a TODO).
|
||||
fn eval(&self, ctx: &mut Ctx) -> Result<Value> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
//! Defines the runtime representation of an attribute set (a map).
|
||||
|
||||
use core::ops::Deref;
|
||||
use std::fmt::Debug;
|
||||
use std::rc::Rc;
|
||||
@@ -7,12 +9,16 @@ use hashbrown::{HashMap, HashSet};
|
||||
use itertools::Itertools;
|
||||
|
||||
use nixjit_error::{Error, Result};
|
||||
use nixjit_value as p;
|
||||
use nixjit_value::Symbol;
|
||||
use nixjit_value::{self as p, format_symbol};
|
||||
|
||||
use super::Value;
|
||||
use crate::EvalContext;
|
||||
|
||||
/// A wrapper around a `HashMap` representing a Nix attribute set.
|
||||
///
|
||||
/// It uses `#[repr(transparent)]` to ensure it has the same memory layout
|
||||
/// as `HashMap<String, Value>`.
|
||||
#[repr(transparent)]
|
||||
#[derive(Constructor, PartialEq)]
|
||||
pub struct AttrSet {
|
||||
@@ -56,16 +62,24 @@ impl Deref for AttrSet {
|
||||
}
|
||||
|
||||
impl AttrSet {
|
||||
/// Creates a new `AttrSet` with a specified initial capacity.
|
||||
pub fn with_capacity(cap: usize) -> Self {
|
||||
AttrSet {
|
||||
data: HashMap::with_capacity(cap),
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts an attribute, overwriting any existing attribute with the same name.
|
||||
pub fn push_attr_force(&mut self, sym: String, val: Value) {
|
||||
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.
|
||||
pub fn push_attr(&mut self, sym: String, val: Value) {
|
||||
if self.data.get(&sym).is_some() {
|
||||
todo!()
|
||||
@@ -73,6 +87,10 @@ impl AttrSet {
|
||||
self.data.insert(sym, val);
|
||||
}
|
||||
|
||||
/// 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(
|
||||
&self,
|
||||
mut path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||
@@ -84,7 +102,7 @@ impl AttrSet {
|
||||
let Some(Value::AttrSet(attrs)) = data.get(&item) else {
|
||||
return Err(Error::EvalError(format!(
|
||||
"attribute '{}' not found",
|
||||
Symbol::from(item)
|
||||
format_symbol(item)
|
||||
)));
|
||||
};
|
||||
data = attrs.as_inner();
|
||||
@@ -95,6 +113,7 @@ impl AttrSet {
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks if an attribute path exists within the set.
|
||||
pub fn has_attr(
|
||||
&self,
|
||||
mut path: impl DoubleEndedIterator<Item = Result<String>>,
|
||||
@@ -110,24 +129,38 @@ impl AttrSet {
|
||||
Ok(data.get(&last?).is_some())
|
||||
}
|
||||
|
||||
/// Merges another `AttrSet` into this one, with attributes from `other`
|
||||
/// overwriting existing ones. This corresponds to the `//` operator in Nix.
|
||||
pub fn update(&mut self, other: &Self) {
|
||||
for (k, v) in other.data.iter() {
|
||||
self.push_attr_force(k.clone(), v.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reference to the inner `HashMap`.
|
||||
pub fn as_inner(&self) -> &HashMap<String, Value> {
|
||||
&self.data
|
||||
}
|
||||
|
||||
/// Converts an `Rc<AttrSet>` to an `Rc<HashMap<String, Value>>` without allocation.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This is safe because `AttrSet` is `#[repr(transparent)]`.
|
||||
pub fn into_inner(self: Rc<Self>) -> Rc<HashMap<String, Value>> {
|
||||
unsafe { core::mem::transmute(self) }
|
||||
}
|
||||
|
||||
/// Creates an `AttrSet` from a `HashMap`.
|
||||
pub fn from_inner(data: HashMap<String, Value>) -> Self {
|
||||
Self { data }
|
||||
}
|
||||
|
||||
/// Performs a deep equality comparison between two `AttrSet`s.
|
||||
///
|
||||
/// It recursively compares the contents of both sets, ensuring that both keys
|
||||
/// and values are identical. The attributes are sorted before comparison to
|
||||
/// ensure a consistent result.
|
||||
pub fn eq_impl(&self, other: &Self) -> bool {
|
||||
self.data.iter().len() == other.data.iter().len()
|
||||
&& std::iter::zip(
|
||||
@@ -137,6 +170,7 @@ impl AttrSet {
|
||||
.all(|((k1, v1), (k2, v2))| k1 == k2 && v1.eq_impl(v2))
|
||||
}
|
||||
|
||||
/// Converts the `AttrSet` to its public-facing representation.
|
||||
pub fn to_public(&self, seen: &mut HashSet<Value>) -> p::Value {
|
||||
p::Value::AttrSet(p::AttrSet::new(
|
||||
self.data
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
//! Defines the runtime representation of a partially applied function.
|
||||
use std::rc::Rc;
|
||||
|
||||
use derive_more::Constructor;
|
||||
@@ -8,10 +9,17 @@ 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, 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>,
|
||||
}
|
||||
|
||||
@@ -26,6 +34,10 @@ impl Clone for FuncApp {
|
||||
}
|
||||
|
||||
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,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
//! Defines the runtime representation of a list.
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::ops::Deref;
|
||||
|
||||
@@ -9,6 +11,7 @@ use nixjit_value::Value as PubValue;
|
||||
use super::Value;
|
||||
use crate::EvalContext;
|
||||
|
||||
/// A wrapper around a `Vec<Value>` representing a Nix list.
|
||||
#[derive(Default)]
|
||||
pub struct List {
|
||||
data: Vec<Value>,
|
||||
@@ -46,35 +49,43 @@ impl Deref for List {
|
||||
}
|
||||
|
||||
impl List {
|
||||
/// Creates a new, empty `List`.
|
||||
pub fn new() -> Self {
|
||||
List { data: Vec::new() }
|
||||
}
|
||||
|
||||
/// Creates a new `List` with a specified initial capacity.
|
||||
pub fn with_capacity(cap: usize) -> Self {
|
||||
List {
|
||||
data: Vec::with_capacity(cap),
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends an element to the back of the list.
|
||||
pub fn push(&mut self, elem: Value) {
|
||||
self.data.push(elem);
|
||||
}
|
||||
|
||||
/// Appends all elements from another `List` to this one.
|
||||
/// This corresponds to the `++` operator in Nix.
|
||||
pub fn concat(&mut self, other: &Self) {
|
||||
for elem in other.data.iter() {
|
||||
self.data.push(elem.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Consumes the `List` and returns the inner `Vec<Value>`.
|
||||
pub fn into_inner(self) -> Vec<Value> {
|
||||
self.data
|
||||
}
|
||||
|
||||
/// Performs a deep equality comparison between two `List`s.
|
||||
pub fn eq_impl(&self, other: &Self) -> bool {
|
||||
self.len() == other.len()
|
||||
&& core::iter::zip(self.iter(), other.iter()).all(|(a, b)| a.eq_impl(b))
|
||||
}
|
||||
|
||||
/// Converts the `List` to its public-facing representation.
|
||||
pub fn to_public(&self, seen: &mut HashSet<Value>) -> PubValue {
|
||||
PubValue::List(PubList::new(
|
||||
self.data
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
//! Defines the internal representation of values during evaluation.
|
||||
//!
|
||||
//! This module introduces the `Value` enum, which is the cornerstone of the
|
||||
//! 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::process::abort;
|
||||
@@ -26,6 +37,11 @@ pub use func::*;
|
||||
pub use list::List;
|
||||
pub use primop::*;
|
||||
|
||||
/// The internal, C-compatible representation of a Nix value during evaluation.
|
||||
///
|
||||
/// This enum is designed for efficient manipulation within the interpreter and
|
||||
/// 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, TryUnwrap, Unwrap)]
|
||||
pub enum Value {
|
||||
@@ -143,6 +159,9 @@ impl PartialEq for Value {
|
||||
|
||||
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),
|
||||
@@ -161,6 +180,7 @@ pub enum ValueAsRef<'v> {
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -182,10 +202,12 @@ 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::*;
|
||||
match self {
|
||||
@@ -205,6 +227,7 @@ 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,
|
||||
@@ -213,7 +236,16 @@ impl Value {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn call<Ctx: EvalContext>(&mut self, mut iter: impl Iterator<Item = Result<Value>> + ExactSizeIterator, ctx: &mut Ctx) -> Result<()> {
|
||||
/// 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<()> {
|
||||
use Value::*;
|
||||
*self = match self {
|
||||
&mut PrimOp(func) => {
|
||||
@@ -254,7 +286,8 @@ impl Value {
|
||||
} 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));
|
||||
let (ret_args, ret) =
|
||||
ctx.with_args_env(func.args, |ctx| ctx.eval(&func.body));
|
||||
args = ret_args;
|
||||
val = ret?;
|
||||
}
|
||||
@@ -264,7 +297,9 @@ impl Value {
|
||||
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()))
|
||||
_ => Err(Error::EvalError(
|
||||
"attempt to call something which is not a function but ...".to_string(),
|
||||
)),
|
||||
}?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -520,6 +555,12 @@ impl Value {
|
||||
self
|
||||
}
|
||||
|
||||
/// 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, seen: &mut HashSet<Value>) -> PubValue {
|
||||
use Value::*;
|
||||
if seen.contains(self) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
//! Defines the runtime representation of a partially applied primitive operation.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use derive_more::Constructor;
|
||||
@@ -8,15 +10,28 @@ use nixjit_ir::PrimOpId;
|
||||
use super::Value;
|
||||
use crate::EvalContext;
|
||||
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
impl PrimOpApp {
|
||||
/// Applies more arguments to a partially applied primop.
|
||||
///
|
||||
/// 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>,
|
||||
args: Vec<Value>,
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
//! Defines a placeholder for Nix's contextful strings.
|
||||
//!
|
||||
//! In Nix, strings can carry a "context" which affects how they are
|
||||
//! handled, particularly with regards to path resolution. This module
|
||||
//! provides the basic structures for this feature, although it is
|
||||
//! currently a work in progress.
|
||||
|
||||
// TODO: Contextful String
|
||||
|
||||
/// Represents the context associated with a string.
|
||||
pub struct StringContext {
|
||||
context: Vec<()>,
|
||||
}
|
||||
|
||||
impl StringContext {
|
||||
/// Creates a new, empty `StringContext`.
|
||||
pub fn new() -> StringContext {
|
||||
StringContext {
|
||||
context: Vec::new(),
|
||||
@@ -12,12 +21,14 @@ impl StringContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// A string that carries an associated context.
|
||||
pub struct ContextfulString {
|
||||
string: String,
|
||||
context: StringContext,
|
||||
}
|
||||
|
||||
impl ContextfulString {
|
||||
/// Creates a new `ContextfulString` from a standard `String`.
|
||||
pub fn new(string: String) -> ContextfulString {
|
||||
ContextfulString {
|
||||
string,
|
||||
|
||||
Reference in New Issue
Block a user