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.rsdiffbeforeafterboth1use std::{fmt::Debug, rc::Rc};23pub use arglike::{ArgLike, ArgsLike, TlaArg};4use educe::Educe;5use jrsonnet_gcmodule::{Cc, Trace};6use jrsonnet_interner::IStr;7pub use jrsonnet_macros::builtin;8use jrsonnet_parser::{Destruct, Expr, ExprParams, Span, Spanned};910use self::{11 arglike::OptionalContext,12 builtin::{Builtin, StaticBuiltin},13 native::NativeDesc,14 parse::{parse_builtin_call, parse_default_function_call, parse_function_call},15 prepared::{parse_prepared_builtin_call, parse_prepared_function_call, PreparedCall},16};17use crate::{18 bail, error::ErrorKind::*, evaluate, evaluate_trivial, function::builtin::BuiltinFunc, Context,19 ContextBuilder, Result, Thunk, Val,20};2122pub mod arglike;23pub mod builtin;24pub mod native;25pub mod parse;26mod prepared;2728pub use prepared::PreparedFuncVal;2930pub use jrsonnet_parser::function::*;3132/// Function callsite location.33/// Either from other jsonnet code, specified by expression location, or from native (without location).34#[derive(Clone, Copy)]35pub struct CallLocation<'l>(pub Option<&'l Span>);36impl<'l> CallLocation<'l> {37 /// Construct new location for calls coming from specified jsonnet expression location.38 pub const fn new(loc: &'l Span) -> Self {39 Self(Some(loc))40 }41}42impl CallLocation<'static> {43 /// Construct new location for calls coming from native code.44 pub const fn native() -> Self {45 Self(None)46 }47}4849/// Represents Jsonnet function defined in code.50#[derive(Trace, Educe)]51#[educe(Debug, PartialEq)]52pub struct FuncDesc {53 /// # Example54 ///55 /// In expressions like this, deducted to `a`, unspecified otherwise.56 /// ```jsonnet57 /// local a = function() ...58 /// local a() ...59 /// { a: function() ... }60 /// { a() = ... }61 /// ```62 pub name: IStr,63 /// Context, in which this function was evaluated.64 ///65 /// # Example66 /// In67 /// ```jsonnet68 /// local a = 2;69 /// function() ...70 /// ```71 /// context will contain `a`.72 pub ctx: Context,7374 /// Function parameter definition75 pub params: ExprParams,76 /// Function body77 pub body: Rc<Spanned<Expr>>,78}79impl FuncDesc {80 /// Create body context, but fill arguments without defaults with lazy error81 pub fn default_body_context(&self) -> Result<Context> {82 parse_default_function_call(self.ctx.clone(), &self.params)83 }8485 /// Create context, with which body code will run86 pub fn call_body_context(87 &self,88 call_ctx: Context,89 args: &dyn ArgsLike,90 tailstrict: bool,91 ) -> Result<Context> {92 parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)93 }9495 pub fn evaluate_trivial(&self) -> Option<Val> {96 evaluate_trivial(&self.body)97 }98}99100/// Represents a Jsonnet function value, including plain functions and user-provided builtins.101#[allow(clippy::module_name_repetitions)]102#[derive(Trace, Clone)]103pub enum FuncVal {104 /// Identity function, kept this way for comparsions.105 Id,106 /// Plain function implemented in jsonnet.107 Normal(Cc<FuncDesc>),108 /// Function without arguments works just as a fancy thunk value.109 Thunk(Thunk<Val>),110 /// Standard library function.111 StaticBuiltin(#[trace(skip)] &'static dyn StaticBuiltin),112 /// User-provided function.113 Builtin(BuiltinFunc),114}115116impl Debug for FuncVal {117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {118 match self {119 Self::Id => f.debug_tuple("Id").finish(),120 Self::Thunk(arg0) => f.debug_tuple("Thunk").field(arg0).finish(),121 Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),122 Self::StaticBuiltin(arg0) => {123 f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()124 }125 Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),126 }127 }128}129130#[allow(clippy::unnecessary_wraps)]131#[builtin]132const fn builtin_id(x: Val) -> Val {133 x134}135static ID: &builtin_id = &builtin_id {};136137impl FuncVal {138 pub fn builtin(builtin: impl Builtin) -> Self {139 Self::Builtin(BuiltinFunc::new(builtin))140 }141 pub fn static_builtin(static_builtin: &'static dyn StaticBuiltin) -> Self {142 Self::StaticBuiltin(static_builtin)143 }144145 pub fn params(&self) -> FunctionSignature {146 match self {147 Self::Id => ID.params(),148 Self::StaticBuiltin(i) => i.params(),149 Self::Builtin(i) => i.params(),150 Self::Normal(p) => p.params.signature.clone(),151 Self::Thunk(_) => FunctionSignature::empty(),152 }153 }154 /// Amount of non-default required arguments155 pub fn params_len(&self) -> usize {156 self.params().iter().filter(|p| !p.has_default()).count()157 }158 /// Function name, as defined in code.159 pub fn name(&self) -> IStr {160 match self {161 Self::Id => "id".into(),162 Self::Normal(normal) => normal.name.clone(),163 Self::StaticBuiltin(builtin) => builtin.name().into(),164 Self::Builtin(builtin) => builtin.name().into(),165 Self::Thunk(_) => "thunk".into(),166 }167 }168 /// Call function using arguments evaluated in specified `call_ctx` [`Context`].169 ///170 /// If `tailstrict` is specified - then arguments will be evaluated before being passed to function body.171 pub fn evaluate(172 &self,173 call_ctx: Context,174 loc: CallLocation<'_>,175 args: &dyn ArgsLike,176 tailstrict: bool,177 ) -> Result<Val> {178 match self {179 Self::Normal(func) => {180 let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;181 evaluate(body_ctx, &func.body)182 }183 Self::Thunk(thunk) => {184 if !args.is_empty() {185 bail!(TooManyArgsFunctionHas(0, FunctionSignature::empty()))186 }187 thunk.evaluate()188 }189 Self::Id => {190 let args = parse_builtin_call(call_ctx, ID.params(), args, tailstrict)?;191 ID.call(loc, &args)192 }193 Self::StaticBuiltin(b) => {194 let args = parse_builtin_call(call_ctx, b.params(), args, tailstrict)?;195 b.call(loc, &args)196 }197 Self::Builtin(b) => {198 let args = parse_builtin_call(call_ctx, b.params(), args, tailstrict)?;199 b.call(loc, &args)200 }201 }202 }203 pub fn evaluate_simple<A: ArgsLike + OptionalContext>(204 &self,205 args: &A,206 tailstrict: bool,207 ) -> Result<Val> {208 self.evaluate(209 ContextBuilder::new().build(),210 CallLocation::native(),211 args,212 tailstrict,213 )214 }215216 pub(crate) fn evaluate_prepared(217 &self,218 prepared: &PreparedCall,219 loc: CallLocation<'_>,220 unnamed: &[Thunk<Val>],221 named: &[Thunk<Val>],222 _tailstrict: bool,223 ) -> Result<Val> {224 match self {225 FuncVal::Id => {226 let args = parse_prepared_builtin_call(prepared, ID.params(), unnamed, named)?;227 ID.call(loc, &args)228 }229 FuncVal::Normal(func) => {230 let body_ctx = parse_prepared_function_call(231 func.ctx.clone(),232 prepared,233 &func.params,234 unnamed,235 named,236 )?;237 evaluate(body_ctx, &func.body)238 }239 FuncVal::Thunk(t) => t.evaluate(),240 FuncVal::StaticBuiltin(b) => {241 let args = parse_prepared_builtin_call(prepared, b.params(), unnamed, named)?;242 b.call(loc, &args)243 }244 FuncVal::Builtin(b) => {245 let args = parse_prepared_builtin_call(prepared, b.params(), unnamed, named)?;246 b.call(loc, &args)247 }248 }249 }250 /// Convert jsonnet function to plain `Fn` value.251 pub fn into_native<D: NativeDesc>(self) -> D::Value {252 D::into_native(self)253 }254255 /// Is this function an indentity function.256 ///257 /// Currently only works for builtin `std.id`, aka `Self::Id` value, and `function(x) x`.258 ///259 /// This function should only be used for optimization, not for the conditional logic, i.e code should work with syntetic identity function too260 pub fn is_identity(&self) -> bool {261 match self {262 Self::Id => true,263 Self::Normal(desc) => {264 if desc.params.len() != 1 {265 return false;266 }267 let param = &desc.params.exprs[0];268 if param.default.is_some() {269 return false;270 }271272 #[allow(clippy::infallible_destructuring_match)]273 let id = match ¶m.destruct {274 Destruct::Full(id) => id,275 #[cfg(feature = "exp-destruct")]276 _ => return false,277 };278 **desc.body == Expr::Var(id.clone())279 }280 _ => false,281 }282 }283 /// Identity function value.284 pub const fn identity() -> Self {285 Self::Id286 }287288 pub fn evaluate_trivial(&self) -> Option<Val> {289 match self {290 Self::Normal(n) => n.evaluate_trivial(),291 _ => None,292 }293 }294}295296impl<T> From<T> for FuncVal297where298 T: Builtin,299{300 fn from(value: T) -> Self {301 Self::builtin(value)302 }303}304impl From<&'static dyn StaticBuiltin> for FuncVal {305 fn from(value: &'static dyn StaticBuiltin) -> Self {306 Self::static_builtin(value)307 }308}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.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -23,7 +23,8 @@
return Ok(ArrValue::empty());
}
func.evaluate_trivial().map_or_else(
- || Ok(ArrValue::range_exclusive(0, *sz).map(func)),
+ // TODO: Different mapped array impl avoiding allocating unnecessary vals
+ || Ok(ArrValue::range_exclusive(0, *sz).map(Typed::from_untyped(Val::Func(func))?)),
|trivial| {
let mut out = Vec::with_capacity(*sz as usize);
for _ in 0..*sz {
@@ -58,19 +59,22 @@
}
#[builtin]
-pub fn builtin_map(func: FuncVal, arr: IndexableVal) -> ArrValue {
+pub fn builtin_map(func: NativeFn!((Val) -> Val), arr: IndexableVal) -> ArrValue {
let arr = arr.to_array();
arr.map(func)
}
#[builtin]
-pub fn builtin_map_with_index(func: FuncVal, arr: IndexableVal) -> ArrValue {
+pub fn builtin_map_with_index(func: NativeFn!((u32, Val) -> Val), arr: IndexableVal) -> ArrValue {
let arr = arr.to_array();
arr.map_with_index(func)
}
#[builtin]
-pub fn builtin_map_with_key(func: FuncVal, obj: ObjValue) -> Result<ObjValue> {
+pub fn builtin_map_with_key(
+ func: NativeFn!((IStr, Val) -> Val),
+ obj: ObjValue,
+) -> Result<ObjValue> {
let mut out = ObjValueBuilder::new();
for (k, v) in obj.iter(
// Makes sense mapped object should be ordered the same way, should not break anything when the output is not ordered (the default).
@@ -80,15 +84,14 @@
true,
) {
let v = v?;
- out.field(k.clone())
- .value(func.evaluate_simple(&(k, v), false)?);
+ out.field(k.clone()).value(func.call(k, v)?);
}
Ok(out.build())
}
#[builtin]
pub fn builtin_flatmap(
- func: NativeFn<((Either![String, Val],), Val)>,
+ func: NativeFn!((Either![String, Val]) -> Val),
arr: IndexableVal,
) -> Result<IndexableVal> {
use std::fmt::Write;
@@ -96,9 +99,9 @@
IndexableVal::Str(str) => {
let mut out = String::new();
for c in str.chars() {
- match func(Either2::A(c.to_string()))? {
+ match func.call(Either2::A(c.to_string()))? {
Val::Str(o) => write!(out, "{o}").unwrap(),
- Val::Null => {},
+ Val::Null => {}
_ => bail!("in std.join all items should be strings"),
}
}
@@ -108,13 +111,13 @@
let mut out = Vec::new();
for el in a.iter() {
let el = el?;
- match func(Either2::B(el))? {
+ match func.call(Either2::B(el))? {
Val::Arr(o) => {
for oe in o.iter() {
out.push(oe?);
}
}
- Val::Null => {},
+ Val::Null => {}
_ => bail!("in std.join all items should be arrays"),
}
}
@@ -123,32 +126,38 @@
}
}
+type FilterFunc = NativeFn!((Val) -> bool);
+
#[builtin]
-pub fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {
- arr.filter(|val| bool::from_untyped(func.evaluate_simple(&(val.clone(),), false)?))
+pub fn builtin_filter(func: FilterFunc, arr: ArrValue) -> Result<ArrValue> {
+ arr.filter(|val| func.call(val.clone()))
}
#[builtin]
pub fn builtin_filter_map(
- filter_func: FuncVal,
- map_func: FuncVal,
+ filter_func: FilterFunc,
+ map_func: NativeFn!((Val) -> Val),
arr: ArrValue,
) -> Result<ArrValue> {
Ok(builtin_filter(filter_func, arr)?.map(map_func))
}
#[builtin]
-pub fn builtin_foldl(func: FuncVal, arr: Either![ArrValue, IStr], init: Val) -> Result<Val> {
+pub fn builtin_foldl(
+ func: NativeFn!((Val, Either![Val, char]) -> Val),
+ arr: Either![ArrValue, IStr],
+ init: Val,
+) -> Result<Val> {
let mut acc = init;
match arr {
Either2::A(arr) => {
for i in arr.iter() {
- acc = func.evaluate_simple(&(acc, i?), false)?;
+ acc = func.call(acc, Either2::A(i?))?;
}
}
Either2::B(arr) => {
- for i in arr.chars() {
- acc = func.evaluate_simple(&(acc, Val::string(i)), false)?;
+ for c in arr.chars() {
+ acc = func.call(acc, Either2::B(c))?;
}
}
}
@@ -156,17 +165,21 @@
}
#[builtin]
-pub fn builtin_foldr(func: FuncVal, arr: Either![ArrValue, IStr], init: Val) -> Result<Val> {
+pub fn builtin_foldr(
+ func: NativeFn!((Either![Val, char], Val) -> Val),
+ arr: Either![ArrValue, IStr],
+ init: Val,
+) -> Result<Val> {
let mut acc = init;
match arr {
Either2::A(arr) => {
for i in arr.iter().rev() {
- acc = func.evaluate_simple(&(i?, acc), false)?;
+ acc = func.call(Either2::A(i?), acc)?;
}
}
Either2::B(arr) => {
- for i in arr.chars().rev() {
- acc = func.evaluate_simple(&(Val::string(i), acc), false)?;
+ for c in arr.chars().rev() {
+ acc = func.call(Either2::B(c), acc)?;
}
}
}
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(())
-}