chore: comment
This commit is contained in:
@@ -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