difftreelog
refactor reduce boilerplate by automatic conversions
in: master
29 files changed
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -69,10 +69,7 @@
ctx: *const c_void,
mut raw_params: *const *const c_char,
) {
- let name = CStr::from_ptr(name)
- .to_str()
- .expect("name is not utf-8")
- .into();
+ let name = CStr::from_ptr(name).to_str().expect("name is not utf-8");
let mut params = Vec::new();
loop {
if (*raw_params).is_null() {
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -5,10 +5,7 @@
os::raw::{c_char, c_double, c_int},
};
-use jrsonnet_evaluator::{
- val::{ArrValue, StrValue},
- ObjValue, Val,
-};
+use jrsonnet_evaluator::{val::ArrValue, ObjValue, Val};
use crate::VM;
@@ -21,7 +18,7 @@
pub unsafe extern "C" fn jsonnet_json_make_string(_vm: &VM, val: *const c_char) -> *mut Val {
let val = CStr::from_ptr(val);
let val = val.to_str().expect("string is not utf-8");
- Box::into_raw(Box::new(Val::Str(StrValue::Flat(val.into()))))
+ Box::into_raw(Box::new(Val::string(val)))
}
/// Convert the given double to a `JsonnetJsonValue`.
bindings/jsonnet/src/val_modify.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -5,7 +5,6 @@
use std::{ffi::CStr, os::raw::c_char};
use jrsonnet_evaluator::{val::ArrValue, Thunk, Val};
-use jrsonnet_gcmodule::Cc;
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,7 @@
use std::{fs::read_to_string, str::FromStr};
use clap::Parser;
-use jrsonnet_evaluator::{error::Result, trace::PathResolver, State};
+use jrsonnet_evaluator::{trace::PathResolver, Result, State};
use jrsonnet_stdlib::ContextInitializer;
#[derive(Clone)]
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -6,12 +6,8 @@
use super::ArrValue;
use crate::{
- error::ErrorKind::InfiniteRecursionDetected,
- evaluate,
- function::FuncVal,
- typed::Typed,
- val::{StrValue, ThunkValue},
- Context, Error, ObjValue, Result, Thunk, Val,
+ error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, typed::Typed,
+ val::ThunkValue, Context, Error, ObjValue, Result, Thunk, Val,
};
pub trait ArrayLike: Any + Trace + Debug {
@@ -101,9 +97,7 @@
}
fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0
- .get(index)
- .map(|v| Val::Str(StrValue::Flat(IStr::from(*v))))
+ self.0.get(index).map(|v| Val::string(*v))
}
fn is_cheap(&self) -> bool {
true
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -87,9 +87,9 @@
}
#[must_use]
- pub fn with_var(self, name: IStr, value: Val) -> Self {
+ pub fn with_var(self, name: impl Into<IStr>, value: Val) -> Self {
let mut new_bindings = GcHashMap::with_capacity(1);
- new_bindings.insert(name, Thunk::evaluated(value));
+ new_bindings.insert(name.into(), Thunk::evaluated(value));
self.extend(new_bindings, None, None, None)
}
@@ -161,8 +161,8 @@
}
/// # Panics
/// If `name` is already bound
- pub fn bind(&mut self, name: IStr, value: Thunk<Val>) -> &mut Self {
- let old = self.bindings.insert(name, value);
+ pub fn bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) -> &mut Self {
+ let old = self.bindings.insert(name.into(), value);
assert!(old.is_none(), "variable bound twice in single context call");
self
}
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -52,9 +52,3 @@
Self::new()
}
}
-
-impl<T: Trace + Clone> From<Pending<T>> for Thunk<T> {
- fn from(value: Pending<T>) -> Self {
- Self::new(value)
- }
-}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -36,7 +36,7 @@
}
}
Some(match &*expr.0 {
- Expr::Str(s) => Val::Str(StrValue::Flat(s.clone())),
+ Expr::Str(s) => Val::string(s.clone()),
Expr::Num(n) => Val::Num(*n),
Expr::Literal(LiteralType::False) => Val::Bool(false),
Expr::Literal(LiteralType::True) => Val::Bool(true),
@@ -135,7 +135,7 @@
let fctx = Pending::new();
let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());
let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![
- Thunk::evaluated(Val::Str(StrValue::Flat(field.clone()))),
+ Thunk::evaluated(Val::string(field.clone())),
Thunk::new(ObjectFieldThunk {
field: field.clone(),
obj: obj.clone(),
@@ -226,7 +226,7 @@
}
builder
- .member(name.clone())
+ .field(name.clone())
.with_add(*plus)
.with_visibility(*visibility)
.with_location(value.1.clone())
@@ -262,7 +262,7 @@
}
builder
- .member(name.clone())
+ .field(name.clone())
.with_visibility(*visibility)
.with_location(value.1.clone())
.bindable(UnboundMethod {
@@ -437,7 +437,7 @@
Literal(LiteralType::False) => Val::Bool(false),
Literal(LiteralType::Null) => Val::Null,
Parened(e) => evaluate(ctx, e)?,
- Str(v) => Val::Str(StrValue::Flat(v.clone())),
+ Str(v) => Val::string(v.clone()),
Num(v) => Val::new_checked_num(*v)?,
BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
@@ -672,7 +672,7 @@
|| format!("import {:?}", path.clone()),
|| s.import_resolved(resolved_path),
)?,
- ImportStr(_) => Val::Str(StrValue::Flat(s.import_resolved_str(resolved_path)?)),
+ ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),
ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),
_ => unreachable!(),
}
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -30,18 +30,12 @@
Ok(match (a, b) {
(Str(v1), Str(v2)) => Str(StrValue::concat(v1.clone(), v2.clone())),
- (Num(a), Str(b)) => Str(StrValue::Flat(format!("{a}{b}").into())),
- (Str(a), Num(b)) => Str(StrValue::Flat(format!("{a}{b}").into())),
+ (Num(a), Str(b)) => Val::string(format!("{a}{b}")),
+ (Str(a), Num(b)) => Val::string(format!("{a}{b}")),
- (Str(a), o) | (o, Str(a)) if a.is_empty() => {
- Val::Str(StrValue::Flat(o.clone().to_string()?))
- }
- (Str(a), o) => Str(StrValue::Flat(
- format!("{a}{}", o.clone().to_string()?).into(),
- )),
- (o, Str(a)) => Str(StrValue::Flat(
- format!("{}{a}", o.clone().to_string()?).into(),
- )),
+ (Str(a), o) | (o, Str(a)) if a.is_empty() => Val::string(o.clone().to_string()?),
+ (Str(a), o) => Val::string(format!("{a}{}", o.clone().to_string()?)),
+ (o, Str(a)) => Val::string(format!("{}{a}", o.clone().to_string()?)),
(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
(Arr(a), Arr(b)) => Val::Arr(ArrValue::extended(a.clone(), b.clone())),
@@ -149,7 +143,7 @@
(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone().into_flat(), true)),
(a, Mod, b) => evaluate_mod_op(a, b)?,
- (Str(v1), Mul, Num(v2)) => Str(StrValue::Flat(v1.to_string().repeat(*v2 as usize).into())),
+ (Str(v1), Mul, Num(v2)) => Val::string(v1.to_string().repeat(*v2 as usize)),
// Bool X Bool
(Bool(a), And, Bool(b)) => Bool(*a && *b),
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -61,7 +61,7 @@
impl ArgLike for TlaArg {
fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
match self {
- TlaArg::String(s) => Ok(Thunk::evaluated(Val::Str(StrValue::Flat(s.clone())))),
+ TlaArg::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
TlaArg::Code(code) => Ok(if tailstrict {
Thunk::evaluated(evaluate(ctx, code)?)
} else {
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -12,7 +12,10 @@
native::NativeDesc,
parse::{parse_default_function_call, parse_function_call},
};
-use crate::{evaluate, evaluate_trivial, gc::TraceBox, tb, Context, ContextBuilder, Result, Val};
+use crate::{
+ evaluate, evaluate_trivial, gc::TraceBox, tb, Context, ContextBuilder, Result,
+ Val,
+};
pub mod arglike;
pub mod builtin;
@@ -124,6 +127,9 @@
pub fn builtin(builtin: impl Builtin) -> Self {
Self::Builtin(Cc::new(tb!(builtin)))
}
+ pub fn static_builtin(static_builtin: &'static dyn StaticBuiltin) -> Self {
+ Self::StaticBuiltin(static_builtin)
+ }
pub fn params(&self) -> Vec<BuiltinParam> {
match self {
@@ -239,3 +245,17 @@
}
}
}
+
+impl<T> From<T> for FuncVal
+where
+ T: Builtin,
+{
+ fn from(value: T) -> Self {
+ Self::builtin(value)
+ }
+}
+impl From<&'static dyn StaticBuiltin> for FuncVal {
+ fn from(value: &'static dyn StaticBuiltin) -> Self {
+ Self::static_builtin(value)
+ }
+}
crates/jrsonnet-evaluator/src/function/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/native.rs
+++ b/crates/jrsonnet-evaluator/src/function/native.rs
@@ -2,7 +2,7 @@
arglike::{ArgLike, OptionalContext},
FuncVal,
};
-use crate::{error::Result, typed::Typed};
+use crate::{typed::Typed, Result};
pub trait NativeDesc {
type Value;
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -117,9 +117,7 @@
}
#[derive(Debug)]
-pub struct GcHashMap<K, V>(
- pub HashMap<K, V, BuildHasherDefault<FxHasher>>
-);
+pub struct GcHashMap<K, V>(pub HashMap<K, V, BuildHasherDefault<FxHasher>>);
impl<K, V> GcHashMap<K, V> {
pub fn new() -> Self {
Self(HashMap::default())
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth1use std::borrow::Cow;23use jrsonnet_interner::IStr;4use serde::{5 de::Visitor,6 ser::{7 Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,8 SerializeTupleStruct, SerializeTupleVariant,9 },10 Deserialize, Serialize, Serializer,11};1213use crate::{14 arr::ArrValue,15 error::{Error as JrError, ErrorKind, Result},16 val::StrValue,17 ObjValue, ObjValueBuilder, State, Val,18};1920impl<'de> Deserialize<'de> for Val {21 fn deserialize<D>(deserializer: D) -> Result<Val, D::Error>22 where23 D: serde::Deserializer<'de>,24 {25 struct ValVisitor;2627 // macro_rules! visit_num {28 // ($($method:ident => $ty:ty),* $(,)?) => {$(29 // fn $method<E>(self, v: $ty) -> Result<Self::Value, E>30 // where31 // E: serde::de::Error,32 // {33 // Ok(Val::Num(f64::from(v)))34 // }35 // )*};36 // }3738 impl<'de> Visitor<'de> for ValVisitor {39 type Value = Val;4041 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>42 where43 E: serde::de::Error,44 {45 Ok(Val::Bool(v))46 }47 fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>48 where49 E: serde::de::Error,50 {51 if !v.is_finite() {52 return Err(E::custom("only finite numbers are supported"));53 }54 Ok(Val::Num(v))55 }56 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>57 where58 E: serde::de::Error,59 {60 Ok(Val::Str(StrValue::Flat(v.into())))61 }6263 // visit_num! {64 // visit_i8 => i8,65 // visit_i16 => i16,66 // visit_i32 => i32,67 // visit_u8 => u8,68 // visit_u16 => u16,69 // visit_u32 => u32,70 // }71 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>72 where73 E: serde::de::Error,74 {75 Ok(Val::Num(v as f64))76 }77 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>78 where79 E: serde::de::Error,80 {81 Ok(Val::Num(v as f64))82 }8384 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>85 where86 E: serde::de::Error,87 {88 Ok(Val::Arr(ArrValue::bytes(v.into())))89 }9091 fn visit_none<E>(self) -> Result<Self::Value, E>92 where93 E: serde::de::Error,94 {95 Ok(Val::Null)96 }97 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>98 where99 D: serde::Deserializer<'de>,100 {101 deserializer.deserialize_any(self)102 }103104 fn visit_unit<E>(self) -> Result<Self::Value, E>105 where106 E: serde::de::Error,107 {108 Ok(Val::Null)109 }110111 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>112 where113 D: serde::Deserializer<'de>,114 {115 deserializer.deserialize_any(self)116 }117118 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>119 where120 A: serde::de::SeqAccess<'de>,121 {122 let mut out = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);123124 while let Some(val) = seq.next_element::<Val>()? {125 out.push(val);126 }127128 Ok(Val::Arr(ArrValue::eager(out)))129 }130131 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>132 where133 A: serde::de::MapAccess<'de>,134 {135 let mut out = map136 .size_hint()137 .map_or_else(ObjValueBuilder::new, ObjValueBuilder::with_capacity);138139 while let Some((k, v)) = map.next_entry::<Cow<'de, str>, Val>()? {140 // Jsonnet ignores duplicate keys141 out.member(k.into()).value_unchecked(v);142 }143144 Ok(Val::Obj(out.build()))145 }146147 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {148 write!(formatter, "any valid jsonnet value")149 }150 }151 deserializer.deserialize_any(ValVisitor)152 }153}154155impl Serialize for Val {156 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>157 where158 S: serde::Serializer,159 {160 match self {161 Val::Bool(v) => serializer.serialize_bool(*v),162 Val::Null => serializer.serialize_none(),163 Val::Str(s) => serializer.serialize_str(&s.clone().into_flat()),164 Val::Num(n) => {165 if n.fract() != 0.0 {166 serializer.serialize_f64(*n)167 } else {168 let n = *n as i64;169 serializer.serialize_i64(n)170 }171 }172 #[cfg(feature = "exp-bigint")]173 Val::BigInt(b) => b.serialize(serializer),174 Val::Arr(arr) => {175 let mut seq = serializer.serialize_seq(Some(arr.len()))?;176 for (i, element) in arr.iter().enumerate() {177 let mut serde_error = None;178 // TODO: rewrite using try{} after stabilization179 State::push_description(180 || format!("array index [{i}]"),181 || {182 let e = element?;183 if let Err(e) = seq.serialize_element(&e) {184 serde_error = Some(e);185 }186 Ok(())187 },188 )189 .map_err(|e| S::Error::custom(e.to_string()))?;190 if let Some(e) = serde_error {191 return Err(e);192 }193 }194 seq.end()195 }196 Val::Obj(obj) => {197 let mut map = serializer.serialize_map(Some(obj.len()))?;198 for (field, value) in obj.iter(199 #[cfg(feature = "exp-preserve-order")]200 true,201 ) {202 let mut serde_error = None;203 // TODO: rewrite using try{} after stabilization204 State::push_description(205 || format!("object field {field:?}"),206 || {207 let v = value?;208 if let Err(e) = map.serialize_entry(field.as_str(), &v) {209 serde_error = Some(e);210 }211 Ok(())212 },213 )214 .map_err(|e| S::Error::custom(e.to_string()))?;215 if let Some(e) = serde_error {216 return Err(e);217 }218 }219 map.end()220 }221 Val::Func(_) => Err(S::Error::custom("tried to manifest function")),222 }223 }224}225226struct IntoVecValSerializer {227 variant: Option<IStr>,228 data: Vec<Val>,229}230impl IntoVecValSerializer {231 fn new() -> Self {232 Self {233 variant: None,234 data: Vec::new(),235 }236 }237 fn with_capacity(capacity: usize) -> Self {238 Self {239 variant: None,240 data: Vec::with_capacity(capacity),241 }242 }243 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {244 Self {245 variant: Some(variant.into()),246 data: Vec::with_capacity(capacity),247 }248 }249}250impl SerializeSeq for IntoVecValSerializer {251 type Ok = Val;252 type Error = JrError;253254 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>255 where256 T: Serialize,257 {258 let value = value.serialize(IntoValSerializer)?;259 self.data.push(value);260 Ok(())261 }262263 fn end(self) -> Result<Val> {264 let inner = Val::Arr(ArrValue::eager(self.data));265 if let Some(variant) = self.variant {266 let mut out = ObjValue::builder_with_capacity(1);267 out.member(variant).value_unchecked(inner);268 Ok(Val::Obj(out.build()))269 } else {270 Ok(inner)271 }272 }273}274impl SerializeTuple for IntoVecValSerializer {275 type Ok = Val;276 type Error = JrError;277278 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>279 where280 T: Serialize,281 {282 SerializeSeq::serialize_element(self, value)283 }284285 fn end(self) -> Result<Val> {286 SerializeSeq::end(self)287 }288}289impl SerializeTupleVariant for IntoVecValSerializer {290 type Ok = Val;291 type Error = JrError;292293 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>294 where295 T: Serialize,296 {297 SerializeSeq::serialize_element(self, value)298 }299300 fn end(self) -> Result<Val> {301 SerializeSeq::end(self)302 }303}304impl SerializeTupleStruct for IntoVecValSerializer {305 type Ok = Val;306 type Error = JrError;307308 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>309 where310 T: Serialize,311 {312 SerializeSeq::serialize_element(self, value)313 }314315 fn end(self) -> Result<Val> {316 SerializeSeq::end(self)317 }318}319320struct IntoObjValueSerializer {321 variant: Option<IStr>,322 data: ObjValueBuilder,323 key: Option<IStr>,324}325impl IntoObjValueSerializer {326 fn new() -> Self {327 Self {328 variant: None,329 data: ObjValue::builder(),330 key: None,331 }332 }333 fn with_capacity(capacity: usize) -> Self {334 Self {335 variant: None,336 data: ObjValue::builder_with_capacity(capacity),337 key: None,338 }339 }340 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {341 Self {342 variant: Some(variant.into()),343 data: ObjValue::builder_with_capacity(capacity),344 key: None,345 }346 }347}348impl SerializeMap for IntoObjValueSerializer {349 type Ok = Val;350 type Error = JrError;351352 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()>353 where354 T: Serialize,355 {356 let key = key.serialize(IntoValSerializer)?;357 let key = key.to_string()?;358 self.key = Some(key);359 Ok(())360 }361362 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()>363 where364 T: Serialize,365 {366 let key = self.key.take().expect("no serialize_key called");367 let value = value.serialize(IntoValSerializer)?;368 self.data.member(key).value(value)?;369 Ok(())370 }371372 // TODO: serialize_key/serialize_value373 fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<()>374 where375 K: Serialize,376 V: Serialize,377 {378 let key = key.serialize(IntoValSerializer)?;379 let key = key.to_string()?;380 let value = value.serialize(IntoValSerializer)?;381 self.data.member(key).value(value)?;382 Ok(())383 }384385 fn end(self) -> Result<Val> {386 let inner = Val::Obj(self.data.build());387 if let Some(variant) = self.variant {388 let mut out = ObjValue::builder_with_capacity(1);389 out.member(variant).value_unchecked(inner);390 Ok(Val::Obj(out.build()))391 } else {392 Ok(inner)393 }394 }395}396impl SerializeStruct for IntoObjValueSerializer {397 type Ok = Val;398 type Error = JrError;399400 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>401 where402 T: Serialize,403 {404 SerializeMap::serialize_entry(self, key, value)?;405 Ok(())406 }407408 fn end(self) -> Result<Val> {409 SerializeMap::end(self)410 }411}412impl SerializeStructVariant for IntoObjValueSerializer {413 type Ok = Val;414415 type Error = JrError;416417 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>418 where419 T: Serialize,420 {421 SerializeMap::serialize_entry(self, key, value)?;422 Ok(())423 }424425 fn end(self) -> Result<Val> {426 SerializeMap::end(self)427 }428}429430struct IntoValSerializer;431impl Serializer for IntoValSerializer {432 type Ok = Val;433434 type Error = JrError;435436 type SerializeSeq = IntoVecValSerializer;437438 type SerializeTuple = IntoVecValSerializer;439440 type SerializeTupleStruct = IntoVecValSerializer;441442 type SerializeTupleVariant = IntoVecValSerializer;443444 type SerializeMap = IntoObjValueSerializer;445446 type SerializeStruct = IntoObjValueSerializer;447448 type SerializeStructVariant = IntoObjValueSerializer;449450 fn serialize_bool(self, v: bool) -> Result<Val> {451 Ok(Val::Bool(v))452 }453454 fn serialize_i8(self, v: i8) -> Result<Val> {455 Ok(Val::Num(f64::from(v)))456 }457458 fn serialize_i16(self, v: i16) -> Result<Val> {459 Ok(Val::Num(f64::from(v)))460 }461462 fn serialize_i32(self, v: i32) -> Result<Val> {463 Ok(Val::Num(f64::from(v)))464 }465466 fn serialize_i64(self, v: i64) -> Result<Val> {467 Ok(Val::Str(v.to_string().into()))468 }469470 fn serialize_u8(self, v: u8) -> Result<Val> {471 Ok(Val::Num(f64::from(v)))472 }473474 fn serialize_u16(self, v: u16) -> Result<Val> {475 Ok(Val::Num(f64::from(v)))476 }477478 fn serialize_u32(self, v: u32) -> Result<Val> {479 Ok(Val::Num(f64::from(v)))480 }481482 fn serialize_u64(self, v: u64) -> Result<Val> {483 Ok(Val::Str(v.to_string().into()))484 }485486 fn serialize_f32(self, v: f32) -> Result<Val> {487 Ok(Val::Num(f64::from(v)))488 }489490 fn serialize_f64(self, v: f64) -> Result<Val> {491 Ok(Val::Num(v))492 }493494 fn serialize_char(self, v: char) -> Result<Val> {495 Ok(Val::Str(v.to_string().into()))496 }497498 fn serialize_str(self, v: &str) -> Result<Val> {499 Ok(Val::Str(v.into()))500 }501502 fn serialize_bytes(self, v: &[u8]) -> Result<Val> {503 Ok(Val::Arr(ArrValue::bytes(v.into())))504 }505506 fn serialize_none(self) -> Result<Val> {507 Ok(Val::Null)508 }509510 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Val>511 where512 T: Serialize,513 {514 value.serialize(self)515 }516517 fn serialize_unit(self) -> Result<Val> {518 Ok(Val::Null)519 }520521 fn serialize_unit_struct(self, _name: &'static str) -> Result<Val> {522 Ok(Val::Null)523 }524525 fn serialize_unit_variant(526 self,527 _name: &'static str,528 _variant_index: u32,529 variant: &'static str,530 ) -> Result<Val> {531 Ok(Val::Str(variant.into()))532 }533534 fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<Val>535 where536 T: Serialize,537 {538 value.serialize(self)539 }540541 fn serialize_newtype_variant<T: ?Sized>(542 self,543 _name: &'static str,544 _variant_index: u32,545 variant: &'static str,546 value: &T,547 ) -> Result<Val>548 where549 T: Serialize,550 {551 let mut out = ObjValue::builder_with_capacity(1);552 let value = value.serialize(self)?;553 out.member(variant.into()).value_unchecked(value);554 Ok(Val::Obj(out.build()))555 }556557 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {558 Ok(len.map_or_else(559 IntoVecValSerializer::new,560 IntoVecValSerializer::with_capacity,561 ))562 }563564 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {565 Ok(IntoVecValSerializer::with_capacity(len))566 }567568 fn serialize_tuple_struct(569 self,570 _name: &'static str,571 len: usize,572 ) -> Result<Self::SerializeTupleStruct, Self::Error> {573 Ok(IntoVecValSerializer::with_capacity(len))574 }575576 fn serialize_tuple_variant(577 self,578 _name: &'static str,579 _variant_index: u32,580 variant: &'static str,581 len: usize,582 ) -> Result<Self::SerializeTupleVariant, Self::Error> {583 Ok(IntoVecValSerializer::variant_with_capacity(variant, len))584 }585586 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {587 Ok(len.map_or_else(588 IntoObjValueSerializer::new,589 IntoObjValueSerializer::with_capacity,590 ))591 }592593 fn serialize_struct(594 self,595 _name: &'static str,596 len: usize,597 ) -> Result<Self::SerializeStruct, Self::Error> {598 Ok(IntoObjValueSerializer::with_capacity(len))599 }600601 fn serialize_struct_variant(602 self,603 _name: &'static str,604 _variant_index: u32,605 variant: &'static str,606 len: usize,607 ) -> Result<Self::SerializeStructVariant, Self::Error> {608 Ok(IntoObjValueSerializer::variant_with_capacity(variant, len))609 }610}611612impl Val {613 pub fn from_serde(v: impl Serialize) -> Result<Val, JrError> {614 v.serialize(IntoValSerializer)615 }616}617618impl serde::ser::Error for JrError {619 fn custom<T>(msg: T) -> Self620 where621 T: std::fmt::Display,622 {623 runtime_error!("serde: {msg}")624 }625}crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -498,7 +498,7 @@
pub struct InitialUnderscore(pub Thunk<Val>);
impl ContextInitializer for InitialUnderscore {
fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {
- builder.bind("_".into(), self.0.clone());
+ builder.bind("_", self.0.clone());
}
fn as_any(&self) -> &dyn Any {
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -174,11 +174,13 @@
Val::Str(s) => escape_string_json_buf(&s.clone().into_flat(), buf),
Val::Num(n) => write!(buf, "{n}").unwrap(),
#[cfg(feature = "exp-bigint")]
- Val::BigInt(n) => if options.preserve_bigints {
- write!(buf, "{n}").unwrap()
- } else {
- write!(buf, "{:?}", n.to_string()).unwrap()
- },
+ Val::BigInt(n) => {
+ if options.preserve_bigints {
+ write!(buf, "{n}").unwrap()
+ } else {
+ write!(buf, "{:?}", n.to_string()).unwrap()
+ }
+ }
Val::Arr(items) => {
buf.push('[');
if !items.is_empty() {
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -15,7 +15,7 @@
arr::{PickObjectKeyValues, PickObjectValues},
bail,
error::{suggest_object_fields, Error, ErrorKind::*},
- function::CallLocation,
+ function::{CallLocation, FuncVal},
gc::{GcHashMap, GcHashSet, TraceBox},
operator::evaluate_add_op,
tb,
@@ -345,7 +345,7 @@
pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {
let mut out = ObjValueBuilder::with_capacity(1);
out.with_super(self);
- let mut member = out.member(key);
+ let mut member = out.field(key);
if value.flags.add() {
member = member.add()
}
@@ -848,11 +848,27 @@
self.assertions.push(tb!(assertion));
self
}
- pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {
+ pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {
let field_index = self.next_field_index;
self.next_field_index = self.next_field_index.next();
- ObjMemberBuilder::new(ValueBuilder(self), name, field_index)
+ ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)
}
+ /// Preset for common method definiton pattern:
+ /// Create a hidden field with the function value.
+ ///
+ /// `.field(name).hide().value(Val::function(value))`
+ pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {
+ self.field(name).hide().value(Val::Func(value.into()));
+ self
+ }
+ pub fn try_method(
+ &mut self,
+ name: impl Into<IStr>,
+ value: impl Into<FuncVal>,
+ ) -> Result<&mut Self> {
+ self.field(name).hide().try_value(Val::Func(value.into()))?;
+ Ok(self)
+ }
pub fn build(self) -> ObjValue {
if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {
@@ -930,18 +946,19 @@
pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
impl ObjMemberBuilder<ValueBuilder<'_>> {
/// Inserts value, replacing if it is already defined
- pub fn value_unchecked(self, value: Val) {
+ pub fn value(self, value: impl Into<Val>) {
let (receiver, name, member) =
- self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));
+ self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));
let entry = receiver.0.map.entry(name);
entry.insert(member);
}
- pub fn value(self, value: Val) -> Result<()> {
- self.thunk(Thunk::evaluated(value))
+ /// Tries to insert value, returns an error if it was already defined
+ pub fn try_value(self, value: impl Into<Val>) -> Result<()> {
+ self.thunk(Thunk::evaluated(value.into()))
}
- pub fn thunk(self, value: Thunk<Val>) -> Result<()> {
- self.binding(MaybeUnbound::Bound(value))
+ pub fn thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {
+ self.binding(MaybeUnbound::Bound(value.into()))
}
pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {
self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))
@@ -963,8 +980,8 @@
pub struct ExtendBuilder<'v>(&'v mut ObjValue);
impl ObjMemberBuilder<ExtendBuilder<'_>> {
- pub fn value(self, value: Val) {
- self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));
+ pub fn value(self, value: impl Into<Val>) {
+ self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));
}
pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {
self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -276,7 +276,7 @@
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Str(StrValue::Flat(value)))
+ Ok(Val::string(value))
}
fn from_untyped(value: Val) -> Result<Self> {
@@ -292,7 +292,7 @@
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Str(StrValue::Flat(value.into())))
+ Ok(Val::string(value))
}
fn from_untyped(value: Val) -> Result<Self> {
@@ -308,7 +308,7 @@
const TYPE: &'static ComplexValType = &ComplexValType::Char;
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Str(StrValue::Flat(value.to_string().into())))
+ Ok(Val::string(value))
}
fn from_untyped(value: Val) -> Result<Self> {
@@ -356,7 +356,7 @@
bail!("map key should serialize to string");
};
let value = V::into_untyped(v)?;
- out.member(key).value_unchecked(value);
+ out.field(key).value(value);
}
Ok(Val::Obj(out.build()))
}
@@ -611,7 +611,7 @@
fn into_untyped(value: Self) -> Result<Val> {
match value {
- IndexableVal::Str(s) => Ok(Val::Str(StrValue::Flat(s))),
+ IndexableVal::Str(s) => Ok(Val::string(s)),
IndexableVal::Arr(a) => Ok(Val::Arr(a)),
}
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -142,6 +142,14 @@
}
}
}
+impl<T, V: Trace> From<T> for Thunk<V>
+where
+ T: ThunkValue<Output = V>,
+{
+ fn from(value: T) -> Self {
+ Thunk::new(value)
+ }
+}
impl<T: Trace + Default> Default for Thunk<T> {
fn default() -> Self {
@@ -323,21 +331,14 @@
}
}
}
-impl From<&str> for StrValue {
- fn from(value: &str) -> Self {
- Self::Flat(value.into())
- }
-}
-impl From<String> for StrValue {
- fn from(value: String) -> Self {
- Self::Flat(value.into())
+impl<T> From<T> for StrValue
+where
+ IStr: From<T>,
+{
+ fn from(value: T) -> Self {
+ Self::Flat(IStr::from(value))
}
}
-impl From<IStr> for StrValue {
- fn from(value: IStr) -> Self {
- Self::Flat(value)
- }
-}
impl Display for StrValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@@ -401,7 +402,7 @@
impl From<IndexableVal> for Val {
fn from(v: IndexableVal) -> Self {
match v {
- IndexableVal::Str(s) => Self::Str(StrValue::Flat(s)),
+ IndexableVal::Str(s) => Self::string(s),
IndexableVal::Arr(a) => Self::Arr(a),
}
}
@@ -499,6 +500,34 @@
_ => bail!(ValueIsNotIndexable(self.value_type())),
})
}
+
+ pub fn function(function: impl Into<FuncVal>) -> Self {
+ Self::Func(function.into())
+ }
+ pub fn string(string: impl Into<StrValue>) -> Self {
+ Self::Str(string.into())
+ }
+}
+
+impl From<IStr> for Val {
+ fn from(value: IStr) -> Self {
+ Self::string(value)
+ }
+}
+impl From<String> for Val {
+ fn from(value: String) -> Self {
+ Self::string(value)
+ }
+}
+impl From<&str> for Val {
+ fn from(value: &str) -> Self {
+ Self::string(value)
+ }
+}
+impl From<ObjValue> for Val {
+ fn from(value: ObjValue) -> Self {
+ Self::Obj(value)
+ }
}
const fn is_function_like(val: &Val) -> bool {
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -567,18 +567,18 @@
if self.is_option {
quote! {
if let Some(value) = self.#ident {
- out.member(#name.into())
+ out.field(#name)
#hide
#add
- .value(<#ty as Typed>::into_untyped(value)?)?;
+ .try_value(<#ty as Typed>::into_untyped(value)?)?;
}
}
} else {
quote! {
- out.member(#name.into())
+ out.field(#name)
#hide
#add
- .value(<#ty as Typed>::into_untyped(self.#ident)?)?;
+ .try_value(<#ty as Typed>::into_untyped(self.#ident)?)?;
}
}
} else if self.is_option {
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -36,7 +36,7 @@
#[builtin]
pub fn builtin_repeat(what: Either![IStr, ArrValue], count: usize) -> Result<Val> {
Ok(match what {
- Either2::A(s) => Val::Str(StrValue::Flat(s.repeat(count).into())),
+ Either2::A(s) => Val::string(s.repeat(count)),
Either2::B(arr) => Val::Arr(
ArrValue::repeated(arr, count)
.ok_or_else(|| runtime_error!("repeated length overflow"))?,
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -6,13 +6,12 @@
use jrsonnet_evaluator::{
error::{ErrorKind::*, Result},
- function::{builtin::Builtin, CallLocation, FuncVal, TlaArg},
- gc::TraceBox,
+ function::{CallLocation, FuncVal, TlaArg},
tb,
trace::PathResolver,
ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,
};
-use jrsonnet_gcmodule::{Cc, Trace};
+use jrsonnet_gcmodule::Trace;
use jrsonnet_parser::Source;
mod expr;
@@ -182,38 +181,24 @@
.iter()
.cloned()
{
- builder
- .member(name.into())
- .hide()
- .value(Val::Func(FuncVal::StaticBuiltin(builtin)))
- .expect("no conflict");
+ builder.method(name, builtin);
}
- builder
- .member("extVar".into())
- .hide()
- .value(Val::Func(FuncVal::builtin(builtin_ext_var {
+ builder.method(
+ "extVar",
+ builtin_ext_var {
settings: settings.clone(),
- })))
- .expect("no conflict");
- builder
- .member("native".into())
- .hide()
- .value(Val::Func(FuncVal::builtin(builtin_native {
+ },
+ );
+ builder.method(
+ "native",
+ builtin_native {
settings: settings.clone(),
- })))
- .expect("no conflict");
- builder
- .member("trace".into())
- .hide()
- .value(Val::Func(FuncVal::builtin(builtin_trace { settings })))
- .expect("no conflict");
+ },
+ );
+ builder.method("trace", builtin_trace { settings });
- builder
- .member("id".into())
- .hide()
- .value(Val::Func(FuncVal::Id))
- .expect("no conflict");
+ builder.method("id", FuncVal::Id);
builder.build()
}
@@ -293,7 +278,7 @@
#[cfg(not(feature = "legacy-this-file"))]
context: {
let mut context = ContextBuilder::with_capacity(_s, 1);
- context.bind("std".into(), stdlib_thunk.clone());
+ context.bind("std", stdlib_thunk.clone());
context.build()
},
#[cfg(not(feature = "legacy-this-file"))]
@@ -338,10 +323,10 @@
.insert(name.into(), TlaArg::Code(parsed));
Ok(())
}
- pub fn add_native(&self, name: IStr, cb: impl Builtin) {
+ pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {
self.settings_mut()
.ext_natives
- .insert(name, Cc::new(tb!(cb)));
+ .insert(name.into(), cb.into());
}
}
impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {
@@ -354,7 +339,7 @@
}
#[cfg(not(feature = "legacy-this-file"))]
fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {
- builder.bind("std".into(), self.stdlib_thunk.clone());
+ builder.bind("std", self.stdlib_thunk.clone());
}
#[cfg(feature = "legacy-this-file")]
fn populate(&self, source: Source, builder: &mut ContextBuilder) {
@@ -362,14 +347,14 @@
let mut std = ObjValueBuilder::new();
std.with_super(self.stdlib_obj.clone());
- std.member("thisFile".into())
+ std.field("thisFile".into())
.hide()
- .value(Val::Str(StrValue::Flat(
+ .value(Val::string(
match source.source_path().path() {
Some(p) => self.settings().path_resolver.resolve(p).into(),
None => source.source_path().to_string().into(),
},
- )))
+ ))
.expect("this object builder is empty");
let stdlib_with_this_file = std.build();
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -47,7 +47,7 @@
.ext_natives
.get(&x)
.cloned()
- .map_or(Val::Null, |v| Val::Func(FuncVal::Builtin(v)))
+ .map_or(Val::Null, |v| Val::Func(v))
}
#[builtin(fields(
crates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -122,7 +122,7 @@
if k == key {
continue;
}
- new_obj.member(k).value_unchecked(v.unwrap())
+ new_obj.field(k).value(v.unwrap())
}
new_obj.build()
crates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -16,7 +16,7 @@
evaluate_mod_op(
&match a {
A(v) => Val::Num(v),
- B(s) => Val::Str(StrValue::Flat(s)),
+ B(s) => Val::string(s),
},
&b,
)
crates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -1,11 +1,10 @@
use std::cmp::Ordering;
use jrsonnet_evaluator::{
- error::Result,
function::{builtin, FuncVal},
operator::evaluate_compare_op,
val::ArrValue,
- Thunk, Val,
+ Result, Thunk, Val,
};
use jrsonnet_parser::BinaryOpType;
@@ -108,7 +107,7 @@
}
};
}
- while let Some(ac) = &ak {
+ while let Some(_ac) = &ak {
// In a, but not in b
out.push(av.clone().expect("ak != None"));
av = a.next();
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -3,7 +3,7 @@
error::{ErrorKind::*, Result},
function::builtin,
typed::{Either2, M1},
- val::{ArrValue, StrValue},
+ val::ArrValue,
Either, IStr, Val,
};
@@ -41,14 +41,8 @@
pub fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> ArrValue {
use Either2::*;
match maxsplits {
- A(n) => str
- .splitn(n + 1, &c as &str)
- .map(|s| Val::Str(StrValue::Flat(s.into())))
- .collect(),
- B(_) => str
- .split(&c as &str)
- .map(|s| Val::Str(StrValue::Flat(s.into())))
- .collect(),
+ A(n) => str.splitn(n + 1, &c as &str).map(Val::string).collect(),
+ B(_) => str.split(&c as &str).map(Val::string).collect(),
}
}
tests/tests/builtin.rsdiffbeforeafterboth--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -36,7 +36,7 @@
s.with_stdlib();
s.add_global(
"nativeAdd".into(),
- Thunk::evaluated(Val::Func(FuncVal::StaticBuiltin(native_add::INST))),
+ Thunk::evaluated(Val::function(native_add::INST)),
);
let v = s.evaluate_snippet(
@@ -69,7 +69,7 @@
s.with_stdlib();
s.add_global(
"curryAdd".into(),
- Thunk::evaluated(Val::Func(FuncVal::StaticBuiltin(curry_add::INST))),
+ Thunk::evaluated(Val::function(curry_add::INST)),
);
let v = s.evaluate_snippet(
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -77,12 +77,8 @@
#[allow(dead_code)]
pub fn with_test(s: &State) {
let mut bobj = ObjValueBuilder::new();
- bobj.member("assertThrow".into())
- .hide()
- .value_unchecked(Val::Func(FuncVal::StaticBuiltin(assert_throw::INST)));
- bobj.member("paramNames".into())
- .hide()
- .value_unchecked(Val::Func(FuncVal::StaticBuiltin(param_names::INST)));
+ bobj.method("assertThrow", assert_throw::INST);
+ bobj.method("paramNames", param_names::INST);
s.add_global("test".into(), Thunk::evaluated(Val::Obj(bobj.build())))
}