difftreelog
feat array unification
in: master
11 files changed
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -50,7 +50,7 @@
/// Assign elements with [`jsonnet_json_array_append`].
#[no_mangle]
pub extern "C" fn jsonnet_json_make_array(_vm: &VM) -> *mut Val {
- Box::into_raw(Box::new(Val::Arr(ArrValue::eager(Vec::new()))))
+ Box::into_raw(Box::new(Val::arr(())))
}
/// Make a `JsonnetJsonValue` representing an object.
bindings/jsonnet/src/val_modify.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -24,7 +24,7 @@
}
new.push(Thunk::evaluated(val.clone()));
- *arr = Val::Arr(ArrValue::lazy(new));
+ *arr = Val::arr(new);
}
_ => panic!("should receive array"),
}
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -6,7 +6,6 @@
};
use jrsonnet_gcmodule::{Cc, cc_dyn};
-use jrsonnet_interner::IBytes;
use jrsonnet_ir::Expr;
use crate::{Context, Result, Thunk, Val, function::NativeFn, typed::IntoUntyped};
@@ -35,28 +34,17 @@
impl ArrValue {
pub fn empty() -> Self {
- Self::new(RangeArray::empty())
+ Self::new(())
}
pub fn expr(ctx: Context, exprs: Rc<Vec<Expr>>) -> Self {
Self::new(ExprArray::new(ctx, exprs))
- }
-
- pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {
- Self::new(LazyArray(thunks))
}
- pub fn eager(values: Vec<Val>) -> Self {
- Self::new(EagerArray(values))
- }
-
pub fn repeated(data: Self, repeats: usize) -> Option<Self> {
Some(Self::new(RepeatedArray::new(data, repeats)?))
}
- pub fn bytes(bytes: IBytes) -> Self {
- Self::new(BytesArray(bytes))
- }
pub fn chars(chars: impl Iterator<Item = char>) -> Self {
Self::new(CharArray(chars.collect()))
}
@@ -83,7 +71,7 @@
out.push(i);
}
}
- return Ok(Self::eager(out));
+ return Ok(Self::new(out));
};
let mut out = Vec::new();
@@ -92,29 +80,16 @@
out.push(i);
}
}
- Ok(Self::lazy(out))
+ Ok(Self::new(out))
}
pub fn extended(a: Self, b: Self) -> Self {
- // TODO: benchmark for an optimal value, currently just a arbitrary choice
- const ARR_EXTEND_THRESHOLD: usize = 1000;
-
if a.is_empty() {
b
} else if b.is_empty() {
a
- } else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {
+ } else {
Self::new(ExtendedArray::new(a, b))
- } else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {
- let mut out = Vec::with_capacity(a.len() + b.len());
- out.extend(a);
- out.extend(b);
- Self::eager(out)
- } else {
- let mut out = Vec::with_capacity(a.len() + b.len());
- out.extend(a.iter_lazy());
- out.extend(b.iter_lazy());
- Self::lazy(out)
}
}
@@ -165,19 +140,15 @@
self.0.is_empty()
}
+ pub fn is_cheap(&self) -> bool {
+ self.0.is_cheap()
+ }
+
/// Get array element by index, evaluating it, if it is lazy.
///
/// Returns `None` on out-of-bounds condition.
pub fn get(&self, index: usize) -> Result<Option<Val>> {
self.0.get(index)
- }
-
- /// Returns None if get is either non cheap, or out of bounds
- /// Note that non-cheap access includes errorable values
- ///
- /// Prefer it to `get_lazy`, but use `get` when you can.
- fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0.get_cheap(index)
}
/// Get array element by index, without evaluation.
@@ -196,15 +167,6 @@
(0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))
}
- /// Prefer it over `iter_lazy`, but do not use it where `iter` will do.
- pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {
- if self.is_cheap() {
- Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))
- } else {
- None
- }
- }
-
/// Return a reversed view on current array.
#[must_use]
pub fn reversed(self) -> Self {
@@ -213,50 +175,25 @@
pub fn ptr_eq(a: &Self, b: &Self) -> bool {
Cc::ptr_eq(&a.0, &b.0)
- }
-
- /// Is this vec supports `.get_cheap()?`
- pub fn is_cheap(&self) -> bool {
- self.0.is_cheap()
}
pub fn as_any(&self) -> &dyn Any {
&self.0
}
}
-impl From<Vec<Val>> for ArrValue {
- fn from(value: Vec<Val>) -> Self {
- Self::eager(value)
- }
-}
-impl From<Vec<Thunk<Val>>> for ArrValue {
- fn from(value: Vec<Thunk<Val>>) -> Self {
- Self::lazy(value)
- }
-}
-impl FromIterator<Val> for ArrValue {
- fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {
- Self::eager(iter.into_iter().collect())
+impl<T> From<T> for ArrValue
+where
+ T: ArrayLike,
+{
+ fn from(value: T) -> Self {
+ Self::new(value)
}
}
-impl ArrayLike for ArrValue {
- fn len(&self) -> usize {
- self.0.len()
- }
-
- fn get(&self, index: usize) -> Result<Option<Val>> {
- self.0.get(index)
- }
-
- fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- self.0.get_lazy(index)
- }
-
- fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0.get_cheap(index)
- }
-
- fn is_cheap(&self) -> bool {
- self.0.is_cheap()
+impl<I> FromIterator<I> for ArrValue
+where
+ Vec<I>: ArrayLike,
+{
+ fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
+ Self::new(iter.into_iter().collect::<Vec<_>>())
}
}
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -1,4 +1,10 @@
-use std::{any::Any, cell::RefCell, fmt::Debug, mem::replace, rc::Rc};
+use std::{
+ any::Any,
+ cell::RefCell,
+ fmt::{self, Debug},
+ mem::replace,
+ rc::Rc,
+};
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::{IBytes, IStr};
@@ -21,11 +27,45 @@
}
fn get(&self, index: usize) -> Result<Option<Val>>;
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;
- fn get_cheap(&self, index: usize) -> Option<Val>;
- fn is_cheap(&self) -> bool;
+ fn is_cheap(&self) -> bool {
+ false
+ }
+}
+trait ArrayCheap {
+ fn get(&self, index: usize) -> Option<Val>;
+ fn len(&self) -> usize;
}
+impl<T> ArrayLike for T
+where
+ T: Any + Trace + Debug + ArrayCheap,
+{
+ fn len(&self) -> usize {
+ <T as ArrayCheap>::len(self)
+ }
+
+ fn get(&self, index: usize) -> Result<Option<Val>> {
+ Ok(<T as ArrayCheap>::get(self, index))
+ }
+ fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+ <T as ArrayCheap>::get(self, index).map(Thunk::evaluated)
+ }
+
+ fn is_cheap(&self) -> bool {
+ true
+ }
+}
+
+impl ArrayCheap for () {
+ fn len(&self) -> usize {
+ 0
+ }
+ fn get(&self, _index: usize) -> Option<Val> {
+ None
+ }
+}
+
#[derive(Debug, Trace)]
pub struct SliceArray {
pub(crate) inner: ArrValue,
@@ -52,9 +92,6 @@
self.inner.get_lazy(self.map_idx(index))
}
- fn get_cheap(&self, index: usize) -> Option<Val> {
- self.inner.get_cheap(self.map_idx(index))
- }
fn is_cheap(&self) -> bool {
self.inner.is_cheap()
}
@@ -62,47 +99,21 @@
#[derive(Trace, Debug)]
pub struct CharArray(pub Vec<char>);
-impl ArrayLike for CharArray {
+impl ArrayCheap for CharArray {
fn len(&self) -> usize {
- self.0.len()
+ self.0.as_slice().len()
}
-
- fn get(&self, index: usize) -> Result<Option<Val>> {
- Ok(self.get_cheap(index))
- }
-
- fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- self.get_cheap(index).map(Thunk::evaluated)
- }
-
- fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0.get(index).map(|v| Val::string(*v))
- }
- fn is_cheap(&self) -> bool {
- true
+ fn get(&self, index: usize) -> Option<Val> {
+ self.0.as_slice().get(index).map(|v| Val::string(*v))
}
}
-#[derive(Trace, Debug)]
-pub struct BytesArray(pub IBytes);
-impl ArrayLike for BytesArray {
+impl ArrayCheap for IBytes {
fn len(&self) -> usize {
- self.0.len()
- }
-
- fn get(&self, index: usize) -> Result<Option<Val>> {
- Ok(self.get_cheap(index))
- }
-
- fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- self.get_cheap(index).map(Thunk::evaluated)
- }
-
- fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0.get(index).map(|v| Val::Num((*v).into()))
+ self.as_slice().len()
}
- fn is_cheap(&self) -> bool {
- true
+ fn get(&self, index: usize) -> Option<Val> {
+ self.as_slice().get(index).map(|v| Val::Num((*v).into()))
}
}
@@ -190,9 +201,6 @@
expr: self.clone(),
index,
}))
- }
- fn get_cheap(&self, _index: usize) -> Option<Val> {
- None
}
fn is_cheap(&self) -> bool {
false
@@ -275,61 +283,34 @@
self.len
}
- fn get_cheap(&self, index: usize) -> Option<Val> {
- if self.split > index {
- self.a.get_cheap(index)
- } else {
- self.b.get_cheap(index - self.split)
- }
- }
fn is_cheap(&self) -> bool {
self.a.is_cheap() && self.b.is_cheap()
}
}
-#[derive(Trace, Debug)]
-pub struct LazyArray(pub Vec<Thunk<Val>>);
-impl ArrayLike for LazyArray {
+impl<T> ArrayLike for Vec<T>
+where
+ T: IntoUntyped + Trace + fmt::Debug,
+ for<'a> &'a T: IntoUntyped,
+{
fn len(&self) -> usize {
- self.0.len()
+ self.as_slice().len()
}
+
fn get(&self, index: usize) -> Result<Option<Val>> {
- let Some(v) = self.0.get(index) else {
+ let Some(elem) = self.as_slice().get(index) else {
return Ok(None);
};
- v.evaluate().map(Some)
- }
- fn get_cheap(&self, _index: usize) -> Option<Val> {
- None
- }
- fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- self.0.get(index).cloned()
- }
- fn is_cheap(&self) -> bool {
- false
- }
-}
-
-#[derive(Trace, Debug)]
-pub struct EagerArray(pub Vec<Val>);
-impl ArrayLike for EagerArray {
- fn len(&self) -> usize {
- self.0.len()
+ IntoUntyped::into_untyped(elem).map(Some)
}
- fn get(&self, index: usize) -> Result<Option<Val>> {
- Ok(self.0.get(index).cloned())
- }
-
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- self.0.get(index).cloned().map(Thunk::evaluated)
+ let elem = self.as_slice().get(index)?;
+ Some(IntoUntyped::into_lazy_untyped(elem))
}
- fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0.get(index).cloned()
- }
fn is_cheap(&self) -> bool {
- true
+ !T::provides_lazy()
}
}
@@ -363,28 +344,12 @@
WithExactSize(self.start..=self.end, self.size())
}
}
-
-impl ArrayLike for RangeArray {
- fn len(&self) -> usize {
- self.size()
- }
- fn is_empty(&self) -> bool {
- self.size() == 0
- }
-
- fn get(&self, index: usize) -> Result<Option<Val>> {
- Ok(self.get_cheap(index))
- }
-
- fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- self.get_cheap(index).map(Thunk::evaluated)
- }
-
- fn get_cheap(&self, index: usize) -> Option<Val> {
+impl ArrayCheap for RangeArray {
+ fn get(&self, index: usize) -> Option<Val> {
self.range().nth(index).map(|i| Val::Num(i.into()))
}
- fn is_cheap(&self) -> bool {
- true
+ fn len(&self) -> usize {
+ self.size()
}
}
@@ -403,9 +368,6 @@
self.0.get_lazy(self.0.len() - index - 1)
}
- fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0.get_cheap(self.0.len() - index - 1)
- }
fn is_cheap(&self) -> bool {
self.0.is_cheap()
}
@@ -509,13 +471,6 @@
arr: self.clone(),
index,
}))
- }
-
- fn get_cheap(&self, _index: usize) -> Option<Val> {
- None
- }
- fn is_cheap(&self) -> bool {
- false
}
}
@@ -534,6 +489,12 @@
total_len,
})
}
+ fn map_idx(&self, index: usize) -> Option<usize> {
+ if index > self.total_len {
+ return None;
+ }
+ Some(index % self.data.len())
+ }
}
impl ArrayLike for RepeatedArray {
@@ -542,25 +503,17 @@
}
fn get(&self, index: usize) -> Result<Option<Val>> {
- if index > self.total_len {
+ let Some(idx) = self.map_idx(index) else {
return Ok(None);
- }
- self.data.get(index % self.data.len())
+ };
+ self.data.get(idx)
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- if index > self.total_len {
- return None;
- }
- self.data.get_lazy(index % self.data.len())
+ let idx = self.map_idx(index)?;
+ self.data.get_lazy(idx)
}
- fn get_cheap(&self, index: usize) -> Option<Val> {
- if index > self.total_len {
- return None;
- }
- self.data.get_cheap(index % self.data.len())
- }
fn is_cheap(&self) -> bool {
self.data.is_cheap()
}
@@ -584,21 +537,17 @@
}
fn get(&self, index: usize) -> Result<Option<Val>> {
- let Some(key) = self.keys.get(index) else {
+ let Some(key) = self.keys.as_slice().get(index) else {
return Ok(None);
};
Ok(Some(self.obj.get_or_bail(key.clone())?))
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- let key = self.keys.get(index)?;
+ let key = self.keys.as_slice().get(index)?;
Some(self.obj.get_lazy_or_bail(key.clone()))
}
- fn get_cheap(&self, _index: usize) -> Option<Val> {
- None
- }
-
fn is_cheap(&self) -> bool {
false
}
@@ -628,7 +577,7 @@
}
fn get(&self, index: usize) -> Result<Option<Val>> {
- let Some(key) = self.keys.get(index) else {
+ let Some(key) = self.keys.as_slice().get(index) else {
return Ok(None);
};
Ok(Some(
@@ -641,7 +590,7 @@
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- let key = self.keys.get(index)?;
+ let key = self.keys.as_slice().get(index)?;
// Nothing can fail in the key part, yet value is still
// lazy-evaluated
Some(Thunk::evaluated(
@@ -651,10 +600,6 @@
})
.expect("convertible"),
))
- }
-
- fn get_cheap(&self, _index: usize) -> Option<Val> {
- None
}
fn is_cheap(&self) -> bool {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -70,12 +70,12 @@
if n.iter().any(|e| !is_trivial(e)) {
return None;
}
- Val::Arr(ArrValue::eager(
+ Val::Arr(
n.iter()
.map(evaluate_trivial)
.map(|e| e.expect("checked trivial"))
.collect(),
- ))
+ )
}
_ => return None,
})
@@ -145,12 +145,12 @@
let fctx = Pending::new();
let mut new_bindings = FxHashMap::with_capacity(into.binds_len());
let obj = obj.clone();
- let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![
+ let value = Thunk::evaluated(Val::arr(vec![
Thunk::evaluated(Val::string(field.clone())),
- Thunk!(move || obj.get(field).transpose().expect(
+ obj.get_lazy(field).transpose().expect(
"field exists, as field name was obtained from object.fields()",
- )),
- ])));
+ ),
+ ]));
destruct(into, value, fctx.clone(), &mut new_bindings)?;
let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);
@@ -528,7 +528,7 @@
#[cfg(feature = "exp-null-coaelse")]
None if part.null_coaelse => return Ok(Val::Null),
None => {
- let suggestions = suggest_object_fields(&v, key.clone().into_flat());
+ let suggestions = suggest_object_fields(&v, key.into_flat());
return Err(Error::from(NoSuchField(
key.clone().into_flat(),
@@ -628,7 +628,7 @@
}
Arr(items) => {
if items.is_empty() {
- Val::Arr(ArrValue::empty())
+ Val::arr(())
} else {
Val::Arr(ArrValue::expr(ctx, items.clone()))
}
@@ -640,7 +640,7 @@
out.push(Thunk!(move || evaluate(ctx, &expr)));
Ok(())
})?;
- Val::Arr(ArrValue::lazy(out))
+ Val::arr(out)
}
Obj(body) => Val::Obj(evaluate_object(None, ctx, body)?),
ObjExtend(a, b) => {
@@ -718,9 +718,7 @@
|| s.import_resolved(resolved_path),
)?,
ImportKind::Str => Val::string(s.import_resolved_str(resolved_path)?),
- ImportKind::Bin => {
- Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?))
- }
+ ImportKind::Bin => Val::arr(s.import_resolved_bin(resolved_path)?),
}) as Result<Val>
})?
}
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,6 +1,6 @@
use std::borrow::Cow;
-use jrsonnet_interner::IStr;
+use jrsonnet_interner::{IBytes, IStr};
use serde::{
Deserialize, Serialize, Serializer,
de::{self, Visitor},
@@ -11,8 +11,8 @@
};
use crate::{
- Error as JrError, ObjValue, ObjValueBuilder, Result, Val, arr::ArrValue, in_description_frame,
- runtime_error, val::NumValue,
+ Error as JrError, ObjValue, ObjValueBuilder, Result, Val, in_description_frame, runtime_error,
+ val::NumValue,
};
impl<'de> Deserialize<'de> for Val {
@@ -90,7 +90,7 @@
where
E: de::Error,
{
- Ok(Val::Arr(ArrValue::bytes(v.into())))
+ Ok(Val::arr(IBytes::from(v)))
}
fn visit_none<E>(self) -> Result<Self::Value, E>
@@ -130,7 +130,7 @@
out.push(val);
}
- Ok(Val::Arr(ArrValue::eager(out)))
+ Ok(Val::arr(out))
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
@@ -270,7 +270,7 @@
}
fn end(self) -> Result<Val> {
- let inner = Val::Arr(ArrValue::eager(self.data));
+ let inner = Val::arr(self.data);
if let Some(variant) = self.variant {
let mut out = ObjValue::builder_with_capacity(1);
out.field(variant).value(inner);
@@ -509,7 +509,7 @@
}
fn serialize_bytes(self, v: &[u8]) -> Result<Val> {
- Ok(Val::Arr(ArrValue::bytes(v.into())))
+ Ok(Val::arr(IBytes::from(v)))
}
fn serialize_none(self) -> Result<Val> {
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -6,7 +6,7 @@
use crate::{
ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
- arr::{ArrValue, BytesArray},
+ arr::ArrValue,
bail,
function::FuncVal,
typed::CheckType,
@@ -83,6 +83,12 @@
pub trait Typed: Sized {
const TYPE: &'static ComplexValType;
}
+impl<T> Typed for &T
+where
+ T: Typed,
+{
+ const TYPE: &'static ComplexValType = <&T as Typed>::TYPE;
+}
pub trait IntoUntyped: Typed {
// Whatever caller should use `into_lazy_untyped` instead of `into_untyped`
fn provides_lazy() -> bool {
@@ -93,6 +99,7 @@
Thunk::from(Self::into_untyped(typed))
}
}
+
pub trait IntoUntypedResult: Typed {
/// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result
/// This method returns identity in impl Typed for Result, and should not be overriden
@@ -157,6 +164,26 @@
inner.map(<ThunkIntoUntyped<T>>::default())
}
}
+impl<T> IntoUntyped for &Thunk<T>
+where
+ T: IntoUntyped + Trace + Clone,
+{
+ fn into_untyped(typed: Self) -> Result<Val> {
+ T::into_untyped(typed.evaluate()?)
+ }
+ fn provides_lazy() -> bool {
+ true
+ }
+
+ fn into_lazy_untyped(inner: Self) -> Thunk<Val> {
+ // Avoid lazy mapping
+ let inner = match try_cast_thunk_val(inner.clone()) {
+ Ok(v) => return v,
+ Err(e) => e,
+ };
+ inner.map(<ThunkIntoUntyped<T>>::default())
+ }
+}
fn try_cast_thunk_t<T: 'static>(typed: Thunk<Val>) -> Result<Thunk<T>, Thunk<Val>> {
if TypeId::of::<T>() == TypeId::of::<Val>() {
@@ -221,6 +248,11 @@
}
}
}
+ impl IntoUntyped for &$ty {
+ fn into_untyped(value: Self) -> Result<Val> {
+ Ok(Val::Num((*value).into()))
+ }
+ }
impl IntoUntyped for $ty {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::Num(value.into()))
@@ -305,6 +337,11 @@
impl Typed for f64 {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
}
+impl IntoUntyped for &f64 {
+ fn into_untyped(value: Self) -> Result<Val> {
+ Ok(Val::try_num(*value)?)
+ }
+}
impl IntoUntyped for f64 {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::try_num(value)?)
@@ -324,7 +361,7 @@
impl Typed for PositiveF64 {
const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);
}
-impl IntoUntyped for PositiveF64 {
+impl IntoUntyped for &PositiveF64 {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::try_num(value.0)?)
}
@@ -538,6 +575,11 @@
impl Typed for Val {
const TYPE: &'static ComplexValType = &ComplexValType::Any;
}
+impl IntoUntyped for &Val {
+ fn into_untyped(typed: Self) -> Result<Val> {
+ Ok(typed.clone())
+ }
+}
impl IntoUntyped for Val {
fn into_untyped(typed: Self) -> Result<Val> {
Ok(typed)
@@ -567,9 +609,14 @@
const TYPE: &'static ComplexValType =
&ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));
}
+impl IntoUntyped for &IBytes {
+ fn into_untyped(value: Self) -> Result<Val> {
+ Ok(Val::arr(value.clone()))
+ }
+}
impl IntoUntyped for IBytes {
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Arr(ArrValue::bytes(value)))
+ Ok(Val::arr(value))
}
}
impl FromUntyped for IBytes {
@@ -578,8 +625,8 @@
<Self as Typed>::TYPE.check(&value)?;
unreachable!()
};
- if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
- return Ok(bytes.0.as_slice().into());
+ if let Some(bytes) = a.as_any().downcast_ref::<IBytes>() {
+ return Ok(bytes.clone());
}
<Self as Typed>::TYPE.check(&value)?;
// Any::downcast_ref::<ByteArray>(&a);
@@ -596,7 +643,7 @@
impl Typed for M1 {
const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));
}
-impl IntoUntyped for M1 {
+impl IntoUntyped for &M1 {
fn into_untyped(_: Self) -> Result<Val> {
Ok(Val::Num(NumValue::new(-1.0).expect("finite")))
}
@@ -728,6 +775,11 @@
impl Typed for bool {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);
}
+impl IntoUntyped for &bool {
+ fn into_untyped(value: Self) -> Result<Val> {
+ Ok(Val::Bool(*value))
+ }
+}
impl IntoUntyped for bool {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::Bool(value))
@@ -764,19 +816,23 @@
}
}
-pub struct Null;
-impl Typed for Null {
+impl Typed for () {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);
}
-impl IntoUntyped for Null {
- fn into_untyped(_: Self) -> Result<Val> {
+impl IntoUntyped for &() {
+ fn into_untyped((): Self) -> Result<Val> {
Ok(Val::Null)
}
}
-impl FromUntyped for Null {
+impl IntoUntyped for () {
+ fn into_untyped((): Self) -> Result<Val> {
+ Ok(Val::Null)
+ }
+}
+impl FromUntyped for () {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
- Ok(Self)
+ Ok(())
}
}
@@ -811,9 +867,9 @@
impl Typed for NumValue {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
}
-impl IntoUntyped for NumValue {
+impl IntoUntyped for &NumValue {
fn into_untyped(typed: Self) -> Result<Val> {
- Ok(Val::Num(typed))
+ Ok(Val::Num(*typed))
}
}
impl FromUntyped for NumValue {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use std::{2 cell::RefCell,3 cmp::Ordering,4 fmt::{self, Debug, Display},5 marker::PhantomData,6 mem::replace,7 num::NonZeroU32,8 ops::Deref,9 rc::Rc,10};1112use jrsonnet_gcmodule::{Acyclic, Cc, Trace, cc_dyn};13use jrsonnet_interner::IStr;14pub use jrsonnet_macros::Thunk;15use jrsonnet_types::ValType;16use rustc_hash::FxHashMap;17use thiserror::Error;1819pub use crate::arr::{ArrValue, ArrayLike};20use crate::{21 ObjValue, Result, SupThis, Unbound, WeakSupThis, bail,22 error::{Error, ErrorKind::*},23 function::FuncVal,24 gc::WithCapacityExt as _,25 manifest::{ManifestFormat, ToStringFormat},26 typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},27};2829pub trait ThunkValue: Trace {30 type Output;31 fn get(&self) -> Result<Self::Output>;32}3334#[derive(Trace)]35enum MemoizedClusureThunkInner<D: Trace, T: Trace> {36 Computed(T),37 Errored(Error),38 Waiting {39 env: D,40 // Carries no data, as it is not a real closure, all the41 // captured environment is stored in `env` field.42 #[trace(skip)]43 closure: fn(D) -> Result<T>,44 },45 Pending,46}47#[derive(Trace)]48pub struct MemoizedClosureThunk<D: Trace, T: Trace>(RefCell<MemoizedClusureThunkInner<D, T>>);49impl<D: Trace, T: Trace> MemoizedClosureThunk<D, T> {50 pub fn new(env: D, closure: fn(D) -> Result<T>) -> Self {51 Self(RefCell::new(MemoizedClusureThunkInner::Waiting {52 env,53 closure,54 }))55 }56}5758impl<D: Trace, T: Trace + Clone> ThunkValue for MemoizedClosureThunk<D, T> {59 type Output = T;6061 fn get(&self) -> Result<Self::Output> {62 match &*self.0.borrow() {63 MemoizedClusureThunkInner::Computed(v) => return Ok(v.clone()),64 MemoizedClusureThunkInner::Errored(e) => return Err(e.clone()),65 MemoizedClusureThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),66 MemoizedClusureThunkInner::Waiting { .. } => (),67 }68 let MemoizedClusureThunkInner::Waiting { env, closure } = replace(69 &mut *self.0.borrow_mut(),70 MemoizedClusureThunkInner::Pending,71 ) else {72 unreachable!();73 };74 let new_value = match closure(env) {75 Ok(v) => v,76 Err(e) => {77 *self.0.borrow_mut() = MemoizedClusureThunkInner::Errored(e.clone());78 return Err(e);79 }80 };81 *self.0.borrow_mut() = MemoizedClusureThunkInner::Computed(new_value.clone());82 Ok(new_value)83 }84}8586cc_dyn!(87 /// Lazily evaluated value88 #[derive(Clone)] Thunk<V: Trace>,89 ThunkValue<Output = V>,90 pub fn new() {...}91);9293impl<T: Trace> Thunk<T> {94 pub fn evaluated(val: T) -> Self95 where96 T: Clone,97 {98 #[derive(Trace)]99 struct EvaluatedThunk<T: Trace>(T);100 impl<T> ThunkValue for EvaluatedThunk<T>101 where102 T: Clone + Trace,103 {104 type Output = T;105106 fn get(&self) -> Result<Self::Output> {107 Ok(self.0.clone())108 }109 }110 Self::new(EvaluatedThunk(val))111 }112 pub fn errored(e: Error) -> Self {113 #[derive(Trace)]114 struct ErroredThunk<T: Trace>(Error, PhantomData<T>);115 impl<T> ThunkValue for ErroredThunk<T>116 where117 T: Trace,118 {119 type Output = T;120121 fn get(&self) -> Result<Self::Output> {122 Err(self.0.clone())123 }124 }125 Self::new(ErroredThunk(e, PhantomData))126 }127 pub fn result(res: Result<T, Error>) -> Self128 where129 T: Clone,130 {131 match res {132 Ok(o) => Self::evaluated(o),133 Err(e) => Self::errored(e),134 }135 }136}137138impl<T> Thunk<T>139where140 T: Clone + Trace,141{142 pub fn force(&self) -> Result<()> {143 self.evaluate()?;144 Ok(())145 }146147 /// Evaluate thunk, or return cached value148 ///149 /// # Errors150 ///151 /// - Lazy value evaluation returned error152 /// - This method was called during inner value evaluation153 pub fn evaluate(&self) -> Result<T> {154 self.0.get()155 }156}157158pub trait ThunkMapper<Input>: Trace {159 type Output;160 fn map(self, from: Input) -> Result<Self::Output>;161}162impl<Input> Thunk<Input>163where164 Input: Trace + Clone,165{166 pub fn map<M>(self, mapper: M) -> Thunk<M::Output>167 where168 M: ThunkMapper<Input>,169 M::Output: Trace + Clone,170 {171 let inner = self;172 Thunk!(move || {173 let value = inner.evaluate()?;174 let mapped = mapper.map(value)?;175 Ok(mapped)176 })177 }178}179180impl<T: Trace + Clone> From<Result<T>> for Thunk<T> {181 fn from(value: Result<T>) -> Self {182 match value {183 Ok(o) => Self::evaluated(o),184 Err(e) => Self::errored(e),185 }186 }187}188impl<T, V: Trace> From<T> for Thunk<V>189where190 T: ThunkValue<Output = V>,191{192 fn from(value: T) -> Self {193 Self::new(value)194 }195}196197impl<T: Trace + Default + Clone> Default for Thunk<T> {198 fn default() -> Self {199 Self::evaluated(T::default())200 }201}202203#[derive(Trace, Clone)]204pub struct CachedUnbound<I, T>205where206 I: Unbound<Bound = T>,207 T: Trace,208{209 cache: Cc<RefCell<FxHashMap<WeakSupThis, T>>>,210 value: I,211}212impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {213 pub fn new(value: I) -> Self {214 Self {215 cache: Cc::new(RefCell::new(FxHashMap::new())),216 value,217 }218 }219}220impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {221 type Bound = T;222 fn bind(&self, sup_this: SupThis) -> Result<T> {223 let cache_key = sup_this.clone().downgrade();224 {225 if let Some(t) = self.cache.borrow().get(&cache_key) {226 return Ok(t.clone());227 }228 }229 let bound = self.value.bind(sup_this)?;230231 {232 let mut cache = self.cache.borrow_mut();233 cache.insert(cache_key, bound.clone());234 }235236 Ok(bound)237 }238}239240impl<T: Debug + Trace> Debug for Thunk<T> {241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {242 write!(f, "Lazy")243 }244}245impl<T: Trace> PartialEq for Thunk<T> {246 fn eq(&self, other: &Self) -> bool {247 Cc::ptr_eq(&self.0, &other.0)248 }249}250251/// Represents a Jsonnet value, which can be sliced or indexed (string or array).252#[allow(clippy::module_name_repetitions)]253pub enum IndexableVal {254 /// String.255 Str(IStr),256 /// Array.257 Arr(ArrValue),258}259impl IndexableVal {260 pub fn is_empty(&self) -> bool {261 match self {262 Self::Str(s) => s.is_empty(),263 Self::Arr(s) => s.is_empty(),264 }265 }266267 pub fn to_array(self) -> ArrValue {268 match self {269 Self::Str(s) => ArrValue::chars(s.chars()),270 Self::Arr(arr) => arr,271 }272 }273 /// Slice the value.274 ///275 /// # Implementation276 ///277 /// For strings, will create a copy of specified interval.278 ///279 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.280 pub fn slice(281 self,282 index: Option<i32>,283 end: Option<i32>,284 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,285 ) -> Result<Self> {286 match &self {287 Self::Str(s) => {288 let mut computed_len = None;289 let mut get_len = || {290 computed_len.unwrap_or_else(|| {291 let len = s.chars().count();292 let _ = computed_len.insert(len);293 len294 })295 };296 let mut get_idx = |pos: Option<i32>, default| {297 match pos {298 #[expect(clippy::cast_sign_loss, reason = "abs value is used")]299 Some(v) if v < 0 => get_len().saturating_sub((-v as isize) as usize),300 // No need to clamp, as iterator interface is used301 #[expect(clippy::cast_sign_loss, reason = "abs value is used")]302 Some(v) => v as usize,303 None => default,304 }305 };306307 let index = get_idx(index, 0);308 let end = get_idx(end, usize::MAX);309 let step = step.as_deref().copied().unwrap_or(1);310311 if index >= end {312 return Ok(Self::Str("".into()));313 }314315 Ok(Self::Str(316 (s.chars()317 .skip(index)318 .take(end - index)319 .step_by(step)320 .collect::<String>())321 .into(),322 ))323 }324 Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice(325 index,326 end,327 #[expect(328 clippy::cast_possible_truncation,329 reason = "overflow will result with skip too large which would be equivalent"330 )]331 step.map(|v| NonZeroU32::new(v.value() as u32).expect("bounded != 0")),332 ))),333 }334 }335}336337#[derive(Debug, Clone, Acyclic)]338pub enum StrValue {339 Flat(IStr),340 Tree(Rc<(StrValue, StrValue, usize)>),341}342impl StrValue {343 pub fn concat(a: Self, b: Self) -> Self {344 // TODO: benchmark for an optimal value, currently just a arbitrary choice345 const STRING_EXTEND_THRESHOLD: usize = 100;346347 if a.is_empty() {348 b349 } else if b.is_empty() {350 a351 } else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {352 Self::Flat(format!("{a}{b}").into())353 } else {354 let len = a.len() + b.len();355 Self::Tree(Rc::new((a, b, len)))356 }357 }358 pub fn into_flat(self) -> IStr {359 #[cold]360 fn write_buf(s: &StrValue, out: &mut String) {361 match s {362 StrValue::Flat(f) => out.push_str(f),363 StrValue::Tree(t) => {364 write_buf(&t.0, out);365 write_buf(&t.1, out);366 }367 }368 }369 match self {370 Self::Flat(f) => f,371 Self::Tree(_) => {372 let mut buf = String::with_capacity(self.len());373 write_buf(&self, &mut buf);374 buf.into()375 }376 }377 }378 pub fn len(&self) -> usize {379 match self {380 Self::Flat(v) => v.len(),381 Self::Tree(t) => t.2,382 }383 }384 pub fn is_empty(&self) -> bool {385 match self {386 Self::Flat(v) => v.is_empty(),387 // Can't create non-flat empty string388 Self::Tree(_) => false,389 }390 }391}392impl<T> From<T> for StrValue393where394 IStr: From<T>,395{396 fn from(value: T) -> Self {397 Self::Flat(IStr::from(value))398 }399}400impl Display for StrValue {401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {402 match self {403 Self::Flat(v) => write!(f, "{v}"),404 Self::Tree(t) => {405 write!(f, "{}", t.0)?;406 write!(f, "{}", t.1)407 }408 }409 }410}411impl PartialEq for StrValue {412 // False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.413 #[allow(clippy::unconditional_recursion)]414 fn eq(&self, other: &Self) -> bool {415 let a = self.clone().into_flat();416 let b = other.clone().into_flat();417 a == b418 }419}420impl Eq for StrValue {}421impl PartialOrd for StrValue {422 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {423 Some(self.cmp(other))424 }425}426impl Ord for StrValue {427 fn cmp(&self, other: &Self) -> Ordering {428 let a = self.clone().into_flat();429 let b = other.clone().into_flat();430 a.cmp(&b)431 }432}433434/// Represents jsonnet number435/// Jsonnet numbers are finite f64, with NaNs disallowed436#[derive(Trace, Clone, Copy)]437#[repr(transparent)]438pub struct NumValue(f64);439impl NumValue {440 /// Creates a [`NumValue`], if value is finite and not NaN441 pub fn new(v: f64) -> Option<Self> {442 if !v.is_finite() {443 return None;444 }445 Some(Self(v))446 }447 #[inline]448 pub const fn get(&self) -> f64 {449 self.0450 }451 pub(crate) fn truncate_for_bitwise(self) -> Result<i64> {452 if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {453 bail!("numberic value outside of safe integer range for bitwise operation");454 }455 #[expect(clippy::cast_possible_truncation, reason = "intended")]456 Ok(self.0 as i64)457 }458}459impl PartialEq for NumValue {460 fn eq(&self, other: &Self) -> bool {461 self.0 == other.0462 }463}464impl Eq for NumValue {}465impl Ord for NumValue {466 #[inline]467 fn cmp(&self, other: &Self) -> Ordering {468 // Can't use `total_cmp`: its behavior for `-0` and `0`469 // is not following wanted.470 unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }471 }472}473impl PartialOrd for NumValue {474 #[inline]475 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {476 Some(self.cmp(other))477 }478}479impl Debug for NumValue {480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {481 Debug::fmt(&self.0, f)482 }483}484impl Display for NumValue {485 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {486 Display::fmt(&self.0, f)487 }488}489impl Deref for NumValue {490 type Target = f64;491492 #[inline]493 fn deref(&self) -> &Self::Target {494 &self.0495 }496}497macro_rules! impl_num {498 ($($ty:ty),+) => {$(499 impl From<$ty> for NumValue {500 #[inline]501 fn from(value: $ty) -> Self {502 Self(value.into())503 }504 }505 )+};506}507impl_num!(i8, u8, i16, u16, i32, u32);508509#[derive(Clone, Copy, Debug, Error, Trace)]510pub enum ConvertNumValueError {511 #[error("overflow")]512 Overflow,513 #[error("underflow")]514 Underflow,515 #[error("non-finite")]516 NonFinite,517}518impl From<ConvertNumValueError> for Error {519 fn from(e: ConvertNumValueError) -> Self {520 Self::new(e.into())521 }522}523524macro_rules! impl_try_num {525 ($($ty:ty),+) => {$(526 impl TryFrom<$ty> for NumValue {527 type Error = ConvertNumValueError;528 #[inline]529 fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {530 #[expect(clippy::cast_precision_loss, reason = "precision loss is explicitly handled")]531 let value = value as f64;532 if value < MIN_SAFE_INTEGER {533 return Err(ConvertNumValueError::Underflow)534 } else if value > MAX_SAFE_INTEGER {535 return Err(ConvertNumValueError::Overflow)536 }537 // Number is finite.538 Ok(Self(value))539 }540 }541 )+};542}543impl_try_num!(usize, isize, i64, u64);544545impl TryFrom<f64> for NumValue {546 type Error = ConvertNumValueError;547548 #[inline]549 fn try_from(value: f64) -> Result<Self, Self::Error> {550 Self::new(value).ok_or(ConvertNumValueError::NonFinite)551 }552}553impl TryFrom<f32> for NumValue {554 type Error = ConvertNumValueError;555556 #[inline]557 fn try_from(value: f32) -> Result<Self, Self::Error> {558 Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)559 }560}561562/// Represents any valid Jsonnet value.563#[derive(Debug, Clone, Trace, Default)]564pub enum Val {565 /// Represents a Jsonnet boolean.566 Bool(bool),567 /// Represents a Jsonnet null value.568 #[default]569 Null,570 /// Represents a Jsonnet string.571 Str(StrValue),572 /// Represents a Jsonnet number.573 /// Should be finite, and not NaN574 /// This restriction isn't enforced by enum, as enum field can't be marked as private575 Num(NumValue),576 /// Experimental bigint577 #[cfg(feature = "exp-bigint")]578 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),579 /// Represents a Jsonnet array.580 Arr(ArrValue),581 /// Represents a Jsonnet object.582 Obj(ObjValue),583 /// Represents a Jsonnet function.584 Func(FuncVal),585}586587#[cfg(target_pointer_width = "64")]588static_assertions::assert_eq_size!(Val, [u8; 24]);589590impl From<IndexableVal> for Val {591 fn from(v: IndexableVal) -> Self {592 match v {593 IndexableVal::Str(s) => Self::string(s),594 IndexableVal::Arr(a) => Self::Arr(a),595 }596 }597}598599impl Val {600 pub const fn as_bool(&self) -> Option<bool> {601 match self {602 Self::Bool(v) => Some(*v),603 _ => None,604 }605 }606 pub const fn as_null(&self) -> Option<()> {607 match self {608 Self::Null => Some(()),609 _ => None,610 }611 }612 pub fn as_str(&self) -> Option<IStr> {613 match self {614 Self::Str(s) => Some(s.clone().into_flat()),615 _ => None,616 }617 }618 pub const fn as_num(&self) -> Option<f64> {619 match self {620 Self::Num(n) => Some(n.get()),621 _ => None,622 }623 }624 #[cfg(feature = "exp-bigint")]625 pub fn as_bigint(&self) -> Option<num_bigint::BigInt> {626 match self {627 Self::BigInt(n) => Some(*n.clone()),628 _ => None,629 }630 }631 pub fn as_arr(&self) -> Option<ArrValue> {632 match self {633 Self::Arr(a) => Some(a.clone()),634 _ => None,635 }636 }637 pub fn as_obj(&self) -> Option<ObjValue> {638 match self {639 Self::Obj(o) => Some(o.clone()),640 _ => None,641 }642 }643 pub fn as_func(&self) -> Option<FuncVal> {644 match self {645 Self::Func(f) => Some(f.clone()),646 _ => None,647 }648 }649650 pub const fn value_type(&self) -> ValType {651 match self {652 Self::Str(..) => ValType::Str,653 Self::Num(..) => ValType::Num,654 #[cfg(feature = "exp-bigint")]655 Self::BigInt(..) => ValType::BigInt,656 Self::Arr(..) => ValType::Arr,657 Self::Obj(..) => ValType::Obj,658 Self::Bool(_) => ValType::Bool,659 Self::Null => ValType::Null,660 Self::Func(..) => ValType::Func,661 }662 }663664 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {665 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {666 manifest.manifest(val.clone())667 }668 manifest_dyn(self, &format)669 }670671 pub fn to_string(&self) -> Result<IStr> {672 Ok(match self {673 Self::Bool(true) => "true".into(),674 Self::Bool(false) => "false".into(),675 Self::Null => "null".into(),676 Self::Str(s) => s.clone().into_flat(),677 _ => self.manifest(ToStringFormat).map(IStr::from)?,678 })679 }680681 pub fn into_indexable(self) -> Result<IndexableVal> {682 Ok(match self {683 Self::Str(s) => IndexableVal::Str(s.into_flat()),684 Self::Arr(arr) => IndexableVal::Arr(arr),685 _ => bail!(ValueIsNotIndexable(self.value_type())),686 })687 }688689 pub fn function(function: impl Into<FuncVal>) -> Self {690 Self::Func(function.into())691 }692 pub fn string(string: impl Into<StrValue>) -> Self {693 Self::Str(string.into())694 }695 pub fn num(num: impl Into<NumValue>) -> Self {696 Self::Num(num.into())697 }698 pub fn try_num<V, E>(num: V) -> Result<Self, E>699 where700 NumValue: TryFrom<V, Error = E>,701 {702 Ok(Self::Num(num.try_into()?))703 }704}705706impl From<IStr> for Val {707 fn from(value: IStr) -> Self {708 Self::string(value)709 }710}711impl From<String> for Val {712 fn from(value: String) -> Self {713 Self::string(value)714 }715}716impl From<&str> for Val {717 fn from(value: &str) -> Self {718 Self::string(value)719 }720}721impl From<ObjValue> for Val {722 fn from(value: ObjValue) -> Self {723 Self::Obj(value)724 }725}726727const fn is_function_like(val: &Val) -> bool {728 matches!(val, Val::Func(_))729}730731/// Native implementation of `std.primitiveEquals`732pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {733 Ok(match (val_a, val_b) {734 (Val::Bool(a), Val::Bool(b)) => a == b,735 (Val::Null, Val::Null) => true,736 (Val::Str(a), Val::Str(b)) => a == b,737 (Val::Num(a), Val::Num(b)) => (a.get() - b.get()).abs() <= f64::EPSILON,738 #[cfg(feature = "exp-bigint")]739 (Val::BigInt(a), Val::BigInt(b)) => a == b,740 (Val::Arr(_), Val::Arr(_)) => {741 bail!("primitiveEquals operates on primitive types, got array")742 }743 (Val::Obj(_), Val::Obj(_)) => {744 bail!("primitiveEquals operates on primitive types, got object")745 }746 (a, b) if is_function_like(a) && is_function_like(b) => {747 bail!("cannot test equality of functions")748 }749 (_, _) => false,750 })751}752753/// Native implementation of `std.equals`754pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {755 if val_a.value_type() != val_b.value_type() {756 return Ok(false);757 }758 match (val_a, val_b) {759 (Val::Arr(a), Val::Arr(b)) => {760 if ArrValue::ptr_eq(a, b) {761 return Ok(true);762 }763 if a.len() != b.len() {764 return Ok(false);765 }766 for (a, b) in a.iter().zip(b.iter()) {767 if !equals(&a?, &b?)? {768 return Ok(false);769 }770 }771 Ok(true)772 }773 (Val::Obj(a), Val::Obj(b)) => {774 if ObjValue::ptr_eq(a, b) {775 return Ok(true);776 }777 let fields = a.fields(778 #[cfg(feature = "exp-preserve-order")]779 false,780 );781 if fields782 != b.fields(783 #[cfg(feature = "exp-preserve-order")]784 false,785 ) {786 return Ok(false);787 }788 for field in fields {789 if !equals(790 &a.get(field.clone())?.expect("field exists"),791 &b.get(field)?.expect("field exists"),792 )? {793 return Ok(false);794 }795 }796 Ok(true)797 }798 (a, b) => Ok(primitive_equals(a, b)?),799 }800}1use std::{2 cell::RefCell,3 cmp::Ordering,4 fmt::{self, Debug, Display},5 marker::PhantomData,6 mem::replace,7 num::NonZeroU32,8 ops::Deref,9 rc::Rc,10};1112use jrsonnet_gcmodule::{Acyclic, Cc, Trace, cc_dyn};13use jrsonnet_interner::IStr;14pub use jrsonnet_macros::Thunk;15use jrsonnet_types::ValType;16use rustc_hash::FxHashMap;17use thiserror::Error;1819pub use crate::arr::{ArrValue, ArrayLike};20use crate::{21 ObjValue, Result, SupThis, Unbound, WeakSupThis, bail,22 error::{Error, ErrorKind::*},23 function::FuncVal,24 gc::WithCapacityExt as _,25 manifest::{ManifestFormat, ToStringFormat},26 typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},27};2829pub trait ThunkValue: Trace {30 type Output;31 fn get(&self) -> Result<Self::Output>;32}3334#[derive(Trace)]35enum MemoizedClusureThunkInner<D: Trace, T: Trace> {36 Computed(T),37 Errored(Error),38 Waiting {39 env: D,40 // Carries no data, as it is not a real closure, all the41 // captured environment is stored in `env` field.42 #[trace(skip)]43 closure: fn(D) -> Result<T>,44 },45 Pending,46}47#[derive(Trace)]48pub struct MemoizedClosureThunk<D: Trace, T: Trace>(RefCell<MemoizedClusureThunkInner<D, T>>);49impl<D: Trace, T: Trace> MemoizedClosureThunk<D, T> {50 pub fn new(env: D, closure: fn(D) -> Result<T>) -> Self {51 Self(RefCell::new(MemoizedClusureThunkInner::Waiting {52 env,53 closure,54 }))55 }56}5758impl<D: Trace, T: Trace + Clone> ThunkValue for MemoizedClosureThunk<D, T> {59 type Output = T;6061 fn get(&self) -> Result<Self::Output> {62 match &*self.0.borrow() {63 MemoizedClusureThunkInner::Computed(v) => return Ok(v.clone()),64 MemoizedClusureThunkInner::Errored(e) => return Err(e.clone()),65 MemoizedClusureThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),66 MemoizedClusureThunkInner::Waiting { .. } => (),67 }68 let MemoizedClusureThunkInner::Waiting { env, closure } = replace(69 &mut *self.0.borrow_mut(),70 MemoizedClusureThunkInner::Pending,71 ) else {72 unreachable!();73 };74 let new_value = match closure(env) {75 Ok(v) => v,76 Err(e) => {77 *self.0.borrow_mut() = MemoizedClusureThunkInner::Errored(e.clone());78 return Err(e);79 }80 };81 *self.0.borrow_mut() = MemoizedClusureThunkInner::Computed(new_value.clone());82 Ok(new_value)83 }84}8586cc_dyn!(87 /// Lazily evaluated value88 #[derive(Clone)] Thunk<V: Trace>,89 ThunkValue<Output = V>,90 pub fn new() {...}91);9293impl<T: Trace> Thunk<T> {94 pub fn evaluated(val: T) -> Self95 where96 T: Clone,97 {98 #[derive(Trace)]99 struct EvaluatedThunk<T: Trace>(T);100 impl<T> ThunkValue for EvaluatedThunk<T>101 where102 T: Clone + Trace,103 {104 type Output = T;105106 fn get(&self) -> Result<Self::Output> {107 Ok(self.0.clone())108 }109 }110 Self::new(EvaluatedThunk(val))111 }112 pub fn errored(e: Error) -> Self {113 #[derive(Trace)]114 struct ErroredThunk<T: Trace>(Error, PhantomData<T>);115 impl<T> ThunkValue for ErroredThunk<T>116 where117 T: Trace,118 {119 type Output = T;120121 fn get(&self) -> Result<Self::Output> {122 Err(self.0.clone())123 }124 }125 Self::new(ErroredThunk(e, PhantomData))126 }127 pub fn result(res: Result<T, Error>) -> Self128 where129 T: Clone,130 {131 match res {132 Ok(o) => Self::evaluated(o),133 Err(e) => Self::errored(e),134 }135 }136}137138impl<T> Thunk<T>139where140 T: Trace,141{142 pub fn force(&self) -> Result<()> {143 self.evaluate()?;144 Ok(())145 }146147 /// Evaluate thunk, or return cached value148 ///149 /// # Errors150 ///151 /// - Lazy value evaluation returned error152 /// - This method was called during inner value evaluation153 pub fn evaluate(&self) -> Result<T> {154 self.0.get()155 }156}157158pub trait ThunkMapper<Input>: Trace {159 type Output;160 fn map(self, from: Input) -> Result<Self::Output>;161}162impl<Input> Thunk<Input>163where164 Input: Trace,165{166 pub fn map<M>(self, mapper: M) -> Thunk<M::Output>167 where168 M: ThunkMapper<Input>,169 M::Output: Trace + Clone,170 {171 let inner = self;172 Thunk!(move || {173 let value = inner.evaluate()?;174 let mapped = mapper.map(value)?;175 Ok(mapped)176 })177 }178}179180impl<T: Trace + Clone> From<Result<T>> for Thunk<T> {181 fn from(value: Result<T>) -> Self {182 match value {183 Ok(o) => Self::evaluated(o),184 Err(e) => Self::errored(e),185 }186 }187}188impl<T, V: Trace> From<T> for Thunk<V>189where190 T: ThunkValue<Output = V>,191{192 fn from(value: T) -> Self {193 Self::new(value)194 }195}196197impl<T: Trace + Default + Clone> Default for Thunk<T> {198 fn default() -> Self {199 Self::evaluated(T::default())200 }201}202203#[derive(Trace, Clone)]204pub struct CachedUnbound<I, T>205where206 I: Unbound<Bound = T>,207 T: Trace,208{209 cache: Cc<RefCell<FxHashMap<WeakSupThis, T>>>,210 value: I,211}212impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {213 pub fn new(value: I) -> Self {214 Self {215 cache: Cc::new(RefCell::new(FxHashMap::new())),216 value,217 }218 }219}220impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {221 type Bound = T;222 fn bind(&self, sup_this: SupThis) -> Result<T> {223 let cache_key = sup_this.clone().downgrade();224 {225 if let Some(t) = self.cache.borrow().get(&cache_key) {226 return Ok(t.clone());227 }228 }229 let bound = self.value.bind(sup_this)?;230231 {232 let mut cache = self.cache.borrow_mut();233 cache.insert(cache_key, bound.clone());234 }235236 Ok(bound)237 }238}239240impl<T: Debug + Trace> Debug for Thunk<T> {241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {242 write!(f, "Lazy")243 }244}245impl<T: Trace> PartialEq for Thunk<T> {246 fn eq(&self, other: &Self) -> bool {247 Cc::ptr_eq(&self.0, &other.0)248 }249}250251/// Represents a Jsonnet value, which can be sliced or indexed (string or array).252#[allow(clippy::module_name_repetitions)]253pub enum IndexableVal {254 /// String.255 Str(IStr),256 /// Array.257 Arr(ArrValue),258}259impl IndexableVal {260 pub fn is_empty(&self) -> bool {261 match self {262 Self::Str(s) => s.is_empty(),263 Self::Arr(s) => s.is_empty(),264 }265 }266267 pub fn to_array(self) -> ArrValue {268 match self {269 Self::Str(s) => ArrValue::chars(s.chars()),270 Self::Arr(arr) => arr,271 }272 }273 /// Slice the value.274 ///275 /// # Implementation276 ///277 /// For strings, will create a copy of specified interval.278 ///279 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.280 pub fn slice(281 self,282 index: Option<i32>,283 end: Option<i32>,284 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,285 ) -> Result<Self> {286 match &self {287 Self::Str(s) => {288 let mut computed_len = None;289 let mut get_len = || {290 computed_len.unwrap_or_else(|| {291 let len = s.chars().count();292 let _ = computed_len.insert(len);293 len294 })295 };296 let mut get_idx = |pos: Option<i32>, default| {297 match pos {298 #[expect(clippy::cast_sign_loss, reason = "abs value is used")]299 Some(v) if v < 0 => get_len().saturating_sub((-v as isize) as usize),300 // No need to clamp, as iterator interface is used301 #[expect(clippy::cast_sign_loss, reason = "abs value is used")]302 Some(v) => v as usize,303 None => default,304 }305 };306307 let index = get_idx(index, 0);308 let end = get_idx(end, usize::MAX);309 let step = step.as_deref().copied().unwrap_or(1);310311 if index >= end {312 return Ok(Self::Str("".into()));313 }314315 Ok(Self::Str(316 (s.chars()317 .skip(index)318 .take(end - index)319 .step_by(step)320 .collect::<String>())321 .into(),322 ))323 }324 Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice(325 index,326 end,327 #[expect(328 clippy::cast_possible_truncation,329 reason = "overflow will result with skip too large which would be equivalent"330 )]331 step.map(|v| NonZeroU32::new(v.value() as u32).expect("bounded != 0")),332 ))),333 }334 }335}336337#[derive(Debug, Clone, Acyclic)]338pub enum StrValue {339 Flat(IStr),340 Tree(Rc<(StrValue, StrValue, usize)>),341}342impl StrValue {343 pub fn concat(a: Self, b: Self) -> Self {344 // TODO: benchmark for an optimal value, currently just a arbitrary choice345 const STRING_EXTEND_THRESHOLD: usize = 100;346347 if a.is_empty() {348 b349 } else if b.is_empty() {350 a351 } else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {352 Self::Flat(format!("{a}{b}").into())353 } else {354 let len = a.len() + b.len();355 Self::Tree(Rc::new((a, b, len)))356 }357 }358 pub fn into_flat(&self) -> IStr {359 #[cold]360 fn write_buf(s: &StrValue, out: &mut String) {361 match s {362 StrValue::Flat(f) => out.push_str(f),363 StrValue::Tree(t) => {364 write_buf(&t.0, out);365 write_buf(&t.1, out);366 }367 }368 }369 match self {370 Self::Flat(f) => f.clone(),371 Self::Tree(_) => {372 let mut buf = String::with_capacity(self.len());373 write_buf(self, &mut buf);374 buf.into()375 }376 }377 }378 pub fn len(&self) -> usize {379 match self {380 Self::Flat(v) => v.len(),381 Self::Tree(t) => t.2,382 }383 }384 pub fn is_empty(&self) -> bool {385 match self {386 Self::Flat(v) => v.is_empty(),387 // Can't create non-flat empty string388 Self::Tree(_) => false,389 }390 }391}392impl<T> From<T> for StrValue393where394 IStr: From<T>,395{396 fn from(value: T) -> Self {397 Self::Flat(IStr::from(value))398 }399}400impl Display for StrValue {401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {402 match self {403 Self::Flat(v) => write!(f, "{v}"),404 Self::Tree(t) => {405 write!(f, "{}", t.0)?;406 write!(f, "{}", t.1)407 }408 }409 }410}411impl PartialEq for StrValue {412 // False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.413 #[allow(clippy::unconditional_recursion)]414 fn eq(&self, other: &Self) -> bool {415 let a = self.clone().into_flat();416 let b = other.clone().into_flat();417 a == b418 }419}420impl Eq for StrValue {}421impl PartialOrd for StrValue {422 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {423 Some(self.cmp(other))424 }425}426impl Ord for StrValue {427 fn cmp(&self, other: &Self) -> Ordering {428 let a = self.clone().into_flat();429 let b = other.clone().into_flat();430 a.cmp(&b)431 }432}433434/// Represents jsonnet number435/// Jsonnet numbers are finite f64, with NaNs disallowed436#[derive(Trace, Clone, Copy)]437#[repr(transparent)]438pub struct NumValue(f64);439impl NumValue {440 /// Creates a [`NumValue`], if value is finite and not NaN441 pub fn new(v: f64) -> Option<Self> {442 if !v.is_finite() {443 return None;444 }445 Some(Self(v))446 }447 #[inline]448 pub const fn get(&self) -> f64 {449 self.0450 }451 pub(crate) fn truncate_for_bitwise(self) -> Result<i64> {452 if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {453 bail!("numberic value outside of safe integer range for bitwise operation");454 }455 #[expect(clippy::cast_possible_truncation, reason = "intended")]456 Ok(self.0 as i64)457 }458}459impl PartialEq for NumValue {460 fn eq(&self, other: &Self) -> bool {461 self.0 == other.0462 }463}464impl Eq for NumValue {}465impl Ord for NumValue {466 #[inline]467 fn cmp(&self, other: &Self) -> Ordering {468 // Can't use `total_cmp`: its behavior for `-0` and `0`469 // is not following wanted.470 unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }471 }472}473impl PartialOrd for NumValue {474 #[inline]475 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {476 Some(self.cmp(other))477 }478}479impl Debug for NumValue {480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {481 Debug::fmt(&self.0, f)482 }483}484impl Display for NumValue {485 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {486 Display::fmt(&self.0, f)487 }488}489impl Deref for NumValue {490 type Target = f64;491492 #[inline]493 fn deref(&self) -> &Self::Target {494 &self.0495 }496}497macro_rules! impl_num {498 ($($ty:ty),+) => {$(499 impl From<$ty> for NumValue {500 #[inline]501 fn from(value: $ty) -> Self {502 Self(value.into())503 }504 }505 )+};506}507impl_num!(i8, u8, i16, u16, i32, u32);508509#[derive(Clone, Copy, Debug, Error, Trace)]510pub enum ConvertNumValueError {511 #[error("overflow")]512 Overflow,513 #[error("underflow")]514 Underflow,515 #[error("non-finite")]516 NonFinite,517}518impl From<ConvertNumValueError> for Error {519 fn from(e: ConvertNumValueError) -> Self {520 Self::new(e.into())521 }522}523524macro_rules! impl_try_num {525 ($($ty:ty),+) => {$(526 impl TryFrom<$ty> for NumValue {527 type Error = ConvertNumValueError;528 #[inline]529 fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {530 #[expect(clippy::cast_precision_loss, reason = "precision loss is explicitly handled")]531 let value = value as f64;532 if value < MIN_SAFE_INTEGER {533 return Err(ConvertNumValueError::Underflow)534 } else if value > MAX_SAFE_INTEGER {535 return Err(ConvertNumValueError::Overflow)536 }537 // Number is finite.538 Ok(Self(value))539 }540 }541 )+};542}543impl_try_num!(usize, isize, i64, u64);544545impl TryFrom<f64> for NumValue {546 type Error = ConvertNumValueError;547548 #[inline]549 fn try_from(value: f64) -> Result<Self, Self::Error> {550 Self::new(value).ok_or(ConvertNumValueError::NonFinite)551 }552}553impl TryFrom<f32> for NumValue {554 type Error = ConvertNumValueError;555556 #[inline]557 fn try_from(value: f32) -> Result<Self, Self::Error> {558 Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)559 }560}561562/// Represents any valid Jsonnet value.563#[derive(Debug, Clone, Trace, Default)]564pub enum Val {565 /// Represents a Jsonnet boolean.566 Bool(bool),567 /// Represents a Jsonnet null value.568 #[default]569 Null,570 /// Represents a Jsonnet string.571 Str(StrValue),572 /// Represents a Jsonnet number.573 /// Should be finite, and not NaN574 /// This restriction isn't enforced by enum, as enum field can't be marked as private575 Num(NumValue),576 /// Experimental bigint577 #[cfg(feature = "exp-bigint")]578 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),579 /// Represents a Jsonnet array.580 Arr(ArrValue),581 /// Represents a Jsonnet object.582 Obj(ObjValue),583 /// Represents a Jsonnet function.584 Func(FuncVal),585}586587#[cfg(target_pointer_width = "64")]588static_assertions::assert_eq_size!(Val, [u8; 24]);589590impl From<IndexableVal> for Val {591 fn from(v: IndexableVal) -> Self {592 match v {593 IndexableVal::Str(s) => Self::string(s),594 IndexableVal::Arr(a) => Self::Arr(a),595 }596 }597}598599impl Val {600 pub const fn as_bool(&self) -> Option<bool> {601 match self {602 Self::Bool(v) => Some(*v),603 _ => None,604 }605 }606 pub const fn as_null(&self) -> Option<()> {607 match self {608 Self::Null => Some(()),609 _ => None,610 }611 }612 pub fn as_str(&self) -> Option<IStr> {613 match self {614 Self::Str(s) => Some(s.clone().into_flat()),615 _ => None,616 }617 }618 pub const fn as_num(&self) -> Option<f64> {619 match self {620 Self::Num(n) => Some(n.get()),621 _ => None,622 }623 }624 #[cfg(feature = "exp-bigint")]625 pub fn as_bigint(&self) -> Option<num_bigint::BigInt> {626 match self {627 Self::BigInt(n) => Some(*n.clone()),628 _ => None,629 }630 }631 pub fn as_arr(&self) -> Option<ArrValue> {632 match self {633 Self::Arr(a) => Some(a.clone()),634 _ => None,635 }636 }637 pub fn as_obj(&self) -> Option<ObjValue> {638 match self {639 Self::Obj(o) => Some(o.clone()),640 _ => None,641 }642 }643 pub fn as_func(&self) -> Option<FuncVal> {644 match self {645 Self::Func(f) => Some(f.clone()),646 _ => None,647 }648 }649650 pub const fn value_type(&self) -> ValType {651 match self {652 Self::Str(..) => ValType::Str,653 Self::Num(..) => ValType::Num,654 #[cfg(feature = "exp-bigint")]655 Self::BigInt(..) => ValType::BigInt,656 Self::Arr(..) => ValType::Arr,657 Self::Obj(..) => ValType::Obj,658 Self::Bool(_) => ValType::Bool,659 Self::Null => ValType::Null,660 Self::Func(..) => ValType::Func,661 }662 }663664 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {665 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {666 manifest.manifest(val.clone())667 }668 manifest_dyn(self, &format)669 }670671 pub fn to_string(&self) -> Result<IStr> {672 Ok(match self {673 Self::Bool(true) => "true".into(),674 Self::Bool(false) => "false".into(),675 Self::Null => "null".into(),676 Self::Str(s) => s.clone().into_flat(),677 _ => self.manifest(ToStringFormat).map(IStr::from)?,678 })679 }680681 pub fn into_indexable(self) -> Result<IndexableVal> {682 Ok(match self {683 Self::Str(s) => IndexableVal::Str(s.into_flat()),684 Self::Arr(arr) => IndexableVal::Arr(arr),685 _ => bail!(ValueIsNotIndexable(self.value_type())),686 })687 }688689 pub fn function(function: impl Into<FuncVal>) -> Self {690 Self::Func(function.into())691 }692 pub fn string(string: impl Into<StrValue>) -> Self {693 Self::Str(string.into())694 }695 pub fn num(num: impl Into<NumValue>) -> Self {696 Self::Num(num.into())697 }698 pub fn try_num<V, E>(num: V) -> Result<Self, E>699 where700 NumValue: TryFrom<V, Error = E>,701 {702 Ok(Self::Num(num.try_into()?))703 }704 pub fn arr(a: impl ArrayLike) -> Self {705 Self::Arr(ArrValue::new(a))706 }707}708709impl From<IStr> for Val {710 fn from(value: IStr) -> Self {711 Self::string(value)712 }713}714impl From<String> for Val {715 fn from(value: String) -> Self {716 Self::string(value)717 }718}719impl From<&str> for Val {720 fn from(value: &str) -> Self {721 Self::string(value)722 }723}724impl From<ObjValue> for Val {725 fn from(value: ObjValue) -> Self {726 Self::Obj(value)727 }728}729730const fn is_function_like(val: &Val) -> bool {731 matches!(val, Val::Func(_))732}733734/// Native implementation of `std.primitiveEquals`735pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {736 Ok(match (val_a, val_b) {737 (Val::Bool(a), Val::Bool(b)) => a == b,738 (Val::Null, Val::Null) => true,739 (Val::Str(a), Val::Str(b)) => a == b,740 (Val::Num(a), Val::Num(b)) => (a.get() - b.get()).abs() <= f64::EPSILON,741 #[cfg(feature = "exp-bigint")]742 (Val::BigInt(a), Val::BigInt(b)) => a == b,743 (Val::Arr(_), Val::Arr(_)) => {744 bail!("primitiveEquals operates on primitive types, got array")745 }746 (Val::Obj(_), Val::Obj(_)) => {747 bail!("primitiveEquals operates on primitive types, got object")748 }749 (a, b) if is_function_like(a) && is_function_like(b) => {750 bail!("cannot test equality of functions")751 }752 (_, _) => false,753 })754}755756/// Native implementation of `std.equals`757pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {758 if val_a.value_type() != val_b.value_type() {759 return Ok(false);760 }761 match (val_a, val_b) {762 (Val::Arr(a), Val::Arr(b)) => {763 if ArrValue::ptr_eq(a, b) {764 return Ok(true);765 }766 if a.len() != b.len() {767 return Ok(false);768 }769 for (a, b) in a.iter().zip(b.iter()) {770 if !equals(&a?, &b?)? {771 return Ok(false);772 }773 }774 Ok(true)775 }776 (Val::Obj(a), Val::Obj(b)) => {777 if ObjValue::ptr_eq(a, b) {778 return Ok(true);779 }780 let fields = a.fields(781 #[cfg(feature = "exp-preserve-order")]782 false,783 );784 if fields785 != b.fields(786 #[cfg(feature = "exp-preserve-order")]787 false,788 ) {789 return Ok(false);790 }791 for field in fields {792 if !equals(793 &a.get(field.clone())?.expect("field exists"),794 &b.get(field)?.expect("field exists"),795 )? {796 return Ok(false);797 }798 }799 Ok(true)800 }801 (a, b) => Ok(primitive_equals(a, b)?),802 }803}crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -34,7 +34,7 @@
for _ in 0..*sz {
out.push(trivial.clone());
}
- Ok(ArrValue::eager(out))
+ Ok(ArrValue::new(out))
},
)
}
@@ -256,7 +256,7 @@
pub fn builtin_lines(arr: ArrValue) -> Result<IndexableVal> {
builtin_join(
IndexableVal::Str("\n".into()),
- ArrValue::extended(arr, ArrValue::eager(vec![Val::string("")])),
+ ArrValue::extended(arr, ArrValue::new(vec![Val::string("")])),
)
}
@@ -468,7 +468,7 @@
out.push(ele);
}
}
- Val::Arr(ArrValue::eager(out))
+ Val::arr(out)
}
Val::Obj(o) => {
let mut out = ObjValueBuilder::new();
crates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -29,7 +29,11 @@
#[builtin]
#[allow(non_snake_case, clippy::redundant_closure)]
-pub fn builtin_set_inter(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
+pub fn builtin_set_inter(
+ a: ArrValue,
+ b: ArrValue,
+ #[default] keyF: KeyF,
+) -> Result<Vec<Thunk<Val>>> {
let mut a = a.iter_lazy();
let mut b = b.iter_lazy();
@@ -60,12 +64,16 @@
}
}
}
- Ok(ArrValue::lazy(out))
+ Ok(out)
}
#[builtin]
#[allow(non_snake_case, clippy::redundant_closure)]
-pub fn builtin_set_diff(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
+pub fn builtin_set_diff(
+ a: ArrValue,
+ b: ArrValue,
+ #[default] keyF: KeyF,
+) -> Result<Vec<Thunk<Val>>> {
let mut a = a.iter_lazy();
let mut b = b.iter_lazy();
@@ -103,12 +111,16 @@
av = a.next();
ak = av.clone().map(keyF).transpose()?;
}
- Ok(ArrValue::lazy(out))
+ Ok(out)
}
#[builtin]
#[allow(non_snake_case, clippy::redundant_closure)]
-pub fn builtin_set_union(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
+pub fn builtin_set_union(
+ a: ArrValue,
+ b: ArrValue,
+ #[default] keyF: KeyF,
+) -> Result<Vec<Thunk<Val>>> {
let mut a = a.iter_lazy();
let mut b = b.iter_lazy();
@@ -154,5 +166,5 @@
bv = b.next();
bk = bv.clone().map(keyF).transpose()?;
}
- Ok(ArrValue::lazy(out))
+ Ok(out)
}
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -113,11 +113,11 @@
return Ok(values);
}
if key_getter.is_identity() {
- Ok(ArrValue::eager(sort_identity(
+ Ok(ArrValue::new(sort_identity(
values.iter().collect::<Result<Vec<Val>>>()?,
)?))
} else {
- Ok(ArrValue::lazy(sort_keyf(values, key_getter)?))
+ Ok(ArrValue::new(sort_keyf(values, key_getter)?))
}
}
@@ -162,11 +162,11 @@
return Ok(arr);
}
if keyF.is_identity() {
- Ok(ArrValue::eager(uniq_identity(
+ Ok(ArrValue::new(uniq_identity(
arr.iter().collect::<Result<Vec<Val>>>()?,
)?))
} else {
- Ok(ArrValue::lazy(uniq_keyf(arr, keyF)?))
+ Ok(ArrValue::new(uniq_keyf(arr, keyF)?))
}
}
@@ -180,11 +180,11 @@
let arr = arr.iter().collect::<Result<Vec<Val>>>()?;
let arr = sort_identity(arr)?;
let arr = uniq_identity(arr)?;
- Ok(ArrValue::eager(arr))
+ Ok(ArrValue::new(arr))
} else {
let arr = sort_keyf(arr, keyF.clone())?;
- let arr = uniq_keyf(ArrValue::lazy(arr), keyF)?;
- Ok(ArrValue::lazy(arr))
+ let arr = uniq_keyf(ArrValue::new(arr), keyF)?;
+ Ok(ArrValue::new(arr))
}
}