difftreelog
refactor use PreparedFunction for NativeFn
in: master
9 files changed
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -1,14 +1,15 @@
use std::{
any::Any,
fmt::{self},
- num::NonZeroU32, rc::Rc,
+ num::NonZeroU32,
+ rc::Rc,
};
use jrsonnet_gcmodule::{cc_dyn, Cc};
use jrsonnet_interner::IBytes;
use jrsonnet_parser::{Expr, Spanned};
-use crate::{function::FuncVal, Context, Result, Thunk, Val};
+use crate::{typed::NativeFn, Context, Result, Thunk, Val};
mod spec;
pub use spec::{ArrayLike, *};
@@ -61,13 +62,13 @@
}
#[must_use]
- pub fn map(self, mapper: FuncVal) -> Self {
- Self::new(<MappedArray<false>>::new(self, mapper))
+ pub fn map(self, mapper: NativeFn!((Val) -> Val)) -> Self {
+ Self::new(<MappedArray>::new(self, ArrayMapper::Plain(mapper)))
}
#[must_use]
- pub fn map_with_index(self, mapper: FuncVal) -> Self {
- Self::new(<MappedArray<true>>::new(self, mapper))
+ pub fn map_with_index(self, mapper: NativeFn!((u32, Val) -> Val)) -> Self {
+ Self::new(<MappedArray>::new(self, ArrayMapper::WithIndex(mapper)))
}
pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -6,9 +6,11 @@
use jrsonnet_parser::{Expr, Spanned};
use super::ArrValue;
+use crate::typed::NativeFn;
+use crate::val::NumValue;
use crate::{
- error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, typed::Typed,
- val::ThunkValue, Context, Error, ObjValue, Result, Thunk, Val,
+ error::ErrorKind::InfiniteRecursionDetected, evaluate, typed::Typed, val::ThunkValue, Context,
+ Error, ObjValue, Result, Thunk, Val,
};
pub trait ArrayLike: Any + Trace + Debug {
@@ -404,14 +406,20 @@
}
}
+#[derive(Trace, Clone, Debug)]
+pub enum ArrayMapper {
+ Plain(NativeFn!((Val) -> Val)),
+ WithIndex(NativeFn!((u32, Val) -> Val)),
+}
+
#[derive(Trace, Debug, Clone)]
-pub struct MappedArray<const WITH_INDEX: bool> {
+pub struct MappedArray {
inner: ArrValue,
cached: Cc<RefCell<Vec<ArrayThunk>>>,
- mapper: FuncVal,
+ mapper: ArrayMapper,
}
-impl<const WITH_INDEX: bool> MappedArray<WITH_INDEX> {
- pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {
+impl MappedArray {
+ pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {
let len = inner.len();
Self {
inner,
@@ -420,14 +428,13 @@
}
}
fn evaluate(&self, index: usize, value: Val) -> Result<Val> {
- if WITH_INDEX {
- self.mapper.evaluate_simple(&(index, value), false)
- } else {
- self.mapper.evaluate_simple(&(value,), false)
+ match &self.mapper {
+ ArrayMapper::Plain(f) => f.call(value),
+ ArrayMapper::WithIndex(f) => f.call(index as u32, value),
}
}
}
-impl<const WITH_INDEX: bool> ArrayLike for MappedArray<WITH_INDEX> {
+impl ArrayLike for MappedArray {
fn len(&self) -> usize {
self.cached.borrow().len()
}
@@ -468,11 +475,11 @@
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
#[derive(Trace)]
- struct MappedArrayThunk<const WITH_INDEX: bool> {
- arr: MappedArray<WITH_INDEX>,
+ struct MappedArrayThunk {
+ arr: MappedArray,
index: usize,
}
- impl<const WITH_INDEX: bool> ThunkValue for MappedArrayThunk<WITH_INDEX> {
+ impl ThunkValue for MappedArrayThunk {
type Output = Val;
fn get(&self) -> Result<Self::Output> {
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -8,15 +8,13 @@
use jrsonnet_parser::{Destruct, Expr, ExprParams, Span, Spanned};
use self::{
- arglike::OptionalContext,
builtin::{Builtin, StaticBuiltin},
- native::NativeDesc,
parse::{parse_builtin_call, parse_default_function_call, parse_function_call},
prepared::{parse_prepared_builtin_call, parse_prepared_function_call, PreparedCall},
};
use crate::{
bail, error::ErrorKind::*, evaluate, evaluate_trivial, function::builtin::BuiltinFunc, Context,
- ContextBuilder, Result, Thunk, Val,
+ Result, Thunk, Val,
};
pub mod arglike;
@@ -199,18 +197,6 @@
b.call(loc, &args)
}
}
- }
- pub fn evaluate_simple<A: ArgsLike + OptionalContext>(
- &self,
- args: &A,
- tailstrict: bool,
- ) -> Result<Val> {
- self.evaluate(
- ContextBuilder::new().build(),
- CallLocation::native(),
- args,
- tailstrict,
- )
}
pub(crate) fn evaluate_prepared(
@@ -246,10 +232,6 @@
b.call(loc, &args)
}
}
- }
- /// Convert jsonnet function to plain `Fn` value.
- pub fn into_native<D: NativeDesc>(self) -> D::Value {
- D::into_native(self)
}
/// Is this function an indentity function.
crates/jrsonnet-evaluator/src/function/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/native.rs
+++ b/crates/jrsonnet-evaluator/src/function/native.rs
@@ -1,43 +1,2 @@
-use super::{
- arglike::{ArgLike, OptionalContext},
- FuncVal,
-};
-use crate::{typed::Typed, Result};
-
-pub trait NativeDesc {
- type Value;
- fn into_native(val: FuncVal) -> Self::Value;
-}
-macro_rules! impl_native_desc {
- ($($gen:ident)*) => {
- impl<$($gen,)* O> NativeDesc for (($($gen,)*), O)
- where
- $($gen: ArgLike + OptionalContext,)*
- O: Typed,
- {
- type Value = Box<dyn Fn($($gen,)*) -> Result<O>>;
-
- #[allow(non_snake_case)]
- fn into_native(val: FuncVal) -> Self::Value {
- Box::new(move |$($gen),*| {
- let val = val.evaluate_simple(
- &($($gen,)*),
- false,
- )?;
- O::from_untyped(val)
- })
- }
- }
- };
- ($($cur:ident)* @ $c:ident $($rest:ident)*) => {
- impl_native_desc!($($cur)*);
- impl_native_desc!($($cur)* $c @ $($rest)*);
- };
- ($($cur:ident)* @) => {
- impl_native_desc!($($cur)*);
- }
-}
-
-impl_native_desc! {
- @ A B C D E F G H I J K L
-}
+use super::PreparedFuncVal;
+use crate::{typed::Typed, CallLocation, Result, Thunk};
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -8,7 +8,7 @@
use crate::{
arr::{ArrValue, BytesArray},
bail,
- function::{native::NativeDesc, FuncDesc, FuncVal},
+ function::{CallLocation, FuncDesc, FuncVal, PreparedFuncVal},
typed::CheckType,
val::{IndexableVal, NumValue, StrValue, ThunkMapper},
ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
@@ -675,30 +675,65 @@
}
}
-pub struct NativeFn<D: NativeDesc>(D::Value);
-impl<D: NativeDesc> Deref for NativeFn<D> {
- type Target = D::Value;
+#[derive(Debug, Trace, Clone)]
+pub struct NativeFn<D: 'static>(pub(crate) PreparedFuncVal, PhantomData<D>);
+macro_rules! impl_native_desc {
+ ($i:expr; $($gen:ident)*) => {
+ impl<$($gen,)* O> NativeFn<($($gen,)* O,)>
+ where
+ $($gen: Typed,)*
+ O: Typed,
+ {
+ pub fn call(
+ &self,
+ $($gen: $gen,)*
+ ) -> Result<O> {
+ let val = self.0.call(
+ CallLocation::native(),
+ &[$(Typed::into_lazy_untyped($gen),)*],
+ &[],
+ )?;
+ O::from_untyped(val)
+ }
+ }
+ 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")
+ }
- fn deref(&self) -> &Self::Target {
- &self.0
+ fn from_untyped(untyped: Val) -> Result<Self> {
+ let func = FuncVal::from_untyped(untyped)?;
+ Ok(Self(
+ PreparedFuncVal::new(func, $i, &[])?,
+ PhantomData,
+ ))
+ }
+ }
+ };
+ ($i:expr; $($cur:ident)* @ $c:ident $($rest:ident)*) => {
+ impl_native_desc!($i; $($cur)*);
+ impl_native_desc!($i + 1; $($cur)* $c @ $($rest)*);
+ };
+ ($i:expr; $($cur:ident)* @) => {
+ impl_native_desc!($i; $($cur)*);
}
}
-impl<D: NativeDesc> Typed for NativeFn<D> {
- 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_native_desc! {
+ 0; @ A B C D E F G H I J K L
+}
- fn from_untyped(untyped: Val) -> Result<Self> {
- Ok(Self(
- untyped
- .as_func()
- .expect("shape is checked")
- .into_native::<D>(),
- ))
+mod native_macro {
+ #[macro_export]
+ macro_rules! NativeFn {
+ (($($t:ty),* $(,)?) -> $res:ty) => {
+ NativeFn<($($t,)* $res)>
+ }
}
}
+pub use crate::NativeFn;
impl Typed for NumValue {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -3,7 +3,14 @@
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::{
- Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn, LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type, parenthesized, parse::{Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, spanned::Spanned, token::{self, Comma}
+ parenthesized,
+ parse::{Parse, ParseStream},
+ parse_macro_input,
+ punctuated::Punctuated,
+ spanned::Spanned,
+ token::{self, Comma},
+ Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,
+ LitStr, Meta, Pat, Path, PathArguments, Result, ReturnType, Token, Type,
};
fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth23 return Ok(ArrValue::empty());23 return Ok(ArrValue::empty());24 }24 }25 func.evaluate_trivial().map_or_else(25 func.evaluate_trivial().map_or_else(26 // TODO: Different mapped array impl avoiding allocating unnecessary vals26 || Ok(ArrValue::range_exclusive(0, *sz).map(func)),27 || Ok(ArrValue::range_exclusive(0, *sz).map(Typed::from_untyped(Val::Func(func))?)),27 |trivial| {28 |trivial| {28 let mut out = Vec::with_capacity(*sz as usize);29 let mut out = Vec::with_capacity(*sz as usize);29 for _ in 0..*sz {30 for _ in 0..*sz {58}59}596060#[builtin]61#[builtin]61pub fn builtin_map(func: FuncVal, arr: IndexableVal) -> ArrValue {62pub fn builtin_map(func: NativeFn!((Val) -> Val), arr: IndexableVal) -> ArrValue {62 let arr = arr.to_array();63 let arr = arr.to_array();63 arr.map(func)64 arr.map(func)64}65}656666#[builtin]67#[builtin]67pub fn builtin_map_with_index(func: FuncVal, arr: IndexableVal) -> ArrValue {68pub fn builtin_map_with_index(func: NativeFn!((u32, Val) -> Val), arr: IndexableVal) -> ArrValue {68 let arr = arr.to_array();69 let arr = arr.to_array();69 arr.map_with_index(func)70 arr.map_with_index(func)70}71}717272#[builtin]73#[builtin]73pub fn builtin_map_with_key(func: FuncVal, obj: ObjValue) -> Result<ObjValue> {74pub fn builtin_map_with_key(75 func: NativeFn!((IStr, Val) -> Val),76 obj: ObjValue,77) -> Result<ObjValue> {74 let mut out = ObjValueBuilder::new();78 let mut out = ObjValueBuilder::new();80 true,84 true,81 ) {85 ) {82 let v = v?;86 let v = v?;83 out.field(k.clone())87 out.field(k.clone()).value(func.call(k, v)?);84 .value(func.evaluate_simple(&(k, v), false)?);85 }88 }86 Ok(out.build())89 Ok(out.build())87}90}889189#[builtin]92#[builtin]90pub fn builtin_flatmap(93pub fn builtin_flatmap(91 func: NativeFn<((Either![String, Val],), Val)>,94 func: NativeFn!((Either![String, Val]) -> Val),92 arr: IndexableVal,95 arr: IndexableVal,93) -> Result<IndexableVal> {96) -> Result<IndexableVal> {94 use std::fmt::Write;97 use std::fmt::Write;95 match arr {98 match arr {96 IndexableVal::Str(str) => {99 IndexableVal::Str(str) => {97 let mut out = String::new();100 let mut out = String::new();98 for c in str.chars() {101 for c in str.chars() {99 match func(Either2::A(c.to_string()))? {102 match func.call(Either2::A(c.to_string()))? {100 Val::Str(o) => write!(out, "{o}").unwrap(),103 Val::Str(o) => write!(out, "{o}").unwrap(),101 Val::Null => {},104 Val::Null => {}102 _ => bail!("in std.join all items should be strings"),105 _ => bail!("in std.join all items should be strings"),103 }106 }104 }107 }108 let mut out = Vec::new();111 let mut out = Vec::new();109 for el in a.iter() {112 for el in a.iter() {110 let el = el?;113 let el = el?;111 match func(Either2::B(el))? {114 match func.call(Either2::B(el))? {112 Val::Arr(o) => {115 Val::Arr(o) => {113 for oe in o.iter() {116 for oe in o.iter() {114 out.push(oe?);117 out.push(oe?);115 }118 }116 }119 }117 Val::Null => {},120 Val::Null => {}118 _ => bail!("in std.join all items should be arrays"),121 _ => bail!("in std.join all items should be arrays"),119 }122 }120 }123 }123 }126 }124}127}128129type FilterFunc = NativeFn!((Val) -> bool);125130126#[builtin]131#[builtin]127pub fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {132pub fn builtin_filter(func: FilterFunc, arr: ArrValue) -> Result<ArrValue> {128 arr.filter(|val| bool::from_untyped(func.evaluate_simple(&(val.clone(),), false)?))133 arr.filter(|val| func.call(val.clone()))129}134}130135131#[builtin]136#[builtin]132pub fn builtin_filter_map(137pub fn builtin_filter_map(133 filter_func: FuncVal,138 filter_func: FilterFunc,134 map_func: FuncVal,139 map_func: NativeFn!((Val) -> Val),135 arr: ArrValue,140 arr: ArrValue,136) -> Result<ArrValue> {141) -> Result<ArrValue> {137 Ok(builtin_filter(filter_func, arr)?.map(map_func))142 Ok(builtin_filter(filter_func, arr)?.map(map_func))138}143}139144140#[builtin]145#[builtin]141pub fn builtin_foldl(func: FuncVal, arr: Either![ArrValue, IStr], init: Val) -> Result<Val> {146pub fn builtin_foldl(147 func: NativeFn!((Val, Either![Val, char]) -> Val),148 arr: Either![ArrValue, IStr],149 init: Val,150) -> Result<Val> {142 let mut acc = init;151 let mut acc = init;143 match arr {152 match arr {144 Either2::A(arr) => {153 Either2::A(arr) => {145 for i in arr.iter() {154 for i in arr.iter() {146 acc = func.evaluate_simple(&(acc, i?), false)?;155 acc = func.call(acc, Either2::A(i?))?;147 }156 }148 }157 }149 Either2::B(arr) => {158 Either2::B(arr) => {150 for i in arr.chars() {159 for c in arr.chars() {151 acc = func.evaluate_simple(&(acc, Val::string(i)), false)?;160 acc = func.call(acc, Either2::B(c))?;152 }161 }153 }162 }154 }163 }155 Ok(acc)164 Ok(acc)156}165}157166158#[builtin]167#[builtin]159pub fn builtin_foldr(func: FuncVal, arr: Either![ArrValue, IStr], init: Val) -> Result<Val> {168pub fn builtin_foldr(169 func: NativeFn!((Either![Val, char], Val) -> Val),170 arr: Either![ArrValue, IStr],171 init: Val,172) -> Result<Val> {160 let mut acc = init;173 let mut acc = init;161 match arr {174 match arr {162 Either2::A(arr) => {175 Either2::A(arr) => {163 for i in arr.iter().rev() {176 for i in arr.iter().rev() {164 acc = func.evaluate_simple(&(i?, acc), false)?;177 acc = func.call(Either2::A(i?), acc)?;165 }178 }166 }179 }167 Either2::B(arr) => {180 Either2::B(arr) => {168 for i in arr.chars().rev() {181 for c in arr.chars().rev() {169 acc = func.evaluate_simple(&(Val::string(i), acc), false)?;182 acc = func.call(Either2::B(c), acc)?;170 }183 }171 }184 }172 }185 }crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -38,6 +38,7 @@
mod compat;
mod encoding;
mod hash;
+mod keyf;
mod manifest;
mod math;
mod misc;
@@ -50,7 +51,6 @@
mod sort;
mod strings;
mod types;
-mod keyf;
#[allow(clippy::too_many_lines)]
pub fn stdlib_uncached(settings: Cc<RefCell<Settings>>) -> ObjValue {
tests/tests/as_native.rsdiffbeforeafterboth--- a/tests/tests/as_native.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use jrsonnet_evaluator::{FileImportResolver, Result, State, trace::PathResolver};
-use jrsonnet_stdlib::ContextInitializer;
-
-mod common;
-
-#[test]
-fn as_native() -> Result<()> {
- let mut s = State::builder();
- s.context_initializer(ContextInitializer::new(PathResolver::new_cwd_fallback()))
- .import_resolver(FileImportResolver::default());
- let s = s.build();
-
- let val = s.evaluate_snippet("snip".to_owned(), r"function(a, b) a + b")?;
- let func = val.as_func().expect("this is function");
-
- let native = func.into_native::<((u32, u32), u32)>();
-
- ensure_eq!(native(1, 2)?, 3);
- ensure_eq!(native(3, 4)?, 7);
-
- Ok(())
-}