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.rsdiffbeforeafterboth1use std::rc::Rc;2use std::{any::Any, cell::RefCell, fmt::Debug, mem::replace};34use jrsonnet_gcmodule::{Cc, Trace};5use jrsonnet_interner::{IBytes, IStr};6use jrsonnet_parser::{Expr, Spanned};78use super::ArrValue;9use crate::{10 error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, typed::Typed,11 val::ThunkValue, Context, Error, ObjValue, Result, Thunk, Val,12};1314pub trait ArrayLike: Any + Trace + Debug {15 fn len(&self) -> usize;16 fn is_empty(&self) -> bool {17 self.len() == 018 }19 fn get(&self, index: usize) -> Result<Option<Val>>;20 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;21 fn get_cheap(&self, index: usize) -> Option<Val>;2223 fn is_cheap(&self) -> bool;24}2526#[derive(Debug, Trace)]27pub struct SliceArray {28 pub(crate) inner: ArrValue,29 pub(crate) from: u32,30 pub(crate) to: u32,31 pub(crate) step: u32,32}3334impl SliceArray {35 fn map_idx(&self, index: usize) -> usize {36 self.from as usize + self.step as usize * index37 }38}39impl ArrayLike for SliceArray {40 fn len(&self) -> usize {41 (self.to - self.from).div_ceil(self.step) as usize42 }4344 fn get(&self, index: usize) -> Result<Option<Val>> {45 self.inner.get(self.map_idx(index))46 }4748 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {49 self.inner.get_lazy(self.map_idx(index))50 }5152 fn get_cheap(&self, index: usize) -> Option<Val> {53 self.inner.get_cheap(self.map_idx(index))54 }55 fn is_cheap(&self) -> bool {56 self.inner.is_cheap()57 }58}5960#[derive(Trace, Debug)]61pub struct CharArray(pub Vec<char>);62impl ArrayLike for CharArray {63 fn len(&self) -> usize {64 self.0.len()65 }6667 fn get(&self, index: usize) -> Result<Option<Val>> {68 Ok(self.get_cheap(index))69 }7071 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {72 self.get_cheap(index).map(Thunk::evaluated)73 }7475 fn get_cheap(&self, index: usize) -> Option<Val> {76 self.0.get(index).map(|v| Val::string(*v))77 }78 fn is_cheap(&self) -> bool {79 true80 }81}8283#[derive(Trace, Debug)]84pub struct BytesArray(pub IBytes);85impl ArrayLike for BytesArray {86 fn len(&self) -> usize {87 self.0.len()88 }8990 fn get(&self, index: usize) -> Result<Option<Val>> {91 Ok(self.get_cheap(index))92 }9394 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {95 self.get_cheap(index).map(Thunk::evaluated)96 }9798 fn get_cheap(&self, index: usize) -> Option<Val> {99 self.0.get(index).map(|v| Val::Num((*v).into()))100 }101 fn is_cheap(&self) -> bool {102 true103 }104}105106#[derive(Debug, Trace, Clone)]107enum ArrayThunk {108 Computed(Val),109 Errored(Error),110 Waiting,111 Pending,112}113114#[derive(Debug, Trace, Clone)]115pub struct ExprArray {116 ctx: Context,117 src: Rc<Vec<Spanned<Expr>>>,118 cached: Cc<RefCell<Vec<ArrayThunk>>>,119}120impl ExprArray {121 pub fn new(ctx: Context, src: Rc<Vec<Spanned<Expr>>>) -> Self {122 Self {123 ctx,124 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),125 src,126 }127 }128}129impl ArrayLike for ExprArray {130 fn len(&self) -> usize {131 self.cached.borrow().len()132 }133 fn get(&self, index: usize) -> Result<Option<Val>> {134 if index >= self.len() {135 return Ok(None);136 }137 match &self.cached.borrow()[index] {138 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),139 ArrayThunk::Errored(e) => return Err(e.clone()),140 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),141 ArrayThunk::Waiting => {}142 }143144 let ArrayThunk::Waiting =145 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)146 else {147 unreachable!()148 };149150 let new_value = match evaluate(self.ctx.clone(), &self.src[index]) {151 Ok(v) => v,152 Err(e) => {153 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());154 return Err(e);155 }156 };157 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());158 Ok(Some(new_value))159 }160 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {161 #[derive(Trace)]162 struct ExprArrThunk {163 expr: ExprArray,164 index: usize,165 }166 impl ThunkValue for ExprArrThunk {167 type Output = Val;168169 fn get(&self) -> Result<Self::Output> {170 self.expr171 .get(self.index)172 .transpose()173 .expect("index checked")174 }175 }176177 if index >= self.len() {178 return None;179 }180 match &self.cached.borrow()[index] {181 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),182 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),183 ArrayThunk::Waiting | ArrayThunk::Pending => {}184 }185186 Some(Thunk::new(ExprArrThunk {187 expr: self.clone(),188 index,189 }))190 }191 fn get_cheap(&self, _index: usize) -> Option<Val> {192 None193 }194 fn is_cheap(&self) -> bool {195 false196 }197}198199#[derive(Trace, Debug)]200pub struct ExtendedArray {201 pub a: ArrValue,202 pub b: ArrValue,203 split: usize,204 len: usize,205}206impl ExtendedArray {207 pub fn new(a: ArrValue, b: ArrValue) -> Self {208 let a_len = a.len();209 let b_len = b.len();210 Self {211 a,212 b,213 split: a_len,214 len: a_len.checked_add(b_len).expect("too large array value"),215 }216 }217}218219struct WithExactSize<I>(I, usize);220impl<I, T> Iterator for WithExactSize<I>221where222 I: Iterator<Item = T>,223{224 type Item = T;225226 fn next(&mut self) -> Option<Self::Item> {227 self.0.next()228 }229 fn nth(&mut self, n: usize) -> Option<Self::Item> {230 self.0.nth(n)231 }232 fn size_hint(&self) -> (usize, Option<usize>) {233 (self.1, Some(self.1))234 }235}236impl<I> DoubleEndedIterator for WithExactSize<I>237where238 I: DoubleEndedIterator,239{240 fn next_back(&mut self) -> Option<Self::Item> {241 self.0.next_back()242 }243 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {244 self.0.nth_back(n)245 }246}247impl<I> ExactSizeIterator for WithExactSize<I>248where249 I: Iterator,250{251 fn len(&self) -> usize {252 self.1253 }254}255impl ArrayLike for ExtendedArray {256 fn get(&self, index: usize) -> Result<Option<Val>> {257 if self.split > index {258 self.a.get(index)259 } else {260 self.b.get(index - self.split)261 }262 }263 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {264 if self.split > index {265 self.a.get_lazy(index)266 } else {267 self.b.get_lazy(index - self.split)268 }269 }270271 fn len(&self) -> usize {272 self.len273 }274275 fn get_cheap(&self, index: usize) -> Option<Val> {276 if self.split > index {277 self.a.get_cheap(index)278 } else {279 self.b.get_cheap(index - self.split)280 }281 }282 fn is_cheap(&self) -> bool {283 self.a.is_cheap() && self.b.is_cheap()284 }285}286287#[derive(Trace, Debug)]288pub struct LazyArray(pub Vec<Thunk<Val>>);289impl ArrayLike for LazyArray {290 fn len(&self) -> usize {291 self.0.len()292 }293 fn get(&self, index: usize) -> Result<Option<Val>> {294 let Some(v) = self.0.get(index) else {295 return Ok(None);296 };297 v.evaluate().map(Some)298 }299 fn get_cheap(&self, _index: usize) -> Option<Val> {300 None301 }302 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {303 self.0.get(index).cloned()304 }305 fn is_cheap(&self) -> bool {306 false307 }308}309310#[derive(Trace, Debug)]311pub struct EagerArray(pub Vec<Val>);312impl ArrayLike for EagerArray {313 fn len(&self) -> usize {314 self.0.len()315 }316317 fn get(&self, index: usize) -> Result<Option<Val>> {318 Ok(self.0.get(index).cloned())319 }320321 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {322 self.0.get(index).cloned().map(Thunk::evaluated)323 }324325 fn get_cheap(&self, index: usize) -> Option<Val> {326 self.0.get(index).cloned()327 }328 fn is_cheap(&self) -> bool {329 true330 }331}332333/// Inclusive range type334#[derive(Debug, Trace, PartialEq, Eq)]335pub struct RangeArray {336 start: i32,337 end: i32,338}339impl RangeArray {340 pub fn empty() -> Self {341 Self::new_exclusive(0, 0)342 }343 pub fn new_exclusive(start: i32, end: i32) -> Self {344 end.checked_sub(1)345 .map_or_else(Self::empty, |end| Self { start, end })346 }347 pub fn new_inclusive(start: i32, end: i32) -> Self {348 Self { start, end }349 }350 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {351 WithExactSize(352 self.start..=self.end,353 (self.end as usize)354 .wrapping_sub(self.start as usize)355 .wrapping_add(1),356 )357 }358}359360impl ArrayLike for RangeArray {361 fn len(&self) -> usize {362 self.range().len()363 }364 fn is_empty(&self) -> bool {365 self.range().len() == 0366 }367368 fn get(&self, index: usize) -> Result<Option<Val>> {369 Ok(self.get_cheap(index))370 }371372 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {373 self.get_cheap(index).map(Thunk::evaluated)374 }375376 fn get_cheap(&self, index: usize) -> Option<Val> {377 self.range().nth(index).map(|i| Val::Num(i.into()))378 }379 fn is_cheap(&self) -> bool {380 true381 }382}383384#[derive(Debug, Trace)]385pub struct ReverseArray(pub ArrValue);386impl ArrayLike for ReverseArray {387 fn len(&self) -> usize {388 self.0.len()389 }390391 fn get(&self, index: usize) -> Result<Option<Val>> {392 self.0.get(self.0.len() - index - 1)393 }394395 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {396 self.0.get_lazy(self.0.len() - index - 1)397 }398399 fn get_cheap(&self, index: usize) -> Option<Val> {400 self.0.get_cheap(self.0.len() - index - 1)401 }402 fn is_cheap(&self) -> bool {403 self.0.is_cheap()404 }405}406407#[derive(Trace, Debug, Clone)]408pub struct MappedArray<const WITH_INDEX: bool> {409 inner: ArrValue,410 cached: Cc<RefCell<Vec<ArrayThunk>>>,411 mapper: FuncVal,412}413impl<const WITH_INDEX: bool> MappedArray<WITH_INDEX> {414 pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {415 let len = inner.len();416 Self {417 inner,418 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len])),419 mapper,420 }421 }422 fn evaluate(&self, index: usize, value: Val) -> Result<Val> {423 if WITH_INDEX {424 self.mapper.evaluate_simple(&(index, value), false)425 } else {426 self.mapper.evaluate_simple(&(value,), false)427 }428 }429}430impl<const WITH_INDEX: bool> ArrayLike for MappedArray<WITH_INDEX> {431 fn len(&self) -> usize {432 self.cached.borrow().len()433 }434435 fn get(&self, index: usize) -> Result<Option<Val>> {436 if index >= self.len() {437 return Ok(None);438 }439 match &self.cached.borrow()[index] {440 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),441 ArrayThunk::Errored(e) => return Err(e.clone()),442 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),443 ArrayThunk::Waiting => {}444 }445446 let ArrayThunk::Waiting =447 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)448 else {449 unreachable!()450 };451452 let val = self453 .inner454 .get(index)455 .transpose()456 .expect("index checked")457 .and_then(|r| self.evaluate(index, r));458459 let new_value = match val {460 Ok(v) => v,461 Err(e) => {462 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());463 return Err(e);464 }465 };466 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());467 Ok(Some(new_value))468 }469 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {470 #[derive(Trace)]471 struct MappedArrayThunk<const WITH_INDEX: bool> {472 arr: MappedArray<WITH_INDEX>,473 index: usize,474 }475 impl<const WITH_INDEX: bool> ThunkValue for MappedArrayThunk<WITH_INDEX> {476 type Output = Val;477478 fn get(&self) -> Result<Self::Output> {479 self.arr.get(self.index).transpose().expect("index checked")480 }481 }482483 if index >= self.len() {484 return None;485 }486 match &self.cached.borrow()[index] {487 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),488 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),489 ArrayThunk::Waiting | ArrayThunk::Pending => {}490 }491492 Some(Thunk::new(MappedArrayThunk {493 arr: self.clone(),494 index,495 }))496 }497498 fn get_cheap(&self, _index: usize) -> Option<Val> {499 None500 }501 fn is_cheap(&self) -> bool {502 false503 }504}505506#[derive(Trace, Debug)]507pub struct RepeatedArray {508 data: ArrValue,509 repeats: usize,510 total_len: usize,511}512impl RepeatedArray {513 pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {514 let total_len = data.len().checked_mul(repeats)?;515 Some(Self {516 data,517 repeats,518 total_len,519 })520 }521}522523impl ArrayLike for RepeatedArray {524 fn len(&self) -> usize {525 self.total_len526 }527528 fn get(&self, index: usize) -> Result<Option<Val>> {529 if index > self.total_len {530 return Ok(None);531 }532 self.data.get(index % self.data.len())533 }534535 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {536 if index > self.total_len {537 return None;538 }539 self.data.get_lazy(index % self.data.len())540 }541542 fn get_cheap(&self, index: usize) -> Option<Val> {543 if index > self.total_len {544 return None;545 }546 self.data.get_cheap(index % self.data.len())547 }548 fn is_cheap(&self) -> bool {549 self.data.is_cheap()550 }551}552553#[derive(Trace, Debug)]554pub struct PickObjectValues {555 obj: ObjValue,556 keys: Vec<IStr>,557}558559impl PickObjectValues {560 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {561 Self { obj, keys }562 }563}564565impl ArrayLike for PickObjectValues {566 fn len(&self) -> usize {567 self.keys.len()568 }569570 fn get(&self, index: usize) -> Result<Option<Val>> {571 let Some(key) = self.keys.get(index) else {572 return Ok(None);573 };574 Ok(Some(self.obj.get_or_bail(key.clone())?))575 }576577 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {578 let key = self.keys.get(index)?;579 Some(self.obj.get_lazy_or_bail(key.clone()))580 }581582 fn get_cheap(&self, _index: usize) -> Option<Val> {583 None584 }585586 fn is_cheap(&self) -> bool {587 false588 }589}590591#[derive(Trace, Debug)]592pub struct PickObjectKeyValues {593 obj: ObjValue,594 keys: Vec<IStr>,595}596597impl PickObjectKeyValues {598 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {599 Self { obj, keys }600 }601}602603#[derive(Typed)]604pub struct KeyValue {605 key: IStr,606 value: Thunk<Val>,607}608609impl ArrayLike for PickObjectKeyValues {610 fn len(&self) -> usize {611 self.keys.len()612 }613614 fn get(&self, index: usize) -> Result<Option<Val>> {615 let Some(key) = self.keys.get(index) else {616 return Ok(None);617 };618 Ok(Some(619 KeyValue::into_untyped(KeyValue {620 key: key.clone(),621 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),622 })623 .expect("convertible"),624 ))625 }626627 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {628 let key = self.keys.get(index)?;629 // Nothing can fail in the key part, yet value is still630 // lazy-evaluated631 Some(Thunk::evaluated(632 KeyValue::into_untyped(KeyValue {633 key: key.clone(),634 value: self.obj.get_lazy_or_bail(key.clone()),635 })636 .expect("convertible"),637 ))638 }639640 fn get_cheap(&self, _index: usize) -> Option<Val> {641 None642 }643644 fn is_cheap(&self) -> bool {645 false646 }647}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.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(())
-}