difftreelog
refactor split Typed into FromUntyped and IntoUntyped
in: master
20 files changed
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -6,7 +6,7 @@
use jrsonnet_evaluator::{
error::{Error, ErrorKind},
function::builtin::{NativeCallback, NativeCallbackHandler},
- typed::Typed,
+ typed::FromUntyped as _,
IStr, Val,
};
cmds/jrsonnet/Cargo.tomldiffbeforeafterboth--- a/cmds/jrsonnet/Cargo.toml
+++ b/cmds/jrsonnet/Cargo.toml
@@ -11,10 +11,6 @@
workspace = true
[features]
-default = [
- "exp-regex",
-]
-
experimental = [
"exp-preserve-order",
"exp-destruct",
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -5,11 +5,11 @@
rc::Rc,
};
-use jrsonnet_gcmodule::{cc_dyn, Cc, Trace};
+use jrsonnet_gcmodule::{cc_dyn, Cc};
use jrsonnet_interner::IBytes;
use jrsonnet_parser::{Expr, Spanned};
-use crate::{function::NativeFn, typed::Typed, Context, Result, Thunk, Val};
+use crate::{function::NativeFn, Context, Result, Thunk, Val};
mod spec;
pub use spec::{ArrayLike, *};
@@ -241,4 +241,3 @@
self.0.is_cheap()
}
}
-
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -8,8 +8,11 @@
use super::ArrValue;
use crate::function::NativeFn;
use crate::{
- error::ErrorKind::InfiniteRecursionDetected, evaluate, typed::Typed, val::ThunkValue, Context,
- Error, ObjValue, Result, Thunk, Val,
+ error::ErrorKind::InfiniteRecursionDetected,
+ evaluate,
+ typed::{IntoUntyped, Typed},
+ val::ThunkValue,
+ Context, Error, ObjValue, Result, Thunk, Val,
};
pub trait ArrayLike: Any + Trace + Debug {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -20,7 +20,7 @@
function::{CallLocation, FuncDesc, FuncVal},
gc::WithCapacityExt as _,
in_frame,
- typed::Typed,
+ typed::{FromUntyped, IntoUntyped as _, Typed},
val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
ResultExt, SupThis, Unbound, Val,
@@ -620,7 +620,7 @@
}
}
Slice(slice) => {
- fn parse_idx<T: Typed>(
+ fn parse_idx<T: Typed + FromUntyped>(
loc: CallLocation<'_>,
ctx: Context,
expr: Option<&Spanned<Expr>>,
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -8,7 +8,7 @@
error::ErrorKind::*,
evaluate,
stdlib::std_format,
- typed::Typed,
+ typed::IntoUntyped as _,
val::{equals, StrValue},
Context, Result, Val,
};
crates/jrsonnet-evaluator/src/function/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/native.rs
+++ b/crates/jrsonnet-evaluator/src/function/native.rs
@@ -3,7 +3,11 @@
use jrsonnet_gcmodule::Trace;
use super::PreparedFuncVal;
-use crate::{bail, function::FuncVal, typed::Typed, CallLocation, Result, Val};
+use crate::{
+ function::FuncVal,
+ typed::{FromUntyped, IntoUntyped, Typed},
+ CallLocation, Result, Val,
+};
use jrsonnet_types::{ComplexValType, ValType};
#[derive(Debug, Trace, Clone)]
@@ -12,8 +16,8 @@
($i:expr; $($gen:ident)*) => {
impl<$($gen,)* O> NativeFn<($($gen,)* O,)>
where
- $($gen: Typed,)*
- O: Typed,
+ $($gen: Typed + IntoUntyped,)*
+ O: Typed + FromUntyped,
{
#[allow(non_snake_case, clippy::too_many_arguments)]
pub fn call(
@@ -22,7 +26,7 @@
) -> Result<O> {
let val = self.0.call(
CallLocation::native(),
- &[$(Typed::into_lazy_untyped($gen),)*],
+ &[$(IntoUntyped::into_lazy_untyped($gen),)*],
&[],
)?;
O::from_untyped(val)
@@ -30,11 +34,9 @@
}
impl<$($gen,)* O> Typed for NativeFn<($($gen,)* O,)> {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
-
- fn into_untyped(_typed: Self) -> Result<Val> {
- bail!("can only convert functions from jsonnet to native")
- }
+ }
+ impl<$($gen,)* O> FromUntyped for NativeFn<($($gen,)* O,)> {
fn from_untyped(untyped: Val) -> Result<Self> {
let func = FuncVal::from_untyped(untyped)?;
Ok(Self(
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -9,7 +9,7 @@
use crate::{
bail,
error::{format_found, suggest_object_fields, ErrorKind::*},
- typed::Typed,
+ typed::FromUntyped,
Error, ObjValue, 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
@@ -1,6 +1,6 @@
use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};
-use jrsonnet_gcmodule::{Cc, Trace};
+use jrsonnet_gcmodule::Trace;
use jrsonnet_interner::{IBytes, IStr};
pub use jrsonnet_macros::Typed;
use jrsonnet_types::{ComplexValType, ValType};
@@ -8,17 +8,17 @@
use crate::{
arr::{ArrValue, BytesArray},
bail,
- function::{FuncDesc, FuncVal},
+ function::FuncVal,
typed::CheckType,
val::{IndexableVal, NumValue, StrValue, ThunkMapper},
ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
};
#[derive(Trace)]
-struct FromUntyped<K: Trace>(PhantomData<fn() -> K>);
-impl<K> ThunkMapper<Val> for FromUntyped<K>
+struct ThunkFromUntyped<K: Trace>(PhantomData<fn() -> K>);
+impl<K> ThunkMapper<Val> for ThunkFromUntyped<K>
where
- K: Typed + Trace,
+ K: Typed + FromUntyped + Trace,
{
type Output = K;
@@ -26,12 +26,29 @@
K::from_untyped(from)
}
}
-impl<K: Trace> Default for FromUntyped<K> {
+impl<K: Trace> Default for ThunkFromUntyped<K> {
fn default() -> Self {
Self(PhantomData)
}
}
+#[derive(Trace)]
+struct ThunkIntoUntyped<K: Trace>(PhantomData<fn() -> K>);
+impl<K> ThunkMapper<K> for ThunkIntoUntyped<K>
+where
+ K: Typed + Trace + IntoUntyped,
+{
+ type Output = Val;
+ fn map(self, from: K) -> Result<Self::Output> {
+ K::into_untyped(from)
+ }
+}
+impl<K: Trace> Default for ThunkIntoUntyped<K> {
+ fn default() -> Self {
+ Self(PhantomData)
+ }
+}
+
pub trait TypedObj: Typed {
fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;
fn parse(obj: &ObjValue) -> Result<Self>;
@@ -44,31 +61,41 @@
pub trait Typed: Sized {
const TYPE: &'static ComplexValType;
+}
+pub trait IntoUntyped: Typed {
+ // Whatever caller should use `into_lazy_untyped` instead of `into_untyped`
+ fn provides_lazy() -> bool {
+ false
+ }
fn into_untyped(typed: Self) -> Result<Val>;
fn into_lazy_untyped(typed: Self) -> Thunk<Val> {
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
+ #[doc(hidden)]
+ fn into_untyped_result(typed: Self) -> Result<Val>;
+}
+impl<T> IntoUntypedResult for T
+where
+ T: IntoUntyped,
+{
+ fn into_untyped_result(typed: Self) -> Result<Val> {
+ T::into_untyped(typed)
+ }
+}
+
+pub trait FromUntyped: Typed {
fn from_untyped(untyped: Val) -> Result<Self>;
fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {
Self::from_untyped(lazy.evaluate()?)
}
- // Whatever caller should use `into_lazy_untyped` instead of `into_untyped`
- fn provides_lazy() -> bool {
- false
- }
-
// Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible
fn wants_lazy() -> bool {
false
- }
-
- /// 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
- #[doc(hidden)]
- fn into_result(typed: Self) -> Result<Val> {
- let value = Self::into_untyped(typed)?;
- Ok(value)
}
}
@@ -77,38 +104,30 @@
T: Typed + Trace + Clone,
{
const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);
+}
+impl<T> IntoUntyped for Thunk<T>
+where
+ T: Typed + IntoUntyped + Trace + Clone,
+{
fn into_untyped(typed: Self) -> Result<Val> {
T::into_untyped(typed.evaluate()?)
- }
-
- fn from_untyped(untyped: Val) -> Result<Self> {
- Self::from_lazy_untyped(Thunk::evaluated(untyped))
}
-
fn provides_lazy() -> bool {
true
}
fn into_lazy_untyped(inner: Self) -> Thunk<Val> {
- #[derive(Trace)]
- struct IntoUntyped<K: Trace>(PhantomData<fn() -> K>);
- impl<K> ThunkMapper<K> for IntoUntyped<K>
- where
- K: Typed + Trace,
- {
- type Output = Val;
+ inner.map(<ThunkIntoUntyped<T>>::default())
+ }
+}
- fn map(self, from: K) -> Result<Self::Output> {
- K::into_untyped(from)
- }
- }
- impl<K: Trace> Default for IntoUntyped<K> {
- fn default() -> Self {
- Self(PhantomData)
- }
- }
- inner.map(<IntoUntyped<T>>::default())
+impl<T> FromUntyped for Thunk<T>
+where
+ T: Typed + FromUntyped + Trace + Clone,
+{
+ fn from_untyped(untyped: Val) -> Result<Self> {
+ Self::from_lazy_untyped(Thunk::evaluated(untyped))
}
fn wants_lazy() -> bool {
@@ -116,7 +135,7 @@
}
fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {
- Ok(inner.map(<FromUntyped<T>>::default()))
+ Ok(inner.map(<ThunkFromUntyped<T>>::default()))
}
}
@@ -128,6 +147,8 @@
impl Typed for $ty {
const TYPE: &'static ComplexValType =
&ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));
+ }
+ impl FromUntyped for $ty {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -145,6 +166,8 @@
_ => unreachable!(),
}
}
+ }
+ impl IntoUntyped for $ty {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::Num(value.into()))
}
@@ -183,7 +206,9 @@
Some(MIN as f64),
Some(MAX as f64),
);
+ }
+ impl<const MIN: $ty, const MAX: $ty> FromUntyped for $name<MIN, MAX> {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -201,7 +226,9 @@
_ => unreachable!(),
}
}
+ }
+ impl<const MIN: $ty, const MAX: $ty> IntoUntyped for $name<MIN, MAX> {
#[allow(clippy::cast_lossless)]
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::try_num(value.0)?)
@@ -220,11 +247,13 @@
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 FromUntyped for f64 {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -237,11 +266,13 @@
pub struct PositiveF64(pub f64);
impl Typed for PositiveF64 {
const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);
-
+}
+impl IntoUntyped for PositiveF64 {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::try_num(value.0)?)
}
-
+}
+impl FromUntyped for PositiveF64 {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -253,11 +284,13 @@
impl Typed for usize {
const TYPE: &'static ComplexValType =
&ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));
-
+}
+impl IntoUntyped for usize {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::try_num(value)?)
}
-
+}
+impl FromUntyped for usize {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -276,11 +309,13 @@
impl Typed for IStr {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
-
+}
+impl IntoUntyped for IStr {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::string(value))
}
-
+}
+impl FromUntyped for IStr {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -292,11 +327,13 @@
impl Typed for String {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
-
+}
+impl IntoUntyped for String {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::string(value))
}
-
+}
+impl FromUntyped for String {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -308,11 +345,13 @@
impl Typed for StrValue {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
-
+}
+impl IntoUntyped for StrValue {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::Str(value))
}
-
+}
+impl FromUntyped for StrValue {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -324,11 +363,13 @@
impl Typed for char {
const TYPE: &'static ComplexValType = &ComplexValType::Char;
-
+}
+impl IntoUntyped for char {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::string(value))
}
-
+}
+impl FromUntyped for char {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -338,12 +379,14 @@
}
}
+// TODO: View into vec using ArrayLike?
impl<T> Typed for Vec<T>
where
T: Typed,
{
const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);
-
+}
+impl<T: Typed + IntoUntyped> IntoUntyped for Vec<T> {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::Arr(
value
@@ -352,7 +395,8 @@
.collect::<Result<ArrValue>>()?,
))
}
-
+}
+impl<T: Typed + FromUntyped> FromUntyped for Vec<T> {
fn from_untyped(value: Val) -> Result<Self> {
let Val::Arr(a) = value else {
<Self as Typed>::TYPE.check(&value)?;
@@ -369,9 +413,19 @@
}
}
-impl<K: Typed + Ord, V: Typed> Typed for BTreeMap<K, V> {
+// TODO: View into BTreeMap using ObjectCore?
+impl<K, V> Typed for BTreeMap<K, V>
+where
+ K: Typed + Ord,
+ V: Typed,
+{
const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);
-
+}
+impl<K, V> IntoUntyped for BTreeMap<K, V>
+where
+ K: Typed + Ord + IntoUntyped,
+ V: Typed + IntoUntyped,
+{
fn into_untyped(typed: Self) -> Result<Val> {
let mut out = ObjValueBuilder::with_capacity(typed.len());
for (k, v) in typed {
@@ -383,7 +437,12 @@
}
Ok(Val::Obj(out.build()))
}
-
+}
+impl<K, V> FromUntyped for BTreeMap<K, V>
+where
+ K: FromUntyped + Ord,
+ V: FromUntyped,
+{
fn from_untyped(value: Val) -> Result<Self> {
Self::TYPE.check(&value)?;
let obj = value.as_obj().expect("typecheck should fail");
@@ -416,32 +475,27 @@
impl Typed for Val {
const TYPE: &'static ComplexValType = &ComplexValType::Any;
-
+}
+impl IntoUntyped for Val {
fn into_untyped(typed: Self) -> Result<Val> {
Ok(typed)
}
+}
+impl FromUntyped for Val {
fn from_untyped(untyped: Val) -> Result<Self> {
Ok(untyped)
}
}
-// Hack
#[doc(hidden)]
impl<T> Typed for Result<T>
where
T: Typed,
{
const TYPE: &'static ComplexValType = &ComplexValType::Any;
-
- fn into_untyped(_typed: Self) -> Result<Val> {
- panic!("do not use this conversion")
- }
-
- fn from_untyped(_untyped: Val) -> Result<Self> {
- panic!("do not use this conversion")
- }
-
- fn into_result(typed: Self) -> Result<Val> {
+}
+impl<T: IntoUntyped> IntoUntypedResult for Result<T> {
+ fn into_untyped_result(typed: Self) -> Result<Val> {
typed.map(T::into_untyped)?
}
}
@@ -450,11 +504,13 @@
impl Typed for IBytes {
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(ArrValue::bytes(value)))
}
-
+}
+impl FromUntyped for IBytes {
fn from_untyped(value: Val) -> Result<Self> {
let Val::Arr(a) = &value else {
<Self as Typed>::TYPE.check(&value)?;
@@ -477,11 +533,13 @@
pub struct M1;
impl Typed for M1 {
const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));
-
+}
+impl IntoUntyped for M1 {
fn into_untyped(_: Self) -> Result<Val> {
Ok(Val::Num(NumValue::new(-1.0).expect("finite")))
}
-
+}
+impl FromUntyped for M1 {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
Ok(Self)
@@ -499,13 +557,22 @@
$($id: Typed,)*
{
const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);
-
+ }
+ impl<$($id),*> IntoUntyped for $name<$($id),*>
+ where
+ $($id: Typed + IntoUntyped,)*
+ {
fn into_untyped(value: Self) -> Result<Val> {
match value {$(
$name::$id(v) => $id::into_untyped(v)
),*}
}
+ }
+ impl<$($id),*> FromUntyped for $name<$($id),*>
+ where
+ $($id: Typed + FromUntyped,)*
+ {
fn from_untyped(value: Val) -> Result<Self> {
$(
if $id::TYPE.check(&value).is_ok() {
@@ -544,11 +611,13 @@
impl Typed for ArrValue {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
-
+}
+impl IntoUntyped for ArrValue {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::Arr(value))
}
-
+}
+impl FromUntyped for ArrValue {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -560,32 +629,17 @@
impl Typed for FuncVal {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
-
+}
+impl IntoUntyped for FuncVal {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::Func(value))
}
-
- fn from_untyped(value: Val) -> Result<Self> {
- <Self as Typed>::TYPE.check(&value)?;
- match value {
- Val::Func(a) => Ok(a),
- _ => unreachable!(),
- }
- }
}
-
-impl Typed for Cc<FuncDesc> {
- const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
-
- fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Func(FuncVal::Normal(value)))
- }
-
+impl FromUntyped for FuncVal {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
- Val::Func(FuncVal::Normal(desc)) => Ok(desc),
- Val::Func(_) => bail!("expected normal function, not builtin"),
+ Val::Func(a) => Ok(a),
_ => unreachable!(),
}
}
@@ -593,11 +647,13 @@
impl Typed for ObjValue {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);
-
+}
+impl IntoUntyped for ObjValue {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::Obj(value))
}
-
+}
+impl FromUntyped for ObjValue {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -609,11 +665,13 @@
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 FromUntyped for bool {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
@@ -622,19 +680,22 @@
}
}
}
+
impl Typed for IndexableVal {
const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[
&ComplexValType::Simple(ValType::Arr),
&ComplexValType::Simple(ValType::Str),
]);
-
+}
+impl IntoUntyped for IndexableVal {
fn into_untyped(value: Self) -> Result<Val> {
match value {
Self::Str(s) => Ok(Val::string(s)),
Self::Arr(a) => Ok(Val::Arr(a)),
}
}
-
+}
+impl FromUntyped for IndexableVal {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
value.into_indexable()
@@ -644,11 +705,13 @@
pub struct Null;
impl Typed for Null {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);
-
+}
+impl IntoUntyped for Null {
fn into_untyped(_: Self) -> Result<Val> {
Ok(Val::Null)
}
-
+}
+impl FromUntyped for Null {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
Ok(Self)
@@ -661,11 +724,19 @@
{
const TYPE: &'static ComplexValType =
&ComplexValType::UnionRef(&[&ComplexValType::Simple(ValType::Null), T::TYPE]);
-
+}
+impl<T> IntoUntyped for Option<T>
+where
+ T: Typed + IntoUntyped,
+{
fn into_untyped(typed: Self) -> Result<Val> {
typed.map_or_else(|| Ok(Val::Null), |v| T::into_untyped(v))
}
-
+}
+impl<T> FromUntyped for Option<T>
+where
+ T: Typed + FromUntyped,
+{
fn from_untyped(untyped: Val) -> Result<Self> {
if matches!(untyped, Val::Null) {
Ok(None)
@@ -677,11 +748,13 @@
impl Typed for NumValue {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
-
+}
+impl IntoUntyped for NumValue {
fn into_untyped(typed: Self) -> Result<Val> {
Ok(Val::Num(typed))
}
-
+}
+impl FromUntyped for NumValue {
fn from_untyped(untyped: Val) -> Result<Self> {
Self::TYPE.check(&untyped)?;
match untyped {
crates/jrsonnet-interner/src/names.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/names.rs
+++ b/crates/jrsonnet-interner/src/names.rs
@@ -0,0 +1 @@
+
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -8,15 +8,15 @@
parse_macro_input,
punctuated::Punctuated,
spanned::Spanned,
- token::{self, Comma},
+ token::Comma,
Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,
LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,
};
use self::typed::derive_typed_inner;
+mod names;
mod typed;
-mod names;
fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>
where
@@ -202,7 +202,7 @@
_ => {}
}
- let (optionality, ty) = if try_parse_attr_noargs(&mut arg.attrs, "default")? {
+ let (optionality, ty) = if try_parse_attr_noargs(&arg.attrs, "default")? {
remove_attr(&mut arg.attrs, "default");
(Optionality::TypeDefault, ty.clone())
} else if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {
@@ -322,7 +322,7 @@
let name = name.as_ref().map_or("<unnamed>", String::as_str);
let eval = quote! {jrsonnet_evaluator::in_description_frame(
|| format!("argument <{}> evaluation", #name),
- || <#ty>::from_untyped(value.evaluate()?),
+ || <#ty as FromUntyped>::from_untyped(value.evaluate()?),
)?};
let value = match optionality {
Optionality::Required => quote! {{
@@ -411,7 +411,7 @@
use ::jrsonnet_evaluator::{
State, Val,
function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation},
- Result, Context, typed::Typed,
+ Result, Context, typed::{Typed, FromUntyped, IntoUntypedResult},
parser::Span, params, Thunk,
};
params!(
@@ -432,7 +432,7 @@
#[allow(unused_variables)]
fn call(&self, location: CallLocation<'_>, parsed: &[Option<Thunk<Val>>]) -> Result<Val> {
let result: #result = #name(#(#pass)*);
- <_ as Typed>::into_result(result)
+ <_ as IntoUntypedResult>::into_untyped_result(result)
}
fn as_any(&self) -> &dyn ::std::any::Any {
self
crates/jrsonnet-macros/src/names.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/names.rs
+++ b/crates/jrsonnet-macros/src/names.rs
@@ -1,6 +1,5 @@
use proc_macro2::TokenStream;
use quote::quote;
-use std::cell::RefCell;
#[derive(Default)]
pub struct Names {
crates/jrsonnet-macros/src/typed.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/typed.rs
+++ b/crates/jrsonnet-macros/src/typed.rs
@@ -178,7 +178,7 @@
None
};
- __value.map(<#ty as Typed>::from_untyped).transpose()?
+ __value.map(<#ty as FromUntyped>::from_untyped).transpose()?
},
}
}
@@ -219,7 +219,7 @@
return Err(ErrorKind::NoSuchField(__names[#error_text].clone(), vec![]).into());
};
- <#ty as Typed>::from_untyped(__value)?
+ <#ty as FromUntyped>::from_untyped(__value)?
},
}
}
@@ -258,14 +258,14 @@
out.field(__names[#name].clone())
#hide
#add
- .try_thunk(<#ty as Typed>::into_lazy_untyped(value))?;
+ .try_thunk(<#ty as IntoUntyped>::into_lazy_untyped(value))?;
}
} else {
quote! {
out.field(__names[#name].clone())
#hide
#add
- .try_value(<#ty as Typed>::into_untyped(value)?)?;
+ .try_value(<#ty as IntoUntyped>::into_untyped(value)?)?;
}
};
if self.is_option {
@@ -313,18 +313,21 @@
const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[
#(#fields,)*
]);
+ }
+ impl #impl_generics FromUntyped for #ident #ty_generics #where_clause {
fn from_untyped(value: Val) -> JrResult<Self> {
let obj = value.as_obj().expect("shape is correct");
Self::parse(&obj)
}
+ }
+ impl #impl_generics IntoUntyped for #ident #ty_generics #where_clause {
fn into_untyped(value: Self) -> JrResult<Val> {
let mut out = ObjValueBuilder::with_capacity(#capacity);
value.serialize(&mut out)?;
Ok(Val::Obj(out.build()))
}
-
}
}
};
@@ -344,7 +347,7 @@
Ok(quote! {
const _: () = {
use ::jrsonnet_evaluator::{
- typed::{ComplexValType, Typed, TypedObj, CheckType},
+ typed::{ComplexValType, Typed, IntoUntyped, FromUntyped, TypedObj, CheckType},
Val, State,
error::{ErrorKind, Result as JrResult},
ObjValueBuilder, ObjValue, IStr,
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth1#![allow(non_snake_case)]23use jrsonnet_evaluator::{4 bail,5 function::{builtin, FuncVal, NativeFn},6 runtime_error,7 typed::{BoundedI32, BoundedUsize, Either2, Typed},8 val::{equals, ArrValue, IndexableVal},9 Either, IStr, ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,10};1112pub fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {13 if let Some(on_empty) = on_empty {14 on_empty.evaluate()15 } else {16 bail!("expected non-empty array")17 }18}1920#[builtin]21pub fn builtin_make_array(sz: BoundedI32<0, { i32::MAX }>, func: FuncVal) -> Result<ArrValue> {22 if *sz == 0 {23 return Ok(ArrValue::empty());24 }25 func.evaluate_trivial().map_or_else(26 // TODO: Different mapped array impl avoiding allocating unnecessary vals27 || Ok(ArrValue::range_exclusive(0, *sz).map(Typed::from_untyped(Val::Func(func))?)),28 |trivial| {29 let mut out = Vec::with_capacity(*sz as usize);30 for _ in 0..*sz {31 out.push(trivial.clone());32 }33 Ok(ArrValue::eager(out))34 },35 )36}3738#[builtin]39pub fn builtin_repeat(what: Either![IStr, ArrValue], count: usize) -> Result<Val> {40 Ok(match what {41 Either2::A(s) => Val::string(s.repeat(count)),42 Either2::B(arr) => Val::Arr(43 ArrValue::repeated(arr, count)44 .ok_or_else(|| runtime_error!("repeated length overflow"))?,45 ),46 })47}4849#[builtin]50pub fn builtin_slice(51 indexable: IndexableVal,52 index: Option<Option<i32>>,53 end: Option<Option<i32>>,54 step: Option<Option<BoundedUsize<1, { i32::MAX as usize }>>>,55) -> Result<Val> {56 indexable57 .slice(index.flatten(), end.flatten(), step.flatten())58 .map(Val::from)59}6061#[builtin]62pub fn builtin_map(func: NativeFn!((Val) -> Val), arr: IndexableVal) -> ArrValue {63 let arr = arr.to_array();64 arr.map(func)65}6667#[builtin]68pub fn builtin_map_with_index(func: NativeFn!((u32, Val) -> Val), arr: IndexableVal) -> ArrValue {69 let arr = arr.to_array();70 arr.map_with_index(func)71}7273#[builtin]74pub fn builtin_map_with_key(75 func: NativeFn!((IStr, Val) -> Val),76 obj: ObjValue,77) -> Result<ObjValue> {78 let mut out = ObjValueBuilder::new();79 for (k, v) in obj.iter(80 // Makes sense mapped object should be ordered the same way, should not break anything when the output is not ordered (the default).81 // The thrown error might be different, but jsonnet82 // does not specify the evaluation order.83 #[cfg(feature = "exp-preserve-order")]84 true,85 ) {86 let v = v?;87 out.field(k.clone()).value(func.call(k, v)?);88 }89 Ok(out.build())90}9192#[builtin]93pub fn builtin_flatmap(94 func: NativeFn!((Either![String, Val]) -> Val),95 arr: IndexableVal,96) -> Result<IndexableVal> {97 use std::fmt::Write;98 match arr {99 IndexableVal::Str(str) => {100 let mut out = String::new();101 for c in str.chars() {102 match func.call(Either2::A(c.to_string()))? {103 Val::Str(o) => write!(out, "{o}").unwrap(),104 Val::Null => {}105 _ => bail!("in std.join all items should be strings"),106 }107 }108 Ok(IndexableVal::Str(out.into()))109 }110 IndexableVal::Arr(a) => {111 let mut out = Vec::new();112 for el in a.iter() {113 let el = el?;114 match func.call(Either2::B(el))? {115 Val::Arr(o) => {116 for oe in o.iter() {117 out.push(oe?);118 }119 }120 Val::Null => {}121 _ => bail!("in std.join all items should be arrays"),122 }123 }124 Ok(IndexableVal::Arr(out.into()))125 }126 }127}128129type FilterFunc = NativeFn!((Val) -> bool);130131#[builtin]132pub fn builtin_filter(func: FilterFunc, arr: ArrValue) -> Result<ArrValue> {133 arr.filter(|val| func.call(val.clone()))134}135136#[builtin]137pub fn builtin_filter_map(138 filter_func: FilterFunc,139 map_func: NativeFn!((Val) -> Val),140 arr: ArrValue,141) -> Result<ArrValue> {142 Ok(builtin_filter(filter_func, arr)?.map(map_func))143}144145#[builtin]146pub fn builtin_foldl(147 func: NativeFn!((Val, Either![Val, char]) -> Val),148 arr: Either![ArrValue, IStr],149 init: Val,150) -> Result<Val> {151 let mut acc = init;152 match arr {153 Either2::A(arr) => {154 for i in arr.iter() {155 acc = func.call(acc, Either2::A(i?))?;156 }157 }158 Either2::B(arr) => {159 for c in arr.chars() {160 acc = func.call(acc, Either2::B(c))?;161 }162 }163 }164 Ok(acc)165}166167#[builtin]168pub fn builtin_foldr(169 func: NativeFn!((Either![Val, char], Val) -> Val),170 arr: Either![ArrValue, IStr],171 init: Val,172) -> Result<Val> {173 let mut acc = init;174 match arr {175 Either2::A(arr) => {176 for i in arr.iter().rev() {177 acc = func.call(Either2::A(i?), acc)?;178 }179 }180 Either2::B(arr) => {181 for c in arr.chars().rev() {182 acc = func.call(Either2::B(c), acc)?;183 }184 }185 }186 Ok(acc)187}188189#[builtin]190pub fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {191 if to < from {192 return Ok(ArrValue::empty());193 }194 Ok(ArrValue::range_inclusive(from, to))195}196197#[builtin]198pub fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {199 use std::fmt::Write;200 Ok(match sep {201 IndexableVal::Arr(joiner_items) => {202 let mut out = Vec::new();203204 let mut first = true;205 for item in arr.iter() {206 let item = item?.clone();207 if let Val::Arr(items) = item {208 if !first {209 out.reserve(joiner_items.len());210 // TODO: extend211 for item in joiner_items.iter() {212 out.push(item?);213 }214 }215 first = false;216 out.reserve(items.len());217 for item in items.iter() {218 out.push(item?);219 }220 } else if matches!(item, Val::Null) {221 } else {222 bail!("in std.join all items should be arrays");223 }224 }225226 IndexableVal::Arr(out.into())227 }228 IndexableVal::Str(sep) => {229 let mut out = String::new();230231 let mut first = true;232 for item in arr.iter() {233 let item = item?.clone();234 if let Val::Str(item) = item {235 if !first {236 out += &sep;237 }238 first = false;239 write!(out, "{item}").unwrap();240 } else if matches!(item, Val::Null) {241 } else {242 bail!("in std.join all items should be strings");243 }244 }245246 IndexableVal::Str(out.into())247 }248 })249}250251#[builtin]252pub fn builtin_lines(arr: ArrValue) -> Result<IndexableVal> {253 builtin_join(254 IndexableVal::Str("\n".into()),255 ArrValue::extended(arr, ArrValue::eager(vec![Val::string("")])),256 )257}258259#[builtin]260pub fn builtin_resolve_path(f: String, r: String) -> String {261 let Some(pos) = f.rfind('/') else {262 return r;263 };264 format!("{}{}", &f[..=pos], r)265}266267pub fn deep_join_inner(out: &mut String, arr: IndexableVal) -> Result<()> {268 use std::fmt::Write;269 match arr {270 IndexableVal::Str(s) => write!(out, "{s}").expect("no error"),271 IndexableVal::Arr(arr) => {272 for ele in arr.iter() {273 let indexable = IndexableVal::from_untyped(ele?)?;274 deep_join_inner(out, indexable)?;275 }276 }277 }278 Ok(())279}280281#[builtin]282pub fn builtin_deep_join(arr: IndexableVal) -> Result<String> {283 let mut out = String::new();284 deep_join_inner(&mut out, arr)?;285 Ok(out)286}287288#[builtin]289pub fn builtin_reverse(arr: ArrValue) -> ArrValue {290 arr.reversed()291}292293#[builtin]294pub fn builtin_any(arr: ArrValue) -> Result<bool> {295 for v in arr.iter() {296 let v = bool::from_untyped(v?)?;297 if v {298 return Ok(true);299 }300 }301 Ok(false)302}303304#[builtin]305pub fn builtin_all(arr: ArrValue) -> Result<bool> {306 for v in arr.iter() {307 let v = bool::from_untyped(v?)?;308 if !v {309 return Ok(false);310 }311 }312 Ok(true)313}314315#[builtin]316pub fn builtin_member(arr: IndexableVal, x: Val) -> Result<bool> {317 match arr {318 IndexableVal::Str(str) => {319 let x: IStr = IStr::from_untyped(x)?;320 Ok(!x.is_empty() && str.contains(&*x))321 }322 IndexableVal::Arr(a) => {323 for item in a.iter() {324 let item = item?;325 if equals(&item, &x)? {326 return Ok(true);327 }328 }329 Ok(false)330 }331 }332}333334#[builtin]335pub fn builtin_find(value: Val, arr: ArrValue) -> Result<Vec<usize>> {336 let mut out = Vec::new();337 for (i, ele) in arr.iter().enumerate() {338 let ele = ele?;339 if equals(&ele, &value)? {340 out.push(i);341 }342 }343 Ok(out)344}345346#[builtin]347pub fn builtin_contains(arr: IndexableVal, elem: Val) -> Result<bool> {348 builtin_member(arr, elem)349}350351#[builtin]352pub fn builtin_count(arr: ArrValue, x: Val) -> Result<usize> {353 let mut count = 0;354 for item in arr.iter() {355 if equals(&item?, &x)? {356 count += 1;357 }358 }359 Ok(count)360}361362#[builtin]363pub fn builtin_avg(arr: Vec<f64>, onEmpty: Option<Thunk<Val>>) -> Result<Val> {364 if arr.is_empty() {365 return eval_on_empty(onEmpty);366 }367 Ok(Val::try_num(arr.iter().sum::<f64>() / (arr.len() as f64))?)368}369370#[builtin]371pub fn builtin_remove_at(arr: ArrValue, at: i32) -> Result<ArrValue> {372 let newArrLeft = arr.clone().slice(None, Some(at), None);373 let newArrRight = arr.slice(Some(at + 1), None, None);374375 Ok(ArrValue::extended(newArrLeft, newArrRight))376}377378#[builtin]379pub fn builtin_remove(arr: ArrValue, elem: Val) -> Result<ArrValue> {380 for (index, item) in arr.iter().enumerate() {381 if equals(&item?, &elem)? {382 return builtin_remove_at(arr.clone(), index as i32);383 }384 }385 Ok(arr)386}387388#[builtin]389pub fn builtin_flatten_arrays(arrs: Vec<ArrValue>) -> ArrValue {390 pub fn flatten_inner(values: &[ArrValue]) -> ArrValue {391 if values.len() == 1 {392 return values[0].clone();393 } else if values.len() == 2 {394 return ArrValue::extended(values[0].clone(), values[1].clone());395 }396 let (a, b) = values.split_at(values.len() / 2);397 ArrValue::extended(flatten_inner(a), flatten_inner(b))398 }399 if arrs.is_empty() {400 return ArrValue::empty();401 } else if arrs.len() == 1 {402 return arrs.into_iter().next().expect("single");403 }404 flatten_inner(&arrs)405}406407#[builtin]408pub fn builtin_flatten_deep_array(value: Val) -> Result<Vec<Val>> {409 fn process(value: Val, out: &mut Vec<Val>) -> Result<()> {410 match value {411 Val::Arr(arr) => {412 for ele in arr.iter() {413 process(ele?, out)?;414 }415 }416 _ => out.push(value),417 }418 Ok(())419 }420 let mut out = Vec::new();421 process(value, &mut out)?;422 Ok(out)423}424425#[builtin]426pub fn builtin_prune(427 a: Val,428429 #[default(false)]430 #[cfg(feature = "exp-preserve-order")]431 preserve_order: bool,432) -> Result<Val> {433 fn is_content(val: &Val) -> bool {434 match val {435 Val::Null => false,436 Val::Arr(a) => !a.is_empty(),437 Val::Obj(o) => !o.is_empty(),438 _ => true,439 }440 }441 Ok(match a {442 Val::Arr(a) => {443 let mut out = Vec::new();444 for (i, ele) in a.iter().enumerate() {445 let ele = ele446 .and_then(|v| {447 builtin_prune(448 v,449 #[cfg(feature = "exp-preserve-order")]450 preserve_order,451 )452 })453 .with_description(|| format!("elem <{i}> pruning"))?;454 if is_content(&ele) {455 out.push(ele);456 }457 }458 Val::Arr(ArrValue::eager(out))459 }460 Val::Obj(o) => {461 let mut out = ObjValueBuilder::new();462 for (name, value) in o.iter(463 #[cfg(feature = "exp-preserve-order")]464 preserve_order,465 ) {466 let value = value467 .and_then(|v| {468 builtin_prune(469 v,470 #[cfg(feature = "exp-preserve-order")]471 preserve_order,472 )473 })474 .with_description(|| format!("field <{name}> pruning"))?;475 if !is_content(&value) {476 continue;477 }478 out.field(name).value(value);479 }480 Val::Obj(out.build())481 }482 _ => a,483 })484}1#![allow(non_snake_case)]23use jrsonnet_evaluator::{4 bail,5 function::{builtin, FuncVal, NativeFn},6 runtime_error,7 typed::{BoundedI32, BoundedUsize, Either2, FromUntyped},8 val::{equals, ArrValue, IndexableVal},9 Either, IStr, ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,10};1112pub fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {13 if let Some(on_empty) = on_empty {14 on_empty.evaluate()15 } else {16 bail!("expected non-empty array")17 }18}1920#[builtin]21pub fn builtin_make_array(sz: BoundedI32<0, { i32::MAX }>, func: FuncVal) -> Result<ArrValue> {22 if *sz == 0 {23 return Ok(ArrValue::empty());24 }25 func.evaluate_trivial().map_or_else(26 // TODO: Different mapped array impl avoiding allocating unnecessary vals27 || Ok(ArrValue::range_exclusive(0, *sz).map(FromUntyped::from_untyped(Val::Func(func))?)),28 |trivial| {29 let mut out = Vec::with_capacity(*sz as usize);30 for _ in 0..*sz {31 out.push(trivial.clone());32 }33 Ok(ArrValue::eager(out))34 },35 )36}3738#[builtin]39pub fn builtin_repeat(what: Either![IStr, ArrValue], count: usize) -> Result<Val> {40 Ok(match what {41 Either2::A(s) => Val::string(s.repeat(count)),42 Either2::B(arr) => Val::Arr(43 ArrValue::repeated(arr, count)44 .ok_or_else(|| runtime_error!("repeated length overflow"))?,45 ),46 })47}4849#[builtin]50pub fn builtin_slice(51 indexable: IndexableVal,52 index: Option<Option<i32>>,53 end: Option<Option<i32>>,54 step: Option<Option<BoundedUsize<1, { i32::MAX as usize }>>>,55) -> Result<Val> {56 indexable57 .slice(index.flatten(), end.flatten(), step.flatten())58 .map(Val::from)59}6061#[builtin]62pub fn builtin_map(func: NativeFn!((Val) -> Val), arr: IndexableVal) -> ArrValue {63 let arr = arr.to_array();64 arr.map(func)65}6667#[builtin]68pub fn builtin_map_with_index(func: NativeFn!((u32, Val) -> Val), arr: IndexableVal) -> ArrValue {69 let arr = arr.to_array();70 arr.map_with_index(func)71}7273#[builtin]74pub fn builtin_map_with_key(75 func: NativeFn!((IStr, Val) -> Val),76 obj: ObjValue,77) -> Result<ObjValue> {78 let mut out = ObjValueBuilder::new();79 for (k, v) in obj.iter(80 // Makes sense mapped object should be ordered the same way, should not break anything when the output is not ordered (the default).81 // The thrown error might be different, but jsonnet82 // does not specify the evaluation order.83 #[cfg(feature = "exp-preserve-order")]84 true,85 ) {86 let v = v?;87 out.field(k.clone()).value(func.call(k, v)?);88 }89 Ok(out.build())90}9192#[builtin]93pub fn builtin_flatmap(94 func: NativeFn!((Either![String, Val]) -> Val),95 arr: IndexableVal,96) -> Result<IndexableVal> {97 use std::fmt::Write;98 match arr {99 IndexableVal::Str(str) => {100 let mut out = String::new();101 for c in str.chars() {102 match func.call(Either2::A(c.to_string()))? {103 Val::Str(o) => write!(out, "{o}").unwrap(),104 Val::Null => {}105 _ => bail!("in std.join all items should be strings"),106 }107 }108 Ok(IndexableVal::Str(out.into()))109 }110 IndexableVal::Arr(a) => {111 let mut out = Vec::new();112 for el in a.iter() {113 let el = el?;114 match func.call(Either2::B(el))? {115 Val::Arr(o) => {116 for oe in o.iter() {117 out.push(oe?);118 }119 }120 Val::Null => {}121 _ => bail!("in std.join all items should be arrays"),122 }123 }124 Ok(IndexableVal::Arr(out.into()))125 }126 }127}128129type FilterFunc = NativeFn!((Val) -> bool);130131#[builtin]132pub fn builtin_filter(func: FilterFunc, arr: ArrValue) -> Result<ArrValue> {133 arr.filter(|val| func.call(val.clone()))134}135136#[builtin]137pub fn builtin_filter_map(138 filter_func: FilterFunc,139 map_func: NativeFn!((Val) -> Val),140 arr: ArrValue,141) -> Result<ArrValue> {142 Ok(builtin_filter(filter_func, arr)?.map(map_func))143}144145#[builtin]146pub fn builtin_foldl(147 func: NativeFn!((Val, Either![Val, char]) -> Val),148 arr: Either![ArrValue, IStr],149 init: Val,150) -> Result<Val> {151 let mut acc = init;152 match arr {153 Either2::A(arr) => {154 for i in arr.iter() {155 acc = func.call(acc, Either2::A(i?))?;156 }157 }158 Either2::B(arr) => {159 for c in arr.chars() {160 acc = func.call(acc, Either2::B(c))?;161 }162 }163 }164 Ok(acc)165}166167#[builtin]168pub fn builtin_foldr(169 func: NativeFn!((Either![Val, char], Val) -> Val),170 arr: Either![ArrValue, IStr],171 init: Val,172) -> Result<Val> {173 let mut acc = init;174 match arr {175 Either2::A(arr) => {176 for i in arr.iter().rev() {177 acc = func.call(Either2::A(i?), acc)?;178 }179 }180 Either2::B(arr) => {181 for c in arr.chars().rev() {182 acc = func.call(Either2::B(c), acc)?;183 }184 }185 }186 Ok(acc)187}188189#[builtin]190pub fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {191 if to < from {192 return Ok(ArrValue::empty());193 }194 Ok(ArrValue::range_inclusive(from, to))195}196197#[builtin]198pub fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {199 use std::fmt::Write;200 Ok(match sep {201 IndexableVal::Arr(joiner_items) => {202 let mut out = Vec::new();203204 let mut first = true;205 for item in arr.iter() {206 let item = item?.clone();207 if let Val::Arr(items) = item {208 if !first {209 out.reserve(joiner_items.len());210 // TODO: extend211 for item in joiner_items.iter() {212 out.push(item?);213 }214 }215 first = false;216 out.reserve(items.len());217 for item in items.iter() {218 out.push(item?);219 }220 } else if matches!(item, Val::Null) {221 } else {222 bail!("in std.join all items should be arrays");223 }224 }225226 IndexableVal::Arr(out.into())227 }228 IndexableVal::Str(sep) => {229 let mut out = String::new();230231 let mut first = true;232 for item in arr.iter() {233 let item = item?.clone();234 if let Val::Str(item) = item {235 if !first {236 out += &sep;237 }238 first = false;239 write!(out, "{item}").unwrap();240 } else if matches!(item, Val::Null) {241 } else {242 bail!("in std.join all items should be strings");243 }244 }245246 IndexableVal::Str(out.into())247 }248 })249}250251#[builtin]252pub fn builtin_lines(arr: ArrValue) -> Result<IndexableVal> {253 builtin_join(254 IndexableVal::Str("\n".into()),255 ArrValue::extended(arr, ArrValue::eager(vec![Val::string("")])),256 )257}258259#[builtin]260pub fn builtin_resolve_path(f: String, r: String) -> String {261 let Some(pos) = f.rfind('/') else {262 return r;263 };264 format!("{}{}", &f[..=pos], r)265}266267pub fn deep_join_inner(out: &mut String, arr: IndexableVal) -> Result<()> {268 use std::fmt::Write;269 match arr {270 IndexableVal::Str(s) => write!(out, "{s}").expect("no error"),271 IndexableVal::Arr(arr) => {272 for ele in arr.iter() {273 let indexable = IndexableVal::from_untyped(ele?)?;274 deep_join_inner(out, indexable)?;275 }276 }277 }278 Ok(())279}280281#[builtin]282pub fn builtin_deep_join(arr: IndexableVal) -> Result<String> {283 let mut out = String::new();284 deep_join_inner(&mut out, arr)?;285 Ok(out)286}287288#[builtin]289pub fn builtin_reverse(arr: ArrValue) -> ArrValue {290 arr.reversed()291}292293#[builtin]294pub fn builtin_any(arr: ArrValue) -> Result<bool> {295 for v in arr.iter() {296 let v = bool::from_untyped(v?)?;297 if v {298 return Ok(true);299 }300 }301 Ok(false)302}303304#[builtin]305pub fn builtin_all(arr: ArrValue) -> Result<bool> {306 for v in arr.iter() {307 let v = bool::from_untyped(v?)?;308 if !v {309 return Ok(false);310 }311 }312 Ok(true)313}314315#[builtin]316pub fn builtin_member(arr: IndexableVal, x: Val) -> Result<bool> {317 match arr {318 IndexableVal::Str(str) => {319 let x: IStr = IStr::from_untyped(x)?;320 Ok(!x.is_empty() && str.contains(&*x))321 }322 IndexableVal::Arr(a) => {323 for item in a.iter() {324 let item = item?;325 if equals(&item, &x)? {326 return Ok(true);327 }328 }329 Ok(false)330 }331 }332}333334#[builtin]335pub fn builtin_find(value: Val, arr: ArrValue) -> Result<Vec<usize>> {336 let mut out = Vec::new();337 for (i, ele) in arr.iter().enumerate() {338 let ele = ele?;339 if equals(&ele, &value)? {340 out.push(i);341 }342 }343 Ok(out)344}345346#[builtin]347pub fn builtin_contains(arr: IndexableVal, elem: Val) -> Result<bool> {348 builtin_member(arr, elem)349}350351#[builtin]352pub fn builtin_count(arr: ArrValue, x: Val) -> Result<usize> {353 let mut count = 0;354 for item in arr.iter() {355 if equals(&item?, &x)? {356 count += 1;357 }358 }359 Ok(count)360}361362#[builtin]363pub fn builtin_avg(arr: Vec<f64>, onEmpty: Option<Thunk<Val>>) -> Result<Val> {364 if arr.is_empty() {365 return eval_on_empty(onEmpty);366 }367 Ok(Val::try_num(arr.iter().sum::<f64>() / (arr.len() as f64))?)368}369370#[builtin]371pub fn builtin_remove_at(arr: ArrValue, at: i32) -> Result<ArrValue> {372 let newArrLeft = arr.clone().slice(None, Some(at), None);373 let newArrRight = arr.slice(Some(at + 1), None, None);374375 Ok(ArrValue::extended(newArrLeft, newArrRight))376}377378#[builtin]379pub fn builtin_remove(arr: ArrValue, elem: Val) -> Result<ArrValue> {380 for (index, item) in arr.iter().enumerate() {381 if equals(&item?, &elem)? {382 return builtin_remove_at(arr.clone(), index as i32);383 }384 }385 Ok(arr)386}387388#[builtin]389pub fn builtin_flatten_arrays(arrs: Vec<ArrValue>) -> ArrValue {390 pub fn flatten_inner(values: &[ArrValue]) -> ArrValue {391 if values.len() == 1 {392 return values[0].clone();393 } else if values.len() == 2 {394 return ArrValue::extended(values[0].clone(), values[1].clone());395 }396 let (a, b) = values.split_at(values.len() / 2);397 ArrValue::extended(flatten_inner(a), flatten_inner(b))398 }399 if arrs.is_empty() {400 return ArrValue::empty();401 } else if arrs.len() == 1 {402 return arrs.into_iter().next().expect("single");403 }404 flatten_inner(&arrs)405}406407#[builtin]408pub fn builtin_flatten_deep_array(value: Val) -> Result<Vec<Val>> {409 fn process(value: Val, out: &mut Vec<Val>) -> Result<()> {410 match value {411 Val::Arr(arr) => {412 for ele in arr.iter() {413 process(ele?, out)?;414 }415 }416 _ => out.push(value),417 }418 Ok(())419 }420 let mut out = Vec::new();421 process(value, &mut out)?;422 Ok(out)423}424425#[builtin]426pub fn builtin_prune(427 a: Val,428429 #[default(false)]430 #[cfg(feature = "exp-preserve-order")]431 preserve_order: bool,432) -> Result<Val> {433 fn is_content(val: &Val) -> bool {434 match val {435 Val::Null => false,436 Val::Arr(a) => !a.is_empty(),437 Val::Obj(o) => !o.is_empty(),438 _ => true,439 }440 }441 Ok(match a {442 Val::Arr(a) => {443 let mut out = Vec::new();444 for (i, ele) in a.iter().enumerate() {445 let ele = ele446 .and_then(|v| {447 builtin_prune(448 v,449 #[cfg(feature = "exp-preserve-order")]450 preserve_order,451 )452 })453 .with_description(|| format!("elem <{i}> pruning"))?;454 if is_content(&ele) {455 out.push(ele);456 }457 }458 Val::Arr(ArrValue::eager(out))459 }460 Val::Obj(o) => {461 let mut out = ObjValueBuilder::new();462 for (name, value) in o.iter(463 #[cfg(feature = "exp-preserve-order")]464 preserve_order,465 ) {466 let value = value467 .and_then(|v| {468 builtin_prune(469 v,470 #[cfg(feature = "exp-preserve-order")]471 preserve_order,472 )473 })474 .with_description(|| format!("field <{name}> pruning"))?;475 if !is_content(&value) {476 continue;477 }478 out.field(name).value(value);479 }480 Val::Obj(out.build())481 }482 _ => a,483 })484}crates/jrsonnet-stdlib/src/keyf.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/keyf.rs
+++ b/crates/jrsonnet-stdlib/src/keyf.rs
@@ -1,5 +1,5 @@
use jrsonnet_evaluator::function::{CallLocation, FuncVal, PreparedFuncVal};
-use jrsonnet_evaluator::typed::{ComplexValType, Typed, ValType};
+use jrsonnet_evaluator::typed::{ComplexValType, FromUntyped, Typed, ValType};
use jrsonnet_evaluator::{Error, Result, Thunk, Val};
#[derive(Default, Clone)]
@@ -31,11 +31,9 @@
impl Typed for KeyF {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
+}
+impl FromUntyped for KeyF {
fn from_untyped(untyped: Val) -> Result<Self> {
FuncVal::from_untyped(untyped).map(Self::new)
- }
-
- fn into_untyped(_typed: Self) -> Result<Val> {
- unreachable!("unused, todo: port split of Typed trait from #193")
}
}
crates/jrsonnet-stdlib/src/manifest/ini.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/ini.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/ini.rs
@@ -2,7 +2,7 @@
use jrsonnet_evaluator::{
manifest::{ManifestFormat, ToStringFormat},
- typed::Typed,
+ typed::{FromUntyped, Typed},
ObjValue, Result, ResultExt, Val,
};
use jrsonnet_parser::IStr;
crates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -1,7 +1,7 @@
use jrsonnet_evaluator::{
bail, in_description_frame,
manifest::{ManifestFormat, ToStringFormat},
- typed::{ComplexValType, Either2, Typed, ValType},
+ typed::{ComplexValType, Either2, FromUntyped, Typed, ValType},
val::ArrValue,
Either, ObjValue, Result, ResultExt, Val,
};
@@ -32,11 +32,8 @@
}
impl Typed for JSONMLValue {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
-
- fn into_untyped(_typed: Self) -> Result<Val> {
- unreachable!("not used, reserved for parseXML?")
- }
-
+}
+impl FromUntyped for JSONMLValue {
fn from_untyped(untyped: Val) -> Result<Self> {
let val = <Either![ArrValue, String]>::from_untyped(untyped)
.description("parsing JSONML value (an array or string)")?;
@@ -73,7 +70,7 @@
children: in_description_frame(
|| "parsing children".to_owned(),
|| {
- Typed::from_untyped(Val::Arr(arr.slice(
+ FromUntyped::from_untyped(Val::Arr(arr.slice(
Some(if has_attrs { 2 } else { 1 }),
None,
None,
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -4,7 +4,7 @@
bail,
error::{ErrorKind::*, Result},
function::builtin,
- typed::{Either2, Typed, M1},
+ typed::{Either2, FromUntyped, M1},
val::{ArrValue, IndexableVal},
Either, IStr, Val,
};
tests/tests/builtin.rsdiffbeforeafterboth--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -5,7 +5,7 @@
function::{CallLocation, FuncVal, builtin, builtin::Builtin},
parser::Source,
trace::PathResolver,
- typed::Typed,
+ typed::FromUntyped,
};
use jrsonnet_gcmodule::Trace;
use jrsonnet_stdlib::ContextInitializer as StdContextInitializer;
tests/tests/typed_obj.rsdiffbeforeafterboth--- a/tests/tests/typed_obj.rs
+++ b/tests/tests/typed_obj.rs
@@ -2,7 +2,11 @@
use std::fmt::Debug;
-use jrsonnet_evaluator::{Result, State, trace::PathResolver, typed::Typed};
+use jrsonnet_evaluator::{
+ Result, State,
+ trace::PathResolver,
+ typed::{FromUntyped, IntoUntyped, Typed},
+};
use jrsonnet_stdlib::ContextInitializer;
#[derive(Clone, Typed, PartialEq, Debug)]
@@ -11,7 +15,9 @@
b: u16,
}
-fn test_roundtrip<T: Typed + PartialEq + Debug + Clone>(value: T) -> Result<()> {
+fn test_roundtrip<T: Typed + PartialEq + Debug + Clone + FromUntyped + IntoUntyped>(
+ value: T,
+) -> Result<()> {
let untyped = T::into_untyped(value.clone())?;
let value2 = T::from_untyped(untyped.clone())?;
ensure_eq!(value, value2);