difftreelog
perf use prepared call for KeyF
in: master
9 files changed
crates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -3,8 +3,8 @@
use jrsonnet_gcmodule::{cc_dyn, Trace, TraceBox};
use jrsonnet_parser::function::{FunctionSignature, ParamDefault, ParamName, ParamParse};
-use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
-use crate::{Context, Result, Val};
+use super::CallLocation;
+use crate::{Result, Thunk, Val};
#[macro_export]
macro_rules! params {
@@ -34,8 +34,8 @@
self.0.params()
}
- fn call(&self, ctx: Context, loc: CallLocation<'_>, args: &dyn ArgsLike) -> Result<Val> {
- self.0.call(ctx, loc, args)
+ fn call(&self, loc: CallLocation<'_>, args: &[Option<Thunk<Val>>]) -> Result<Val> {
+ self.0.call(loc, args)
}
fn as_any(&self) -> &dyn Any {
@@ -52,7 +52,7 @@
/// Parameter names for named calls
fn params(&self) -> FunctionSignature;
/// Call the builtin
- fn call(&self, ctx: Context, loc: CallLocation<'_>, args: &dyn ArgsLike) -> Result<Val>;
+ fn call(&self, loc: CallLocation<'_>, args: &[Option<Thunk<Val>>]) -> Result<Val>;
fn as_any(&self) -> &dyn Any;
}
@@ -96,11 +96,10 @@
self.params.clone()
}
- fn call(&self, ctx: Context, _loc: CallLocation<'_>, args: &dyn ArgsLike) -> Result<Val> {
- let args = parse_builtin_call(ctx, self.params.clone(), args, true)?;
+ fn call(&self, _loc: CallLocation<'_>, args: &[Option<Thunk<Val>>]) -> Result<Val> {
let args = args
.into_iter()
- .map(|a| a.expect("legacy natives have no default params"))
+ .map(|a| a.as_ref().expect("legacy natives have no default params"))
.map(|a| a.evaluate())
.collect::<Result<Vec<Val>>>()?;
self.handler.call(&args)
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -11,7 +11,8 @@
arglike::OptionalContext,
builtin::{Builtin, StaticBuiltin},
native::NativeDesc,
- parse::{parse_default_function_call, parse_function_call},
+ 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,
@@ -22,7 +23,9 @@
pub mod builtin;
pub mod native;
pub mod parse;
-pub mod prepared;
+mod prepared;
+
+pub use prepared::PreparedFuncVal;
pub use jrsonnet_parser::function::*;
@@ -173,7 +176,6 @@
tailstrict: bool,
) -> Result<Val> {
match self {
- Self::Id => ID.call(call_ctx, loc, args),
Self::Normal(func) => {
let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;
evaluate(body_ctx, &func.body)
@@ -184,8 +186,18 @@
}
thunk.evaluate()
}
- Self::StaticBuiltin(b) => b.call(call_ctx, loc, args),
- Self::Builtin(b) => b.call(call_ctx, loc, args),
+ Self::Id => {
+ let args = parse_builtin_call(call_ctx, ID.params(), args, tailstrict)?;
+ ID.call(loc, &args)
+ }
+ Self::StaticBuiltin(b) => {
+ let args = parse_builtin_call(call_ctx, b.params(), args, tailstrict)?;
+ b.call(loc, &args)
+ }
+ Self::Builtin(b) => {
+ let args = parse_builtin_call(call_ctx, b.params(), args, tailstrict)?;
+ b.call(loc, &args)
+ }
}
}
pub fn evaluate_simple<A: ArgsLike + OptionalContext>(
@@ -200,6 +212,41 @@
tailstrict,
)
}
+
+ pub(crate) fn evaluate_prepared(
+ &self,
+ prepared: &PreparedCall,
+ loc: CallLocation<'_>,
+ unnamed: &[Thunk<Val>],
+ named: &[Thunk<Val>],
+ _tailstrict: bool,
+ ) -> Result<Val> {
+ match self {
+ FuncVal::Id => {
+ let args = parse_prepared_builtin_call(prepared, ID.params(), unnamed, named)?;
+ ID.call(loc, &args)
+ }
+ FuncVal::Normal(func) => {
+ let body_ctx = parse_prepared_function_call(
+ func.ctx.clone(),
+ prepared,
+ &func.params,
+ unnamed,
+ named,
+ )?;
+ evaluate(body_ctx, &func.body)
+ }
+ FuncVal::Thunk(t) => t.evaluate(),
+ FuncVal::StaticBuiltin(b) => {
+ let args = parse_prepared_builtin_call(prepared, b.params(), unnamed, named)?;
+ b.call(loc, &args)
+ }
+ FuncVal::Builtin(b) => {
+ let args = parse_prepared_builtin_call(prepared, b.params(), unnamed, named)?;
+ b.call(loc, &args)
+ }
+ }
+ }
/// Convert jsonnet function to plain `Fn` value.
pub fn into_native<D: NativeDesc>(self) -> D::Value {
D::into_native(self)
crates/jrsonnet-evaluator/src/function/prepared.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/prepared.rs
+++ b/crates/jrsonnet-evaluator/src/function/prepared.rs
@@ -1,3 +1,6 @@
+use std::rc::Rc;
+
+use jrsonnet_gcmodule::{Acyclic, Trace};
use jrsonnet_parser::function::FunctionSignature;
use jrsonnet_parser::{ExprParams, IStr};
use rustc_hash::{FxHashMap, FxHashSet};
@@ -7,6 +10,34 @@
use crate::{bail, error::ErrorKind::*, Result};
use crate::{evaluate_named_param, Context, ContextBuilder, Pending, Thunk, Val};
+use super::{CallLocation, FuncVal};
+
+#[derive(Debug, Trace, Clone)]
+pub struct PreparedFuncVal {
+ fun: FuncVal,
+ prepared: Rc<PreparedCall>,
+}
+
+impl PreparedFuncVal {
+ pub fn new(fun: FuncVal, unnamed: usize, named: &[IStr]) -> Result<Self> {
+ let prepared = prepare_call(fun.params(), unnamed, named)?;
+ Ok(Self {
+ fun,
+ prepared: Rc::new(prepared),
+ })
+ }
+ pub fn call(
+ &self,
+ loc: CallLocation<'_>,
+ unnamed: &[Thunk<Val>],
+ named: &[Thunk<Val>],
+ ) -> Result<Val> {
+ self.fun
+ .evaluate_prepared(&self.prepared, loc, unnamed, named, false)
+ }
+}
+
+#[derive(Acyclic, Debug)]
pub struct PreparedCall {
// Param, named input.
named: Vec<(usize, usize)>,
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -3,16 +3,32 @@
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::{
- parenthesized,
- parse::{Parse, ParseStream},
- parse_macro_input,
- punctuated::Punctuated,
- spanned::Spanned,
- token::{self, Comma},
- Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,
- LitStr, Pat, Path, PathArguments, Result, ReturnType, Token, Type,
+ 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}
};
+fn try_parse_attr_noargs<I>(attrs: &[Attribute], ident: I) -> Result<bool>
+where
+ Ident: PartialEq<I>,
+{
+ let attrs = attrs
+ .iter()
+ .filter(|a| a.path().is_ident(&ident))
+ .collect::<Vec<_>>();
+ if attrs.len() > 1 {
+ return Err(Error::new(
+ attrs[1].span(),
+ "this attribute may be specified only once",
+ ));
+ } else if attrs.is_empty() {
+ return Ok(false);
+ }
+ let attr = attrs[0];
+
+ match attr.meta {
+ Meta::Path(_) => Ok(true),
+ _ => Ok(false),
+ }
+}
fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>
where
Ident: PartialEq<I>,
@@ -125,9 +141,13 @@
Required,
Optional,
Default(Expr),
+ TypeDefault,
}
-#[allow(clippy::large_enum_variant, reason = "this macro is not that hot for it to matter")]
+#[allow(
+ clippy::large_enum_variant,
+ reason = "this macro is not that hot for it to matter"
+)]
enum ArgInfo {
Normal {
ty: Box<Type>,
@@ -170,7 +190,10 @@
_ => {}
}
- let (optionality, ty) = if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {
+ let (optionality, ty) = if try_parse_attr_noargs(&mut arg.attrs, "default")? {
+ remove_attr(&mut arg.attrs, "default");
+ (Optionality::TypeDefault, ty.clone())
+ } else if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {
remove_attr(&mut arg.attrs, "default");
(Optionality::Default(default), ty.clone())
} else if let Some(ty) = extract_type_from_option(ty)? {
@@ -245,7 +268,7 @@
.map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});
let default = match optionality {
Optionality::Required => quote!(ParamDefault::None),
- Optionality::Optional => quote!(ParamDefault::Exists),
+ Optionality::Optional | Optionality::TypeDefault => quote!(ParamDefault::Exists),
Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),
};
Some(quote! {
@@ -305,6 +328,12 @@
let v: #ty = #expr;
v
},},
+ Optionality::TypeDefault => quote! {if let Some(value) = &parsed[#id] {
+ #eval
+ } else {
+ let v: #ty = Default::default();
+ v
+ },},
};
quote! {
#(#cfg_attrs)*
@@ -371,7 +400,7 @@
State, Val,
function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation, ArgsLike, parse::parse_builtin_call},
Result, Context, typed::Typed,
- parser::Span, params,
+ parser::Span, params, Thunk,
};
params!(
#(#params_desc)*
@@ -389,9 +418,7 @@
PARAMS.with(|p| p.clone())
}
#[allow(unused_variables)]
- fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
- let parsed = parse_builtin_call(ctx.clone(), self.params(), args, false)?;
-
+ fn call(&self, location: CallLocation<'_>, parsed: &[Option<Thunk<Val>>]) -> Result<Val> {
let result: #result = #name(#(#pass)*);
<_ as Typed>::into_result(result)
}
crates/jrsonnet-stdlib/src/keyf.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/keyf.rs
@@ -0,0 +1,41 @@
+use jrsonnet_evaluator::function::{CallLocation, FuncVal, PreparedFuncVal};
+use jrsonnet_evaluator::typed::{ComplexValType, Typed, ValType};
+use jrsonnet_evaluator::{Error, Result, Thunk, Val};
+
+#[derive(Default, Clone)]
+pub enum KeyF {
+ #[default]
+ Identity,
+ Prepared(PreparedFuncVal),
+ PrepareFailure(Error),
+}
+impl KeyF {
+ pub fn is_identity(&self) -> bool {
+ matches!(self, Self::Identity)
+ }
+ fn new(val: FuncVal) -> Self {
+ if val.is_identity() {
+ Self::Identity
+ } else {
+ PreparedFuncVal::new(val, 1, &[]).map_or_else(Self::PrepareFailure, Self::Prepared)
+ }
+ }
+ pub fn eval(&self, val: impl Into<Thunk<Val>>) -> Result<Val> {
+ match self {
+ KeyF::Identity => val.into().evaluate(),
+ KeyF::Prepared(p) => p.call(CallLocation::native(), &[val.into()], &[]),
+ KeyF::PrepareFailure(e) => Err(e.clone()),
+ }
+ }
+}
+
+impl Typed for KeyF {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
+ 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/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -50,6 +50,7 @@
mod sort;
mod strings;
mod types;
+mod keyf;
#[allow(clippy::too_many_lines)]
pub fn stdlib_uncached(settings: Cc<RefCell<Settings>>) -> ObjValue {
crates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth1use std::cmp::Ordering;23use jrsonnet_evaluator::{4 function::{builtin, FuncVal},5 operator::evaluate_compare_op,6 val::ArrValue,7 Result, Thunk, Val,8};9use jrsonnet_parser::BinaryOpType;1011#[builtin]12#[allow(non_snake_case)]13pub fn builtin_set_member(x: Thunk<Val>, arr: ArrValue, keyF: Option<FuncVal>) -> Result<bool> {14 let mut low = 0;15 let mut high = arr.len();1617 let keyF = keyF18 .unwrap_or(FuncVal::Id)19 .into_native::<((Thunk<Val>,), Val)>();2021 let x = keyF(x)?;2223 while low < high {24 let middle = usize::midpoint(high, low);25 let comp = keyF(arr.get_lazy(middle).expect("in bounds"))?;26 match evaluate_compare_op(&comp, &x, BinaryOpType::Lt)? {27 Ordering::Less => low = middle + 1,28 Ordering::Equal => return Ok(true),29 Ordering::Greater => high = middle,30 }31 }32 Ok(false)33}3435#[builtin]36#[allow(non_snake_case, clippy::redundant_closure)]37pub fn builtin_set_inter(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {38 let mut a = a.iter_lazy();39 let mut b = b.iter_lazy();4041 let keyF = keyF42 .unwrap_or(FuncVal::identity())43 .into_native::<((Thunk<Val>,), Val)>();44 let keyF = |v| keyF(v);4546 let mut av = a.next();47 let mut bv = b.next();48 let mut ak = av.clone().map(keyF).transpose()?;49 let mut bk = bv.map(keyF).transpose()?;5051 let mut out = Vec::new();52 while let (Some(ac), Some(bc)) = (&ak, &bk) {53 match evaluate_compare_op(ac, bc, BinaryOpType::Lt)? {54 Ordering::Less => {55 av = a.next();56 ak = av.clone().map(keyF).transpose()?;57 }58 Ordering::Greater => {59 bv = b.next();60 bk = bv.map(keyF).transpose()?;61 }62 Ordering::Equal => {63 out.push(av.clone().expect("ak != None => av != None"));64 av = a.next();65 ak = av.clone().map(keyF).transpose()?;66 bv = b.next();67 bk = bv.map(keyF).transpose()?;68 }69 }70 }71 Ok(ArrValue::lazy(out))72}7374#[builtin]75#[allow(non_snake_case, clippy::redundant_closure)]76pub fn builtin_set_diff(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {77 let mut a = a.iter_lazy();78 let mut b = b.iter_lazy();7980 let keyF = keyF81 .unwrap_or(FuncVal::identity())82 .into_native::<((Thunk<Val>,), Val)>();83 let keyF = |v| keyF(v);8485 let mut av = a.next();86 let mut bv = b.next();87 let mut ak = av.clone().map(keyF).transpose()?;88 let mut bk = bv.map(keyF).transpose()?;8990 let mut out = Vec::new();91 while let (Some(ac), Some(bc)) = (&ak, &bk) {92 match evaluate_compare_op(ac, bc, BinaryOpType::Lt)? {93 Ordering::Less => {94 // In a, but not in b95 out.push(av.clone().expect("ak != None"));96 av = a.next();97 ak = av.clone().map(keyF).transpose()?;98 }99 Ordering::Greater => {100 bv = b.next();101 bk = bv.map(keyF).transpose()?;102 }103 Ordering::Equal => {104 av = a.next();105 ak = av.clone().map(keyF).transpose()?;106 bv = b.next();107 bk = bv.map(keyF).transpose()?;108 }109 }110 }111 while let Some(_ac) = &ak {112 // In a, but not in b113 out.push(av.clone().expect("ak != None"));114 av = a.next();115 ak = av.clone().map(keyF).transpose()?;116 }117 Ok(ArrValue::lazy(out))118}119120#[builtin]121#[allow(non_snake_case, clippy::redundant_closure)]122pub fn builtin_set_union(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {123 let mut a = a.iter_lazy();124 let mut b = b.iter_lazy();125126 let keyF = keyF127 .unwrap_or(FuncVal::identity())128 .into_native::<((Thunk<Val>,), Val)>();129 let keyF = |v| keyF(v);130131 let mut av = a.next();132 let mut bv = b.next();133 let mut ak = av.clone().map(keyF).transpose()?;134 let mut bk = bv.clone().map(keyF).transpose()?;135136 let mut out = Vec::new();137 while let (Some(ac), Some(bc)) = (&ak, &bk) {138 match evaluate_compare_op(ac, bc, BinaryOpType::Lt)? {139 Ordering::Less => {140 out.push(av.clone().expect("ak != None"));141 av = a.next();142 ak = av.clone().map(keyF).transpose()?;143 }144 Ordering::Greater => {145 out.push(bv.clone().expect("bk != None"));146 bv = b.next();147 bk = bv.clone().map(keyF).transpose()?;148 }149 Ordering::Equal => {150 // NOTE: order matters, values in `a` win151 out.push(av.clone().expect("ak != None"));152 av = a.next();153 ak = av.clone().map(keyF).transpose()?;154 bv = b.next();155 bk = bv.clone().map(keyF).transpose()?;156 }157 }158 }159 // a.len() > b.len()160 while let Some(_ac) = &ak {161 out.push(av.clone().expect("ak != None"));162 av = a.next();163 ak = av.clone().map(keyF).transpose()?;164 }165 // b.len() > a.len()166 while let Some(_bc) = &bk {167 out.push(bv.clone().expect("ak != None"));168 bv = b.next();169 bk = bv.clone().map(keyF).transpose()?;170 }171 Ok(ArrValue::lazy(out))172}1use std::cmp::Ordering;23use jrsonnet_evaluator::{4 function::builtin, operator::evaluate_compare_op, val::ArrValue, Result, Thunk, Val,5};6use jrsonnet_parser::BinaryOpType;78use crate::keyf::KeyF;910#[builtin]11#[allow(non_snake_case)]12pub fn builtin_set_member(x: Thunk<Val>, arr: ArrValue, #[default] keyF: KeyF) -> Result<bool> {13 let mut low = 0;14 let mut high = arr.len();1516 let x = keyF.eval(x)?;1718 while low < high {19 let middle = usize::midpoint(high, low);20 let comp = keyF.eval(arr.get_lazy(middle).expect("in bounds"))?;21 match evaluate_compare_op(&comp, &x, BinaryOpType::Lt)? {22 Ordering::Less => low = middle + 1,23 Ordering::Equal => return Ok(true),24 Ordering::Greater => high = middle,25 }26 }27 Ok(false)28}2930#[builtin]31#[allow(non_snake_case, clippy::redundant_closure)]32pub fn builtin_set_inter(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {33 let mut a = a.iter_lazy();34 let mut b = b.iter_lazy();3536 let keyF = |v| keyF.eval(v);3738 let mut av = a.next();39 let mut bv = b.next();40 let mut ak = av.clone().map(keyF).transpose()?;41 let mut bk = bv.map(keyF).transpose()?;4243 let mut out = Vec::new();44 while let (Some(ac), Some(bc)) = (&ak, &bk) {45 match evaluate_compare_op(ac, bc, BinaryOpType::Lt)? {46 Ordering::Less => {47 av = a.next();48 ak = av.clone().map(keyF).transpose()?;49 }50 Ordering::Greater => {51 bv = b.next();52 bk = bv.map(keyF).transpose()?;53 }54 Ordering::Equal => {55 out.push(av.clone().expect("ak != None => av != None"));56 av = a.next();57 ak = av.clone().map(keyF).transpose()?;58 bv = b.next();59 bk = bv.map(keyF).transpose()?;60 }61 }62 }63 Ok(ArrValue::lazy(out))64}6566#[builtin]67#[allow(non_snake_case, clippy::redundant_closure)]68pub fn builtin_set_diff(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {69 let mut a = a.iter_lazy();70 let mut b = b.iter_lazy();7172 let keyF = |v| keyF.eval(v);7374 let mut av = a.next();75 let mut bv = b.next();76 let mut ak = av.clone().map(keyF).transpose()?;77 let mut bk = bv.map(keyF).transpose()?;7879 let mut out = Vec::new();80 while let (Some(ac), Some(bc)) = (&ak, &bk) {81 match evaluate_compare_op(ac, bc, BinaryOpType::Lt)? {82 Ordering::Less => {83 // In a, but not in b84 out.push(av.clone().expect("ak != None"));85 av = a.next();86 ak = av.clone().map(keyF).transpose()?;87 }88 Ordering::Greater => {89 bv = b.next();90 bk = bv.map(keyF).transpose()?;91 }92 Ordering::Equal => {93 av = a.next();94 ak = av.clone().map(keyF).transpose()?;95 bv = b.next();96 bk = bv.map(keyF).transpose()?;97 }98 }99 }100 while let Some(_ac) = &ak {101 // In a, but not in b102 out.push(av.clone().expect("ak != None"));103 av = a.next();104 ak = av.clone().map(keyF).transpose()?;105 }106 Ok(ArrValue::lazy(out))107}108109#[builtin]110#[allow(non_snake_case, clippy::redundant_closure)]111pub fn builtin_set_union(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {112 let mut a = a.iter_lazy();113 let mut b = b.iter_lazy();114115 let keyF = |v| keyF.eval(v);116117 let mut av = a.next();118 let mut bv = b.next();119 let mut ak = av.clone().map(keyF).transpose()?;120 let mut bk = bv.clone().map(keyF).transpose()?;121122 let mut out = Vec::new();123 while let (Some(ac), Some(bc)) = (&ak, &bk) {124 match evaluate_compare_op(ac, bc, BinaryOpType::Lt)? {125 Ordering::Less => {126 out.push(av.clone().expect("ak != None"));127 av = a.next();128 ak = av.clone().map(keyF).transpose()?;129 }130 Ordering::Greater => {131 out.push(bv.clone().expect("bk != None"));132 bv = b.next();133 bk = bv.clone().map(keyF).transpose()?;134 }135 Ordering::Equal => {136 // NOTE: order matters, values in `a` win137 out.push(av.clone().expect("ak != None"));138 av = a.next();139 ak = av.clone().map(keyF).transpose()?;140 bv = b.next();141 bk = bv.clone().map(keyF).transpose()?;142 }143 }144 }145 // a.len() > b.len()146 while let Some(_ac) = &ak {147 out.push(av.clone().expect("ak != None"));148 av = a.next();149 ak = av.clone().map(keyF).transpose()?;150 }151 // b.len() > a.len()152 while let Some(_bc) = &bk {153 out.push(bv.clone().expect("ak != None"));154 bv = b.next();155 bk = bv.clone().map(keyF).transpose()?;156 }157 Ok(ArrValue::lazy(out))158}crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -4,14 +4,14 @@
use jrsonnet_evaluator::{
bail,
- function::{builtin, FuncVal},
+ function::builtin,
operator::evaluate_compare_op,
val::{equals, ArrValue},
Result, Thunk, Val,
};
use jrsonnet_parser::BinaryOpType;
-use crate::eval_on_empty;
+use crate::{eval_on_empty, keyf::KeyF};
#[derive(Copy, Clone)]
enum SortKeyType {
@@ -70,14 +70,11 @@
Ok(values)
}
-fn sort_keyf(values: ArrValue, keyf: FuncVal) -> Result<Vec<Thunk<Val>>> {
+fn sort_keyf(values: ArrValue, keyf: KeyF) -> Result<Vec<Thunk<Val>>> {
// Slow path, user provided key getter
let mut vk = Vec::with_capacity(values.len());
for value in values.iter_lazy() {
- vk.push((
- value.clone(),
- keyf.evaluate_simple(&(value.clone(),), false)?,
- ));
+ vk.push((value.clone(), keyf.eval(value)?));
}
let sort_type = get_sort_type(&vk, |v| &v.1)?;
match sort_type {
@@ -112,7 +109,7 @@
}
/// * `key_getter` - None, if identity sort required
-pub fn sort(values: ArrValue, key_getter: FuncVal) -> Result<ArrValue> {
+pub fn sort(values: ArrValue, key_getter: KeyF) -> Result<ArrValue> {
if values.len() <= 1 {
return Ok(values);
}
@@ -126,11 +123,7 @@
}
#[builtin]
-pub fn builtin_sort(
- arr: ArrValue,
-
- #[default(FuncVal::identity())] keyF: FuncVal,
-) -> Result<ArrValue> {
+pub fn builtin_sort(arr: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
super::sort::sort(arr, keyF)
}
@@ -147,14 +140,14 @@
Ok(out)
}
-fn uniq_keyf(arr: ArrValue, keyf: FuncVal) -> Result<Vec<Thunk<Val>>> {
+fn uniq_keyf(arr: ArrValue, keyf: KeyF) -> Result<Vec<Thunk<Val>>> {
let mut out = Vec::new();
let last_value = arr.get_lazy(0).unwrap();
- let mut last_key = keyf.evaluate_simple(&(last_value.clone(),), false)?;
+ let mut last_key = keyf.eval(last_value.clone())?;
out.push(last_value);
for next in arr.iter_lazy().skip(1) {
- let next_key = keyf.evaluate_simple(&(next.clone(),), false)?;
+ let next_key = keyf.eval(next.clone())?;
if !equals(&last_key, &next_key)? {
out.push(next.clone());
}
@@ -165,11 +158,7 @@
#[builtin]
#[allow(non_snake_case)]
-pub fn builtin_uniq(
- arr: ArrValue,
-
- #[default(FuncVal::identity())] keyF: FuncVal,
-) -> Result<ArrValue> {
+pub fn builtin_uniq(arr: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
if arr.len() <= 1 {
return Ok(arr);
}
@@ -184,11 +173,7 @@
#[builtin]
#[allow(non_snake_case)]
-pub fn builtin_set(
- arr: ArrValue,
-
- #[default(FuncVal::identity())] keyF: FuncVal,
-) -> Result<ArrValue> {
+pub fn builtin_set(arr: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
if arr.len() <= 1 {
return Ok(arr);
}
@@ -201,24 +186,16 @@
let arr = sort_keyf(arr, keyF.clone())?;
let arr = uniq_keyf(ArrValue::lazy(arr), keyF)?;
Ok(ArrValue::lazy(arr))
- }
-}
-
-fn eval_keyf(val: Val, key_f: Option<&FuncVal>) -> Result<Val> {
- if let Some(key_f) = key_f {
- key_f.evaluate_simple(&(val,), false)
- } else {
- Ok(val)
}
}
-fn array_top1(arr: ArrValue, key_f: Option<&FuncVal>, ordering: Ordering) -> Result<Val> {
+fn array_top1(arr: ArrValue, keyf: KeyF, ordering: Ordering) -> Result<Val> {
let mut iter = arr.iter();
let mut min = iter.next().expect("not empty")?;
- let mut min_key = eval_keyf(min.clone(), key_f)?;
+ let mut min_key = keyf.eval(Thunk::evaluated(min.clone()))?;
for item in iter {
let cur = item?;
- let cur_key = eval_keyf(cur.clone(), key_f)?;
+ let cur_key = keyf.eval(Thunk::evaluated(cur.clone()))?;
if evaluate_compare_op(&cur_key, &min_key, BinaryOpType::Lt)? == ordering {
min = cur;
min_key = cur_key;
@@ -230,22 +207,22 @@
#[builtin]
pub fn builtin_min_array(
arr: ArrValue,
- keyF: Option<FuncVal>,
+ #[default] keyF: KeyF,
onEmpty: Option<Thunk<Val>>,
) -> Result<Val> {
if arr.is_empty() {
return eval_on_empty(onEmpty);
}
- array_top1(arr, keyF.as_ref(), Ordering::Less)
+ array_top1(arr, keyF, Ordering::Less)
}
#[builtin]
pub fn builtin_max_array(
arr: ArrValue,
- keyF: Option<FuncVal>,
+ #[default] keyF: KeyF,
onEmpty: Option<Thunk<Val>>,
) -> Result<Val> {
if arr.is_empty() {
return eval_on_empty(onEmpty);
}
- array_top1(arr, keyF.as_ref(), Ordering::Greater)
+ array_top1(arr, keyF, Ordering::Greater)
}
tests/tests/builtin.rsdiffbeforeafterboth--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -18,8 +18,7 @@
#[test]
fn basic_function() -> Result<()> {
let a: a = a {};
- let v =
- u32::from_untyped(a.call(ContextBuilder::new().build(), CallLocation::native(), &())?)?;
+ let v = u32::from_untyped(a.call(CallLocation::native(), &[])?)?;
ensure_eq!(v, 1);
Ok(())