difftreelog
refactor drop ArgsLike abstraction
in: master
17 files changed
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -22,11 +22,11 @@
use jrsonnet_evaluator::{
apply_tla, bail,
- function::TlaArg,
gc::WithCapacityExt as _,
manifest::{JsonFormat, ManifestFormat, ToStringFormat},
rustc_hash::FxHashMap,
stack::set_stack_depth_limit,
+ tla::TlaArg,
trace::{CompactFormat, PathResolver, TraceFormat},
AsPathLike, FileImportResolver, IStr, ImportResolver, Result, State, Val,
};
@@ -40,6 +40,7 @@
pub extern "C" fn _start() {}
/// Return the version string of the Jsonnet interpreter.
+///
/// Conforms to [semantic versioning](http://semver.org/).
/// If this does not match `LIB_JSONNET_VERSION`
/// then there is a mismatch between header and compiled library.
bindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -2,7 +2,8 @@
use std::{ffi::CStr, os::raw::c_char};
-use jrsonnet_evaluator::{function::TlaArg, IStr};
+use jrsonnet_evaluator::tla::TlaArg;
+use jrsonnet_evaluator::IStr;
use crate::VM;
crates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -1,7 +1,8 @@
use std::str::FromStr;
use clap::Parser;
-use jrsonnet_evaluator::{function::TlaArg, trace::PathResolver, Result};
+use jrsonnet_evaluator::tla::TlaArg;
+use jrsonnet_evaluator::{trace::PathResolver, Result};
use jrsonnet_stdlib::ContextInitializer;
#[derive(Clone)]
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,7 +1,6 @@
use clap::Parser;
-use jrsonnet_evaluator::{
- error::Result, function::TlaArg, gc::WithCapacityExt as _, rustc_hash::FxHashMap, IStr,
-};
+use jrsonnet_evaluator::tla::TlaArg;
+use jrsonnet_evaluator::{error::Result, gc::WithCapacityExt as _, rustc_hash::FxHashMap, IStr};
use crate::{ExtFile, ExtStr};
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -9,7 +9,7 @@
use jrsonnet_interner::IBytes;
use jrsonnet_parser::{Expr, Spanned};
-use crate::{typed::NativeFn, Context, Result, Thunk, Val};
+use crate::{function::NativeFn, Context, Result, Thunk, Val};
mod spec;
pub use spec::{ArrayLike, *};
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -6,8 +6,7 @@
use jrsonnet_parser::{Expr, Spanned};
use super::ArrValue;
-use crate::typed::NativeFn;
-use crate::val::NumValue;
+use crate::function::NativeFn;
use crate::{
error::ErrorKind::InfiniteRecursionDetected, evaluate, typed::Typed, val::ThunkValue, Context,
Error, ObjValue, Result, Thunk, Val,
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ /dev/null
@@ -1,197 +0,0 @@
-use std::collections::HashMap;
-use std::rc::Rc;
-
-use jrsonnet_gcmodule::Trace;
-use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ArgsDesc, Expr, SourceFifo, SourcePath, Spanned};
-
-use crate::{evaluate, typed::Typed, with_state, Context, Result, Thunk, Val};
-
-pub trait ArgLike {
- fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>>;
-}
-
-impl ArgLike for &Rc<Spanned<Expr>> {
- fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
- Ok(if tailstrict {
- Thunk::evaluated(evaluate(ctx, self)?)
- } else {
- let expr = (*self).clone();
- Thunk!(move || evaluate(ctx, &expr))
- })
- }
-}
-
-impl<T> ArgLike for T
-where
- T: Typed + Clone,
-{
- fn evaluate_arg(&self, _ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
- if T::provides_lazy() && !tailstrict {
- return Ok(T::into_lazy_untyped(self.clone()));
- }
- let val = T::into_untyped(self.clone())?;
- Ok(Thunk::evaluated(val))
- }
-}
-
-#[derive(Clone, Trace)]
-pub enum TlaArg {
- String(IStr),
- Val(Val),
- Lazy(Thunk<Val>),
- Import(String),
- ImportStr(String),
- InlineCode(String),
-}
-impl TlaArg {
- pub fn evaluate_tailstrict(&self) -> Result<Val> {
- match self {
- Self::String(s) => Ok(Val::string(s.clone())),
- Self::Val(val) => Ok(val.clone()),
- Self::Lazy(lazy) => Ok(lazy.evaluate()?),
- Self::Import(p) => with_state(|s| {
- let resolved = s.resolve_from_default(&p.as_str())?;
- s.import_resolved(resolved)
- }),
- Self::ImportStr(p) => with_state(|s| {
- let resolved = s.resolve_from_default(&p.as_str())?;
- s.import_resolved_str(resolved).map(Val::string)
- }),
- Self::InlineCode(p) => with_state(|s| {
- let resolved =
- SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
- s.import_resolved(resolved)
- }),
- }
- }
- pub fn evaluate(&self) -> Result<Thunk<Val>> {
- match self {
- Self::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
- Self::Val(val) => Ok(Thunk::evaluated(val.clone())),
- Self::Lazy(lazy) => Ok(lazy.clone()),
- Self::Import(p) => with_state(|s| {
- let resolved = s.resolve_from_default(&p.as_str())?;
- Ok(Thunk!(move || s.import_resolved(resolved)))
- }),
- Self::ImportStr(p) => with_state(|s| {
- let resolved = s.resolve_from_default(&p.as_str())?;
- Ok(Thunk!(move || s
- .import_resolved_str(resolved)
- .map(Val::string)))
- }),
- Self::InlineCode(p) => with_state(|s| {
- let resolved =
- SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
- Ok(Thunk!(move || s.import_resolved(resolved)))
- }),
- }
- }
-}
-
-pub trait ArgsLike {
- fn unnamed_len(&self) -> usize;
- fn unnamed_iter(
- &self,
- ctx: Context,
- tailstrict: bool,
- handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
- ) -> Result<()>;
- fn named_iter(
- &self,
- ctx: Context,
- tailstrict: bool,
- handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
- ) -> Result<()>;
- fn named_names(&self, handler: &mut dyn FnMut(&IStr));
- fn is_empty(&self) -> bool;
-}
-
-impl ArgsLike for Vec<Val> {
- fn unnamed_len(&self) -> usize {
- self.len()
- }
- fn unnamed_iter(
- &self,
- _ctx: Context,
- _tailstrict: bool,
- handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
- ) -> Result<()> {
- for (idx, el) in self.iter().enumerate() {
- handler(idx, Thunk::evaluated(el.clone()))?;
- }
- Ok(())
- }
- fn named_iter(
- &self,
- _ctx: Context,
- _tailstrict: bool,
- _handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
- ) -> Result<()> {
- Ok(())
- }
- fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}
- fn is_empty(&self) -> bool {
- self.is_empty()
- }
-}
-
-impl ArgsLike for ArgsDesc {
- fn unnamed_len(&self) -> usize {
- self.unnamed.len()
- }
-
- fn unnamed_iter(
- &self,
- ctx: Context,
- tailstrict: bool,
- handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
- ) -> Result<()> {
- for (id, arg) in self.unnamed.iter().enumerate() {
- handler(
- id,
- if tailstrict {
- Thunk::evaluated(evaluate(ctx.clone(), arg)?)
- } else {
- let ctx = ctx.clone();
- let arg = arg.clone();
-
- Thunk!(move || evaluate(ctx, &arg))
- },
- )?;
- }
- Ok(())
- }
-
- fn named_iter(
- &self,
- ctx: Context,
- tailstrict: bool,
- handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
- ) -> Result<()> {
- for (name, arg) in &self.named {
- handler(
- name,
- if tailstrict {
- Thunk::evaluated(evaluate(ctx.clone(), arg)?)
- } else {
- let ctx = ctx.clone();
- let arg = arg.clone();
-
- Thunk!(move || evaluate(ctx, &arg))
- },
- )?;
- }
- Ok(())
- }
-
- fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
- for (name, _) in &self.named {
- handler(name);
- }
- }
-
- fn is_empty(&self) -> bool {
- self.unnamed.is_empty() && self.named.is_empty()
- }
-}
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -1,11 +1,10 @@
use std::{fmt::Debug, rc::Rc};
-pub use arglike::{ArgLike, ArgsLike, TlaArg};
use educe::Educe;
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
pub use jrsonnet_macros::builtin;
-use jrsonnet_parser::{Destruct, Expr, ExprParams, Span, Spanned};
+use jrsonnet_parser::{ArgsDesc, Destruct, Expr, ExprParams, Span, Spanned};
use self::{
builtin::{Builtin, StaticBuiltin},
@@ -17,12 +16,12 @@
Result, Thunk, Val,
};
-pub mod arglike;
pub mod builtin;
-pub mod native;
-pub mod parse;
+mod native;
+mod parse;
mod prepared;
+pub use native::NativeFn;
pub use prepared::PreparedFuncVal;
pub use jrsonnet_parser::function::*;
@@ -81,10 +80,10 @@
}
/// Create context, with which body code will run
- pub fn call_body_context(
+ pub(crate) fn call_body_context(
&self,
call_ctx: Context,
- args: &dyn ArgsLike,
+ args: &ArgsDesc,
tailstrict: bool,
) -> Result<Context> {
parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)
@@ -170,7 +169,7 @@
&self,
call_ctx: Context,
loc: CallLocation<'_>,
- args: &dyn ArgsLike,
+ args: &ArgsDesc,
tailstrict: bool,
) -> Result<Val> {
match self {
@@ -179,7 +178,7 @@
evaluate(body_ctx, &func.body)
}
Self::Thunk(thunk) => {
- if !args.is_empty() {
+ if !args.named.is_empty() || !args.unnamed.is_empty() {
bail!(TooManyArgsFunctionHas(0, FunctionSignature::empty()))
}
thunk.evaluate()
crates/jrsonnet-evaluator/src/function/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/native.rs
+++ b/crates/jrsonnet-evaluator/src/function/native.rs
@@ -1,2 +1,68 @@
+use std::marker::PhantomData;
+
+use jrsonnet_gcmodule::Trace;
+
use super::PreparedFuncVal;
-use crate::{typed::Typed, CallLocation, Result, Thunk};
+use crate::{bail, function::FuncVal, typed::Typed, CallLocation, Result, Val};
+use jrsonnet_types::{ComplexValType, ValType};
+
+#[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,
+ {
+ #[allow(non_snake_case, clippy::too_many_arguments)]
+ 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 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_native_desc! {
+ 0; @ A B C D E F G H I J K L
+}
+
+mod native_macro {
+ #[macro_export]
+ macro_rules! NativeFn {
+ (($($t:ty),* $(,)?) -> $res:ty) => {
+ NativeFn<($($t,)* $res)>
+ }
+ }
+}
+pub use crate::NativeFn;
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -1,19 +1,29 @@
+use std::rc::Rc;
+
use jrsonnet_parser::{
function::{FunctionSignature, ParamName},
- ExprParams,
+ ArgsDesc, Expr, ExprParams, Spanned,
};
use rustc_hash::FxHashMap;
-use super::arglike::ArgsLike;
use crate::{
bail,
destructure::destruct,
error::{ErrorKind::*, Result},
- evaluate_named_param,
+ evaluate, evaluate_named_param,
gc::WithCapacityExt as _,
Context, Pending, Thunk, Val,
};
+fn eval_arg(ctx: Context, arg: &Rc<Spanned<Expr>>, tailstrict: bool) -> Result<Thunk<Val>> {
+ if tailstrict {
+ Ok(Thunk::evaluated(evaluate(ctx, arg)?))
+ } else {
+ let arg = arg.clone();
+ Ok(Thunk!(move || evaluate(ctx, &arg)))
+ }
+}
+
/// Creates correct [context](Context) for function body evaluation returning error on invalid call.
///
/// ## Parameters
@@ -22,15 +32,15 @@
/// * `params`: function parameters' definition
/// * `args`: passed function arguments
/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily
-pub fn parse_function_call(
+pub(crate) fn parse_function_call(
ctx: Context,
body_ctx: Context,
params: &ExprParams,
- args: &dyn ArgsLike,
+ args: &ArgsDesc,
tailstrict: bool,
) -> Result<Context> {
let mut passed_args = FxHashMap::with_capacity(params.binds_len());
- if args.unnamed_len() > params.signature.len() {
+ if args.unnamed.len() > params.signature.len() {
bail!(TooManyArgsFunctionHas(
params.signature.len(),
params.signature.clone(),
@@ -40,28 +50,29 @@
let mut filled_named = 0;
let mut filled_positionals = 0;
- args.unnamed_iter(ctx.clone(), tailstrict, &mut |id, arg| {
+ for (id, arg) in args.unnamed.iter().enumerate() {
destruct(
¶ms.exprs[id].destruct,
- arg,
+ eval_arg(ctx.clone(), arg, tailstrict)?,
Pending::new_filled(ctx.clone()),
&mut passed_args,
)?;
filled_positionals += 1;
- Ok(())
- })?;
+ }
- args.named_iter(ctx, tailstrict, &mut |name, value| {
+ for (name, value) in &args.named {
// FIXME: O(n) for arg existence check
if !params.exprs.iter().any(|p| &p.destruct.name() == name) {
bail!(UnknownFunctionParameter(name.clone()));
}
- if passed_args.insert(name.clone(), value).is_some() {
+ if passed_args
+ .insert(name.clone(), eval_arg(ctx.clone(), value, tailstrict)?)
+ .is_some()
+ {
bail!(BindingParameterASecondTime(name.clone()));
}
filled_named += 1;
- Ok(())
- })?;
+ }
if filled_named + filled_positionals < params.len() {
// Some args are unset, but maybe we have defaults for them
@@ -104,13 +115,13 @@
// Some args still weren't filled
if filled_named + filled_positionals != params.len() {
- for param in params.exprs.iter().skip(args.unnamed_len()) {
+ for param in params.exprs.iter().skip(args.unnamed.len()) {
let mut found = false;
- args.named_names(&mut |name| {
+ for (name, _) in &args.named {
if ¶m.destruct.name() == name {
found = true;
}
- });
+ }
if !found {
bail!(FunctionParameterNotBoundInCall(
param.destruct.name(),
@@ -141,34 +152,35 @@
pub fn parse_builtin_call(
ctx: Context,
params: FunctionSignature,
- args: &dyn ArgsLike,
+ args: &ArgsDesc,
tailstrict: bool,
) -> Result<Vec<Option<Thunk<Val>>>> {
let mut passed_args: Vec<Option<Thunk<Val>>> = vec![None; params.len()];
- if args.unnamed_len() > params.len() {
+ if args.unnamed.len() > params.len() {
bail!(TooManyArgsFunctionHas(params.len(), params,))
}
let mut filled_args = 0;
- args.unnamed_iter(ctx.clone(), tailstrict, &mut |id, arg| {
- passed_args[id] = Some(arg);
+ for (id, arg) in args.unnamed.iter().enumerate() {
+ passed_args[id] = Some(eval_arg(ctx.clone(), arg, tailstrict)?);
filled_args += 1;
- Ok(())
- })?;
+ }
- args.named_iter(ctx, tailstrict, &mut |name, arg| {
+ for (name, arg) in &args.named {
// FIXME: O(n) for arg existence check
let id = params
.iter()
.position(|p| p.name() == name)
.ok_or_else(|| UnknownFunctionParameter(name.clone()))?;
- if passed_args[id].replace(arg).is_some() {
+ if passed_args[id]
+ .replace(eval_arg(ctx.clone(), arg, tailstrict)?)
+ .is_some()
+ {
bail!(BindingParameterASecondTime(name.clone()));
}
filled_args += 1;
- Ok(())
- })?;
+ }
if filled_args < params.len() {
for (id, _) in params.iter().enumerate().filter(|(_, p)| p.has_default()) {
@@ -180,13 +192,13 @@
// Some args still wasn't filled
if filled_args != params.len() {
- for param in params.iter().skip(args.unnamed_len()) {
+ for param in params.iter().skip(args.unnamed.len()) {
let mut found = false;
- args.named_names(&mut |name| {
+ for (name, _) in &args.named {
if param.name() == name {
found = true;
}
- });
+ }
if !found {
bail!(FunctionParameterNotBoundInCall(
param.name().clone(),
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -19,7 +19,7 @@
mod obj;
pub mod stack;
pub mod stdlib;
-mod tla;
+pub mod tla;
pub mod trace;
pub mod typed;
pub mod val;
crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/tla.rs
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -1,12 +1,68 @@
use std::{collections::HashMap, hash::BuildHasher};
+use jrsonnet_gcmodule::Trace;
use jrsonnet_interner::IStr;
+use jrsonnet_parser::{SourceFifo, SourcePath};
use crate::{
- function::{CallLocation, PreparedFuncVal, TlaArg},
- in_description_frame, Result, Val,
+ function::{CallLocation, PreparedFuncVal},
+ in_description_frame, with_state, Result, Thunk, Val,
};
+#[derive(Clone, Trace)]
+pub enum TlaArg {
+ String(IStr),
+ Val(Val),
+ Lazy(Thunk<Val>),
+ Import(String),
+ ImportStr(String),
+ InlineCode(String),
+}
+impl TlaArg {
+ pub fn evaluate_tailstrict(&self) -> Result<Val> {
+ match self {
+ Self::String(s) => Ok(Val::string(s.clone())),
+ Self::Val(val) => Ok(val.clone()),
+ Self::Lazy(lazy) => Ok(lazy.evaluate()?),
+ Self::Import(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ s.import_resolved(resolved)
+ }),
+ Self::ImportStr(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ s.import_resolved_str(resolved).map(Val::string)
+ }),
+ Self::InlineCode(p) => with_state(|s| {
+ let resolved =
+ SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
+ s.import_resolved(resolved)
+ }),
+ }
+ }
+ pub fn evaluate(&self) -> Result<Thunk<Val>> {
+ match self {
+ Self::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
+ Self::Val(val) => Ok(Thunk::evaluated(val.clone())),
+ Self::Lazy(lazy) => Ok(lazy.clone()),
+ Self::Import(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ Ok(Thunk!(move || s.import_resolved(resolved)))
+ }),
+ Self::ImportStr(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ Ok(Thunk!(move || s
+ .import_resolved_str(resolved)
+ .map(Val::string)))
+ }),
+ Self::InlineCode(p) => with_state(|s| {
+ let resolved =
+ SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
+ Ok(Thunk!(move || s.import_resolved(resolved)))
+ }),
+ }
+ }
+}
+
pub fn apply_tla<H: BuildHasher>(args: &HashMap<IStr, TlaArg, H>, val: Val) -> Result<Val> {
Ok(if let Val::Func(func) = val {
in_description_frame(
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::{CallLocation, FuncDesc, FuncVal, PreparedFuncVal},
+ function::{FuncDesc, FuncVal},
typed::CheckType,
val::{IndexableVal, NumValue, StrValue, ThunkMapper},
ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
@@ -671,69 +671,9 @@
Ok(None)
} else {
T::from_untyped(untyped).map(Some)
- }
- }
-}
-
-#[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 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_native_desc! {
- 0; @ A B C D E F G H I J K L
}
-
-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
@@ -405,7 +405,7 @@
const _: () = {
use ::jrsonnet_evaluator::{
State, Val,
- function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation, ArgsLike, parse::parse_builtin_call},
+ function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation},
Result, Context, typed::Typed,
parser::Span, params, Thunk,
};
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth1#![allow(non_snake_case)]23use jrsonnet_evaluator::{4 bail,5 function::{builtin, FuncVal},6 runtime_error,7 typed::{BoundedI32, BoundedUsize, Either2, NativeFn, 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, 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}crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -13,7 +13,8 @@
pub use hash::*;
use jrsonnet_evaluator::{
error::Result,
- function::{CallLocation, FuncVal, TlaArg},
+ function::{CallLocation, FuncVal},
+ tla::TlaArg,
trace::PathResolver,
val::NumValue,
ContextBuilder, IStr, ObjValue, ObjValueBuilder, Thunk, Val,
tests/tests/cpp_test_suite.rsdiffbeforeafterboth--- a/tests/tests/cpp_test_suite.rs
+++ b/tests/tests/cpp_test_suite.rs
@@ -6,10 +6,10 @@
use jrsonnet_evaluator::{
FileImportResolver, IStr, ObjValueBuilder, State, Val, apply_tla,
- function::TlaArg,
gc::WithCapacityExt as _,
manifest::JsonFormat,
rustc_hash::FxHashMap,
+ tla::TlaArg,
trace::{CompactFormat, PathResolver, TraceFormat},
};
use jrsonnet_stdlib::ContextInitializer;