difftreelog
refactor prefer builtins over natives
in: master
8 files changed
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -1,11 +1,11 @@
use gcmodule::Cc;
use jrsonnet_evaluator::{
error::{Error, LocError},
+ function::BuiltinParam,
gc::TraceBox,
native::{NativeCallback, NativeCallbackHandler},
EvaluationState, IStr, Val,
};
-use jrsonnet_parser::{Param, ParamsDesc};
use std::{
convert::TryFrom,
ffi::{c_void, CStr},
@@ -28,7 +28,7 @@
cb: JsonnetNativeCallback,
}
impl NativeCallbackHandler for JsonnetNativeCallbackHandler {
- fn call(&self, _from: Rc<Path>, args: &[Val]) -> Result<Val, LocError> {
+ fn call(&self, _from: Option<Rc<Path>>, args: &[Val]) -> Result<Val, LocError> {
let mut n_args = Vec::new();
for a in args {
n_args.push(Some(Box::new(a.clone())));
@@ -68,16 +68,19 @@
break;
}
let param = CStr::from_ptr(*raw_params).to_str().expect("not utf8");
- params.push(Param(param.into(), None));
+ params.push(BuiltinParam {
+ name: param.into(),
+ has_default: false,
+ });
raw_params = raw_params.offset(1);
}
- let params = ParamsDesc(Rc::new(params));
vm.add_native(
name,
- Cc::new(NativeCallback::new(
+ #[allow(deprecated)]
+ Cc::new(TraceBox(Box::new(NativeCallback::new(
params,
TraceBox(Box::new(JsonnetNativeCallbackHandler { ctx, cb })),
- )),
+ )))),
)
}
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -11,7 +11,6 @@
};
use crate::{Either, ObjValue};
use format::{format_arr, format_obj};
-use gcmodule::Cc;
use jrsonnet_interner::IStr;
use jrsonnet_parser::ExprLocation;
use serde::Deserialize;
@@ -142,7 +141,7 @@
}
#[jrsonnet_macros::builtin]
-fn builtin_length(x: Either![IStr, VecVal, ObjValue, Cc<FuncVal>]) -> Result<usize> {
+fn builtin_length(x: Either![IStr, VecVal, ObjValue, FuncVal]) -> Result<usize> {
use Either4::*;
Ok(match x {
A(x) => x.chars().count(),
@@ -162,7 +161,7 @@
}
#[jrsonnet_macros::builtin]
-fn builtin_make_array(sz: usize, func: Cc<FuncVal>) -> Result<VecVal> {
+fn builtin_make_array(sz: usize, func: FuncVal) -> Result<VecVal> {
let mut out = Vec::with_capacity(sz);
for i in 0..sz {
out.push(func.evaluate_simple(&[i as f64].as_slice())?)
@@ -345,24 +344,24 @@
}
#[jrsonnet_macros::builtin]
-fn builtin_native(name: IStr) -> Result<Cc<FuncVal>> {
+fn builtin_native(name: IStr) -> Result<FuncVal> {
Ok(with_state(|s| s.settings().ext_natives.get(&name).cloned())
- .map(|v| Cc::new(FuncVal::NativeExt(name.clone(), v)))
+ .map(|v| FuncVal::Builtin(v.clone()))
.ok_or(UndefinedExternalFunction(name))?)
}
#[jrsonnet_macros::builtin]
-fn builtin_filter(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {
+fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {
arr.filter(|val| bool::try_from(func.evaluate_simple(&[Any(val.clone())].as_slice())?))
}
#[jrsonnet_macros::builtin]
-fn builtin_map(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {
+fn builtin_map(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {
arr.map(|val| func.evaluate_simple(&[Any(val)].as_slice()))
}
#[jrsonnet_macros::builtin]
-fn builtin_flatmap(func: Cc<FuncVal>, arr: IndexableVal) -> Result<IndexableVal> {
+fn builtin_flatmap(func: FuncVal, arr: IndexableVal) -> Result<IndexableVal> {
match arr {
IndexableVal::Str(s) => {
let mut out = String::new();
@@ -397,7 +396,7 @@
}
#[jrsonnet_macros::builtin]
-fn builtin_foldl(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {
+fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {
let mut acc = init.0;
for i in arr.iter() {
acc = func.evaluate_simple(&[Any(acc), Any(i?)].as_slice())?;
@@ -406,7 +405,7 @@
}
#[jrsonnet_macros::builtin]
-fn builtin_foldr(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {
+fn builtin_foldr(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {
let mut acc = init.0;
for i in arr.iter().rev() {
acc = func.evaluate_simple(&[Any(i?), Any(acc)].as_slice())?;
@@ -416,13 +415,13 @@
#[jrsonnet_macros::builtin]
#[allow(non_snake_case)]
-fn builtin_sort(arr: ArrValue, keyF: Option<Cc<FuncVal>>) -> Result<ArrValue> {
+fn builtin_sort(arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
if arr.len() <= 1 {
return Ok(arr);
}
Ok(ArrValue::Eager(sort::sort(
arr.evaluated()?,
- keyF.as_deref(),
+ keyF.as_ref(),
)?))
}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -177,7 +177,7 @@
}
pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {
- Val::Func(Cc::new(FuncVal::Normal(FuncDesc {
+ Val::Func(FuncVal::Normal(Cc::new(FuncDesc {
name,
ctx,
params,
@@ -630,11 +630,11 @@
Function(params, body) => {
evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
}
- Intrinsic(name) => Val::Func(Cc::new(FuncVal::StaticBuiltin(
+ Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(
BUILTINS
.with(|b| b.get(name).copied())
.ok_or_else(|| IntrinsicNotFound(name.clone()))?,
- ))),
+ )),
AssertExpr(assert, returned) => {
evaluate_assert(context.clone(), assert)?;
evaluate(context, returned)?
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -371,7 +371,7 @@
type BuiltinParamName = Cow<'static, str>;
-#[derive(Clone)]
+#[derive(Clone, Trace)]
pub struct BuiltinParam {
pub name: BuiltinParamName,
pub has_default: bool,
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -13,7 +13,7 @@
mod dynamic;
pub mod error;
mod evaluate;
-mod function;
+pub mod function;
mod import;
mod integrations;
mod map;
@@ -27,14 +27,12 @@
pub use dynamic::*;
use error::{Error::*, LocError, Result, StackTraceElement};
pub use evaluate::*;
-pub use function::parse_function_call;
-use function::TlaArg;
+use function::{Builtin, TlaArg};
use gc::{GcHashMap, TraceBox};
use gcmodule::{Cc, Trace};
pub use import::*;
pub use jrsonnet_interner::IStr;
use jrsonnet_parser::*;
-use native::NativeCallback;
pub use obj::*;
use std::{
cell::{Ref, RefCell, RefMut},
@@ -79,7 +77,7 @@
/// Used for s`td.extVar`
pub ext_vars: HashMap<IStr, Val>,
/// Used for ext.native
- pub ext_natives: HashMap<IStr, Cc<NativeCallback>>,
+ pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,
/// TLA vars
pub tla_vars: HashMap<IStr, TlaArg>,
/// Global variables are inserted in default context
@@ -614,7 +612,7 @@
self.settings_mut().import_resolver = resolver;
}
- pub fn add_native(&self, name: IStr, cb: Cc<NativeCallback>) {
+ pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {
self.settings_mut().ext_natives.insert(name, cb);
}
@@ -657,8 +655,8 @@
pub mod tests {
use super::Val;
use crate::{
- error::Error::*, gc::TraceBox, native::NativeCallbackHandler, primitive_equals,
- EvaluationState,
+ error::Error::*, function::BuiltinParam, gc::TraceBox, native::NativeCallbackHandler,
+ primitive_equals, EvaluationState,
};
use gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
@@ -1096,8 +1094,11 @@
#[derive(Trace)]
struct NativeAdd;
impl NativeCallbackHandler for NativeAdd {
- fn call(&self, from: Rc<Path>, args: &[Val]) -> crate::error::Result<Val> {
- assert_eq!(&from as &Path, &PathBuf::from("native_caller.jsonnet"));
+ fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> crate::error::Result<Val> {
+ assert_eq!(
+ &from.unwrap() as &Path,
+ &PathBuf::from("native_caller.jsonnet")
+ );
match (&args[0], &args[1]) {
(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),
(_, _) => unreachable!(),
@@ -1106,13 +1107,20 @@
}
evaluator.settings_mut().ext_natives.insert(
"native_add".into(),
- Cc::new(NativeCallback::new(
- ParamsDesc(Rc::new(vec![
- Param("a".into(), None),
- Param("b".into(), None),
- ])),
+ #[allow(deprecated)]
+ Cc::new(TraceBox(Box::new(NativeCallback::new(
+ vec![
+ BuiltinParam {
+ name: "a".into(),
+ has_default: false,
+ },
+ BuiltinParam {
+ name: "b".into(),
+ has_default: false,
+ },
+ ],
TraceBox(Box::new(NativeAdd)),
- )),
+ )))),
);
evaluator.evaluate_snippet_raw(
PathBuf::from("native_caller.jsonnet").into(),
crates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -1,33 +1,52 @@
#![allow(clippy::type_complexity)]
+use crate::function::{parse_builtin_call, ArgsLike, Builtin, BuiltinParam};
use crate::gc::TraceBox;
+use crate::Context;
use crate::{error::Result, Val};
use gcmodule::Trace;
-use jrsonnet_parser::ParamsDesc;
-use std::fmt::Debug;
+use jrsonnet_parser::ExprLocation;
use std::path::Path;
use std::rc::Rc;
-#[deprecated(note = "Use builtins instead")]
-pub trait NativeCallbackHandler: Trace {
- fn call(&self, from: Rc<Path>, args: &[Val]) -> Result<Val>;
-}
-
#[derive(Trace)]
pub struct NativeCallback {
- pub params: ParamsDesc,
+ pub(crate) params: Vec<BuiltinParam>,
handler: TraceBox<dyn NativeCallbackHandler>,
}
impl NativeCallback {
- pub fn new(params: ParamsDesc, handler: TraceBox<dyn NativeCallbackHandler>) -> Self {
+ #[deprecated = "prefer using builtins directly, use this interface only for bindings"]
+ pub fn new(params: Vec<BuiltinParam>, handler: TraceBox<dyn NativeCallbackHandler>) -> Self {
Self { params, handler }
- }
- pub fn call(&self, caller: Rc<Path>, args: &[Val]) -> Result<Val> {
- self.handler.call(caller, args)
}
}
-impl Debug for NativeCallback {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("NativeCallback").finish()
+
+impl Builtin for NativeCallback {
+ fn name(&self) -> &str {
+ // TODO: standard natives gets their names from definition
+ // But builitins should already have them
+ "<native>"
+ }
+
+ fn params(&self) -> &[BuiltinParam] {
+ &self.params
+ }
+
+ fn call(
+ &self,
+ context: Context,
+ loc: Option<&ExprLocation>,
+ args: &dyn ArgsLike,
+ ) -> Result<Val> {
+ let args = parse_builtin_call(context, &self.params, args, true)?;
+ let mut out_args = Vec::with_capacity(self.params.len());
+ for p in self.params.iter() {
+ out_args.push(args[&p.name].evaluate()?);
+ }
+ self.handler.call(loc.map(|l| l.0.clone()), &out_args)
}
}
+
+pub trait NativeCallbackHandler: Trace {
+ fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> Result<Val>;
+}
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth1use std::convert::{TryFrom, TryInto};23use gcmodule::Cc;4use jrsonnet_interner::IStr;5use jrsonnet_types::{ComplexValType, ValType};67use crate::{8 error::{Error::*, LocError, Result},9 throw,10 typed::CheckType,11 ArrValue, FuncVal, IndexableVal, ObjValue, Val,12};1314pub trait Typed: TryFrom<Val, Error = LocError> + TryInto<Val, Error = LocError> {15 const TYPE: &'static ComplexValType;16}1718macro_rules! impl_int {19 ($($ty:ty)*) => {$(20 impl Typed for $ty {21 const TYPE: &'static ComplexValType =22 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));23 }24 impl TryFrom<Val> for $ty {25 type Error = LocError;2627 fn try_from(value: Val) -> Result<Self> {28 <Self as Typed>::TYPE.check(&value)?;29 match value {30 Val::Num(n) => {31 if n.trunc() != n {32 throw!(RuntimeError(33 format!(34 "cannot convert number with fractional part to {}",35 stringify!($ty)36 )37 .into()38 ))39 }40 Ok(n as Self)41 }42 _ => unreachable!(),43 }44 }45 }46 impl TryFrom<$ty> for Val {47 type Error = LocError;4849 fn try_from(value: $ty) -> Result<Self> {50 Ok(Self::Num(value as f64))51 }52 }53 )*};54}5556impl_int!(i8 u8 i16 u16 i32 u32);5758impl Typed for f64 {59 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);60}61impl TryFrom<Val> for f64 {62 type Error = LocError;6364 fn try_from(value: Val) -> Result<Self> {65 <Self as Typed>::TYPE.check(&value)?;66 match value {67 Val::Num(n) => Ok(n),68 _ => unreachable!(),69 }70 }71}72impl TryFrom<f64> for Val {73 type Error = LocError;7475 fn try_from(value: f64) -> Result<Self> {76 Ok(Self::Num(value))77 }78}7980pub struct PositiveF64(pub f64);81impl Typed for PositiveF64 {82 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);83}84impl TryFrom<Val> for PositiveF64 {85 type Error = LocError;8687 fn try_from(value: Val) -> Result<Self> {88 <Self as Typed>::TYPE.check(&value)?;89 match value {90 Val::Num(n) => Ok(Self(n)),91 _ => unreachable!(),92 }93 }94}95impl TryFrom<PositiveF64> for Val {96 type Error = LocError;9798 fn try_from(value: PositiveF64) -> Result<Self> {99 Ok(Self::Num(value.0))100 }101}102103impl Typed for usize {104 // It is possible to store 54 bits of precision in f64, but leaving u32::MAX here for compatibility105 const TYPE: &'static ComplexValType =106 &ComplexValType::BoundedNumber(Some(0.0), Some(4294967295.0));107}108impl TryFrom<Val> for usize {109 type Error = LocError;110111 fn try_from(value: Val) -> Result<Self> {112 <Self as Typed>::TYPE.check(&value)?;113 match value {114 Val::Num(n) => {115 if n.trunc() != n {116 throw!(RuntimeError(117 "cannot convert number with fractional part to usize".into()118 ))119 }120 Ok(n as Self)121 }122 _ => unreachable!(),123 }124 }125}126impl TryFrom<usize> for Val {127 type Error = LocError;128129 fn try_from(value: usize) -> Result<Self> {130 if value > u32::MAX as usize {131 throw!(RuntimeError("number is too large".into()))132 }133 Ok(Self::Num(value as f64))134 }135}136137impl Typed for IStr {138 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);139}140impl TryFrom<Val> for IStr {141 type Error = LocError;142143 fn try_from(value: Val) -> Result<Self> {144 <Self as Typed>::TYPE.check(&value)?;145 match value {146 Val::Str(s) => Ok(s),147 _ => unreachable!(),148 }149 }150}151impl TryFrom<IStr> for Val {152 type Error = LocError;153154 fn try_from(value: IStr) -> Result<Self> {155 Ok(Self::Str(value))156 }157}158159impl Typed for String {160 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);161}162impl TryFrom<Val> for String {163 type Error = LocError;164165 fn try_from(value: Val) -> Result<Self> {166 <Self as Typed>::TYPE.check(&value)?;167 match value {168 Val::Str(s) => Ok(s.to_string()),169 _ => unreachable!(),170 }171 }172}173impl TryFrom<String> for Val {174 type Error = LocError;175176 fn try_from(value: String) -> Result<Self> {177 Ok(Self::Str(value.into()))178 }179}180181impl Typed for char {182 const TYPE: &'static ComplexValType = &ComplexValType::Char;183}184impl TryFrom<Val> for char {185 type Error = LocError;186187 fn try_from(value: Val) -> Result<Self> {188 <Self as Typed>::TYPE.check(&value)?;189 match value {190 Val::Str(s) => Ok(s.chars().next().unwrap()),191 _ => unreachable!(),192 }193 }194}195impl TryFrom<char> for Val {196 type Error = LocError;197198 fn try_from(value: char) -> Result<Self> {199 Ok(Self::Str(value.to_string().into()))200 }201}202203impl<T> Typed for Vec<T>204where205 T: Typed,206 T: TryFrom<Val, Error = LocError>,207 T: TryInto<Val, Error = LocError>,208{209 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);210}211impl<T> TryFrom<Val> for Vec<T>212where213 T: Typed,214 T: TryFrom<Val, Error = LocError>,215 T: TryInto<Val, Error = LocError>,216{217 type Error = LocError;218219 fn try_from(value: Val) -> Result<Self> {220 <Self as Typed>::TYPE.check(&value)?;221 match value {222 Val::Arr(a) => {223 let mut o = Self::with_capacity(a.len());224 for i in a.iter() {225 o.push(T::try_from(i?)?);226 }227 Ok(o)228 }229 _ => unreachable!(),230 }231 }232}233impl<T> TryFrom<Vec<T>> for Val234where235 T: Typed,236 T: TryFrom<Self, Error = LocError>,237 T: TryInto<Self, Error = LocError>,238{239 type Error = LocError;240241 fn try_from(value: Vec<T>) -> Result<Self> {242 let mut o = Vec::with_capacity(value.len());243 for i in value {244 o.push(i.try_into()?);245 }246 Ok(Self::Arr(o.into()))247 }248}249250/// To be used in Vec<Any>251/// Regular Val can't be used here, because it has wrong TryFrom::Error type252#[derive(Clone)]253pub struct Any(pub Val);254255impl Typed for Any {256 const TYPE: &'static ComplexValType = &ComplexValType::Any;257}258impl TryFrom<Val> for Any {259 type Error = LocError;260261 fn try_from(value: Val) -> Result<Self> {262 Ok(Self(value))263 }264}265impl TryFrom<Any> for Val {266 type Error = LocError;267268 fn try_from(value: Any) -> Result<Self> {269 Ok(value.0)270 }271}272273/// Specialization, provides faster TryFrom<VecVal> for Val274pub struct VecVal(pub Vec<Val>);275276impl Typed for VecVal {277 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);278}279impl TryFrom<Val> for VecVal {280 type Error = LocError;281282 fn try_from(value: Val) -> Result<Self> {283 <Self as Typed>::TYPE.check(&value)?;284 match value {285 Val::Arr(a) => Ok(Self(a.evaluated()?.to_vec())),286 _ => unreachable!(),287 }288 }289}290impl TryFrom<VecVal> for Val {291 type Error = LocError;292293 fn try_from(value: VecVal) -> Result<Self> {294 Ok(Self::Arr(value.0.into()))295 }296}297298pub struct M1;299impl Typed for M1 {300 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));301}302impl TryFrom<Val> for M1 {303 type Error = LocError;304305 fn try_from(value: Val) -> Result<Self> {306 <Self as Typed>::TYPE.check(&value)?;307 Ok(Self)308 }309}310impl TryFrom<M1> for Val {311 type Error = LocError;312313 fn try_from(_: M1) -> Result<Self> {314 Ok(Self::Num(-1.0))315 }316}317318macro_rules! decl_either {319 ($($name: ident, $($id: ident)*);*) => {$(320 pub enum $name<$($id),*> {321 $($id($id)),*322 }323 impl<$($id),*> Typed for $name<$($id),*>324 where325 $($id: Typed,)*326 {327 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);328 }329 impl<$($id),*> TryFrom<Val> for $name<$($id),*>330 where331 $($id: Typed,)*332 {333 type Error = LocError;334335 fn try_from(value: Val) -> Result<Self> {336 $(337 if $id::TYPE.check(&value).is_ok() {338 $id::try_from(value).map(Self::$id)339 } else340 )* {341 <Self as Typed>::TYPE.check(&value)?;342 unreachable!()343 }344 }345 }346 impl<$($id),*> TryFrom<$name<$($id),*>> for Val347 where348 $($id: Typed,)*349 {350 type Error = LocError;351 fn try_from(value: $name<$($id),*>) -> Result<Self> {352 match value {$(353 $name::$id(v) => v.try_into()354 ),*}355 }356 }357 )*}358}359decl_either!(360 Either1, A;361 Either2, A B;362 Either3, A B C;363 Either4, A B C D;364 Either5, A B C D E;365 Either6, A B C D E F;366 Either7, A B C D E F G367);368#[macro_export]369macro_rules! Either {370 ($a:ty) => {Either1<$a>};371 ($a:ty, $b:ty) => {Either2<$a, $b>};372 ($a:ty, $b:ty, $c:ty) => {Either3<$a, $b, $c>};373 ($a:ty, $b:ty, $c:ty, $d:ty) => {Either4<$a, $b, $c, $d>};374 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {Either5<$a, $b, $c, $d, $e>};375 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {Either6<$a, $b, $c, $d, $e, $f>};376 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {Either7<$a, $b, $c, $d, $e, $f, $g>};377}378379pub type MyType = Either![u32, f64, String];380381impl Typed for ArrValue {382 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);383}384impl TryFrom<Val> for ArrValue {385 type Error = LocError;386387 fn try_from(value: Val) -> Result<Self> {388 <Self as Typed>::TYPE.check(&value)?;389 match value {390 Val::Arr(a) => Ok(a),391 _ => unreachable!(),392 }393 }394}395impl TryFrom<ArrValue> for Val {396 type Error = LocError;397398 fn try_from(value: ArrValue) -> Result<Self> {399 Ok(Self::Arr(value))400 }401}402403impl Typed for Cc<FuncVal> {404 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);405}406impl TryFrom<Val> for Cc<FuncVal> {407 type Error = LocError;408409 fn try_from(value: Val) -> Result<Self> {410 <Self as Typed>::TYPE.check(&value)?;411 match value {412 Val::Func(a) => Ok(a),413 _ => unreachable!(),414 }415 }416}417impl TryFrom<Cc<FuncVal>> for Val {418 type Error = LocError;419420 fn try_from(value: Cc<FuncVal>) -> Result<Self> {421 Ok(Self::Func(value))422 }423}424impl Typed for ObjValue {425 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);426}427impl TryFrom<Val> for ObjValue {428 type Error = LocError;429430 fn try_from(value: Val) -> Result<Self> {431 <Self as Typed>::TYPE.check(&value)?;432 match value {433 Val::Obj(a) => Ok(a),434 _ => unreachable!(),435 }436 }437}438impl TryFrom<ObjValue> for Val {439 type Error = LocError;440441 fn try_from(value: ObjValue) -> Result<Self> {442 Ok(Self::Obj(value))443 }444}445446impl Typed for bool {447 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);448}449impl TryFrom<Val> for bool {450 type Error = LocError;451452 fn try_from(value: Val) -> Result<Self> {453 <Self as Typed>::TYPE.check(&value)?;454 match value {455 Val::Bool(a) => Ok(a),456 _ => unreachable!(),457 }458 }459}460impl TryFrom<bool> for Val {461 type Error = LocError;462463 fn try_from(value: bool) -> Result<Self> {464 Ok(Self::Bool(value))465 }466}467468impl Typed for IndexableVal {469 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[470 &ComplexValType::Simple(ValType::Arr),471 &ComplexValType::Simple(ValType::Str),472 ]);473}474impl TryFrom<Val> for IndexableVal {475 type Error = LocError;476477 fn try_from(value: Val) -> Result<Self> {478 <Self as Typed>::TYPE.check(&value)?;479 value.into_indexable()480 }481}482impl TryFrom<IndexableVal> for Val {483 type Error = LocError;484485 fn try_from(value: IndexableVal) -> Result<Self> {486 match value {487 IndexableVal::Str(s) => Ok(Self::Str(s)),488 IndexableVal::Arr(a) => Ok(Self::Arr(a)),489 }490 }491}492493pub struct Null;494impl Typed for Null {495 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);496}497impl TryFrom<Val> for Null {498 type Error = LocError;499500 fn try_from(value: Val) -> Result<Self> {501 <Self as Typed>::TYPE.check(&value)?;502 Ok(Self)503 }504}505impl TryFrom<Null> for Val {506 type Error = LocError;507508 fn try_from(_: Null) -> Result<Self> {509 Ok(Self::Null)510 }511}crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -7,7 +7,6 @@
evaluate,
function::{parse_function_call, ArgsLike, Builtin, StaticBuiltin},
gc::TraceBox,
- native::NativeCallback,
throw, Context, ObjValue, Result,
};
use gcmodule::{Cc, Trace};
@@ -86,16 +85,14 @@
pub body: LocExpr,
}
-#[derive(Trace)]
+#[derive(Trace, Clone)]
pub enum FuncVal {
/// Plain function implemented in jsonnet
- Normal(FuncDesc),
+ Normal(Cc<FuncDesc>),
/// Standard library function
StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),
- Builtin(TraceBox<dyn Builtin>),
- /// Library functions implemented in native
- NativeExt(IStr, Cc<NativeCallback>),
+ Builtin(Cc<TraceBox<dyn Builtin>>),
}
impl Debug for FuncVal {
@@ -104,9 +101,6 @@
Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),
Self::StaticBuiltin(arg0) => f.debug_tuple("Intrinsic").field(&arg0.name()).finish(),
Self::Builtin(arg0) => f.debug_tuple("Intrinsic").field(&arg0.name()).finish(),
- Self::NativeExt(arg0, arg1) => {
- f.debug_tuple("NativeExt").field(arg0).field(arg1).finish()
- }
}
}
}
@@ -116,7 +110,6 @@
match (self, other) {
(Self::Normal(a), Self::Normal(b)) => a == b,
(Self::StaticBuiltin(an), Self::StaticBuiltin(bn)) => std::ptr::eq(*an, *bn),
- (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,
(..) => false,
}
}
@@ -127,7 +120,6 @@
Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),
Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),
Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),
- Self::NativeExt(_, n) => n.params.iter().filter(|p| p.1.is_none()).count(),
}
}
pub fn name(&self) -> IStr {
@@ -135,7 +127,6 @@
Self::Normal(normal) => normal.name.clone(),
Self::StaticBuiltin(builtin) => builtin.name().into(),
Self::Builtin(builtin) => builtin.name().into(),
- Self::NativeExt(n, _) => format!("native.{}", n).into(),
}
}
pub fn evaluate(
@@ -158,15 +149,6 @@
}
Self::StaticBuiltin(name) => name.call(call_ctx, loc, args),
Self::Builtin(b) => b.call(call_ctx, loc, args),
- Self::NativeExt(_name, handler) => {
- let args =
- parse_function_call(call_ctx, Context::new(), &handler.params, args, true)?;
- let mut out_args = Vec::with_capacity(handler.params.len());
- for p in handler.params.0.iter() {
- out_args.push(args.binding(p.0.clone())?.evaluate()?);
- }
- Ok(handler.call(loc.expect("todo").0.clone(), &out_args)?)
- }
}
}
pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {
@@ -352,7 +334,7 @@
Num(f64),
Arr(ArrValue),
Obj(ObjValue),
- Func(Cc<FuncVal>),
+ Func(FuncVal),
}
impl Val {