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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -11,10 +11,8 @@
};
use crate::{
- arr::ArrValue,
- error::{Error as JrError, ErrorKind, Result},
- val::StrValue,
- ObjValue, ObjValueBuilder, State, Val,
+ arr::ArrValue, runtime_error, Error as JrError, ObjValue, ObjValueBuilder,
+ Result, State, Val,
};
impl<'de> Deserialize<'de> for Val {
@@ -57,7 +55,7 @@
where
E: serde::de::Error,
{
- Ok(Val::Str(StrValue::Flat(v.into())))
+ Ok(Val::string(v))
}
// visit_num! {
@@ -138,7 +136,7 @@
while let Some((k, v)) = map.next_entry::<Cow<'de, str>, Val>()? {
// Jsonnet ignores duplicate keys
- out.member(k.into()).value_unchecked(v);
+ out.field(k).value(v);
}
Ok(Val::Obj(out.build()))
@@ -264,7 +262,7 @@
let inner = Val::Arr(ArrValue::eager(self.data));
if let Some(variant) = self.variant {
let mut out = ObjValue::builder_with_capacity(1);
- out.member(variant).value_unchecked(inner);
+ out.field(variant).value(inner);
Ok(Val::Obj(out.build()))
} else {
Ok(inner)
@@ -365,7 +363,7 @@
{
let key = self.key.take().expect("no serialize_key called");
let value = value.serialize(IntoValSerializer)?;
- self.data.member(key).value(value)?;
+ self.data.field(key).try_value(value)?;
Ok(())
}
@@ -378,7 +376,7 @@
let key = key.serialize(IntoValSerializer)?;
let key = key.to_string()?;
let value = value.serialize(IntoValSerializer)?;
- self.data.member(key).value(value)?;
+ self.data.field(key).try_value(value)?;
Ok(())
}
@@ -386,7 +384,7 @@
let inner = Val::Obj(self.data.build());
if let Some(variant) = self.variant {
let mut out = ObjValue::builder_with_capacity(1);
- out.member(variant).value_unchecked(inner);
+ out.field(variant).value(inner);
Ok(Val::Obj(out.build()))
} else {
Ok(inner)
@@ -550,7 +548,7 @@
{
let mut out = ObjValue::builder_with_capacity(1);
let value = value.serialize(self)?;
- out.member(variant.into()).value_unchecked(value);
+ out.field(variant).value(value);
Ok(Val::Obj(out.build()))
}
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.rsdiffbeforeafterboth1use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5pub use jrsonnet_macros::Typed;6use jrsonnet_types::{ComplexValType, ValType};78use crate::{9 arr::{ArrValue, BytesArray},10 bail,11 function::{native::NativeDesc, FuncDesc, FuncVal},12 typed::CheckType,13 val::{IndexableVal, ThunkMapper},14 ObjValue, ObjValueBuilder, Result, Thunk, Val,15};1617#[derive(Trace)]18struct FromUntyped<K: Trace>(PhantomData<fn() -> K>);19impl<K> ThunkMapper<Val> for FromUntyped<K>20where21 K: Typed + Trace,22{23 type Output = K;2425 fn map(self, from: Val) -> Result<Self::Output> {26 K::from_untyped(from)27 }28}29impl<K: Trace> Default for FromUntyped<K> {30 fn default() -> Self {31 Self(PhantomData)32 }33}3435pub trait TypedObj: Typed {36 fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;37 fn parse(obj: &ObjValue) -> Result<Self>;38 fn into_object(self) -> Result<ObjValue> {39 let mut builder = ObjValueBuilder::new();40 self.serialize(&mut builder)?;41 Ok(builder.build())42 }43}4445pub trait Typed: Sized {46 const TYPE: &'static ComplexValType;47 fn into_untyped(typed: Self) -> Result<Val>;48 fn into_lazy_untyped(typed: Self) -> Thunk<Val> {49 Thunk::from(Self::into_untyped(typed))50 }51 fn from_untyped(untyped: Val) -> Result<Self>;52 fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {53 Self::from_untyped(lazy.evaluate()?)54 }5556 // Whatever caller should use `into_lazy_untyped` instead of `into_untyped`57 fn provides_lazy() -> bool {58 false59 }6061 // Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible62 fn wants_lazy() -> bool {63 false64 }6566 /// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result67 /// This method returns identity in impl Typed for Result, and should not be overriden68 #[doc(hidden)]69 fn into_result(typed: Self) -> Result<Val> {70 let value = Self::into_untyped(typed)?;71 Ok(value)72 }73}7475impl<T> Typed for Thunk<T>76where77 T: Typed + Trace + Clone,78{79 const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);8081 fn into_untyped(typed: Self) -> Result<Val> {82 T::into_untyped(typed.evaluate()?)83 }8485 fn from_untyped(untyped: Val) -> Result<Self> {86 Self::from_lazy_untyped(Thunk::evaluated(untyped))87 }8889 fn provides_lazy() -> bool {90 true91 }9293 fn into_lazy_untyped(inner: Self) -> Thunk<Val> {94 #[derive(Trace)]95 struct IntoUntyped<K: Trace>(PhantomData<fn() -> K>);96 impl<K> ThunkMapper<K> for IntoUntyped<K>97 where98 K: Typed + Trace,99 {100 type Output = Val;101102 fn map(self, from: K) -> Result<Self::Output> {103 K::into_untyped(from)104 }105 }106 impl<K: Trace> Default for IntoUntyped<K> {107 fn default() -> Self {108 Self(PhantomData)109 }110 }111 inner.map(<IntoUntyped<T>>::default())112 }113114 fn wants_lazy() -> bool {115 true116 }117118 fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {119 Ok(inner.map(<FromUntyped<T>>::default()))120 }121}122123const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;124125macro_rules! impl_int {126 ($($ty:ty)*) => {$(127 impl Typed for $ty {128 const TYPE: &'static ComplexValType =129 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));130 fn from_untyped(value: Val) -> Result<Self> {131 <Self as Typed>::TYPE.check(&value)?;132 match value {133 Val::Num(n) => {134 #[allow(clippy::float_cmp)]135 if n.trunc() != n {136 bail!(137 "cannot convert number with fractional part to {}",138 stringify!($ty)139 )140 }141 Ok(n as Self)142 }143 _ => unreachable!(),144 }145 }146 fn into_untyped(value: Self) -> Result<Val> {147 Ok(Val::Num(value as f64))148 }149 }150 )*};151}152153impl_int!(i8 u8 i16 u16 i32 u32);154155macro_rules! impl_bounded_int {156 ($($name:ident = $ty:ty)*) => {$(157 #[derive(Clone, Copy)]158 pub struct $name<const MIN: $ty, const MAX: $ty>($ty);159 impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {160 pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {161 if value >= MIN && value <= MAX {162 Some(Self(value))163 } else {164 None165 }166 }167 pub const fn value(self) -> $ty {168 self.0169 }170 }171 impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {172 type Target = $ty;173 fn deref(&self) -> &Self::Target {174 &self.0175 }176 }177178 impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {179 const TYPE: &'static ComplexValType =180 &ComplexValType::BoundedNumber(181 Some(MIN as f64),182 Some(MAX as f64),183 );184185 fn from_untyped(value: Val) -> Result<Self> {186 <Self as Typed>::TYPE.check(&value)?;187 match value {188 Val::Num(n) => {189 #[allow(clippy::float_cmp)]190 if n.trunc() != n {191 bail!(192 "cannot convert number with fractional part to {}",193 stringify!($ty)194 )195 }196 Ok(Self(n as $ty))197 }198 _ => unreachable!(),199 }200 }201202 fn into_untyped(value: Self) -> Result<Val> {203 Ok(Val::Num(value.0 as f64))204 }205 }206 )*};207}208209impl_bounded_int!(210 BoundedI8 = i8211 BoundedI16 = i16212 BoundedI32 = i32213 BoundedI64 = i64214 BoundedUsize = usize215);216217impl Typed for f64 {218 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);219220 fn into_untyped(value: Self) -> Result<Val> {221 Ok(Val::Num(value))222 }223224 fn from_untyped(value: Val) -> Result<Self> {225 <Self as Typed>::TYPE.check(&value)?;226 match value {227 Val::Num(n) => Ok(n),228 _ => unreachable!(),229 }230 }231}232233pub struct PositiveF64(pub f64);234impl Typed for PositiveF64 {235 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);236237 fn into_untyped(value: Self) -> Result<Val> {238 Ok(Val::Num(value.0))239 }240241 fn from_untyped(value: Val) -> Result<Self> {242 <Self as Typed>::TYPE.check(&value)?;243 match value {244 Val::Num(n) => Ok(Self(n)),245 _ => unreachable!(),246 }247 }248}249impl Typed for usize {250 const TYPE: &'static ComplexValType =251 &ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));252253 fn into_untyped(value: Self) -> Result<Val> {254 if value > MAX_SAFE_INTEGER as Self {255 bail!("number is too large")256 }257 Ok(Val::Num(value as f64))258 }259260 fn from_untyped(value: Val) -> Result<Self> {261 <Self as Typed>::TYPE.check(&value)?;262 match value {263 Val::Num(n) => {264 #[allow(clippy::float_cmp)]265 if n.trunc() != n {266 bail!("cannot convert number with fractional part to usize")267 }268 Ok(n as Self)269 }270 _ => unreachable!(),271 }272 }273}274275impl Typed for IStr {276 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);277278 fn into_untyped(value: Self) -> Result<Val> {279 Ok(Val::Str(StrValue::Flat(value)))280 }281282 fn from_untyped(value: Val) -> Result<Self> {283 <Self as Typed>::TYPE.check(&value)?;284 match value {285 Val::Str(s) => Ok(s.into_flat()),286 _ => unreachable!(),287 }288 }289}290291impl Typed for String {292 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);293294 fn into_untyped(value: Self) -> Result<Val> {295 Ok(Val::Str(StrValue::Flat(value.into())))296 }297298 fn from_untyped(value: Val) -> Result<Self> {299 <Self as Typed>::TYPE.check(&value)?;300 match value {301 Val::Str(s) => Ok(s.to_string()),302 _ => unreachable!(),303 }304 }305}306307impl Typed for char {308 const TYPE: &'static ComplexValType = &ComplexValType::Char;309310 fn into_untyped(value: Self) -> Result<Val> {311 Ok(Val::Str(StrValue::Flat(value.to_string().into())))312 }313314 fn from_untyped(value: Val) -> Result<Self> {315 <Self as Typed>::TYPE.check(&value)?;316 match value {317 Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),318 _ => unreachable!(),319 }320 }321}322323impl<T> Typed for Vec<T>324where325 T: Typed,326{327 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);328329 fn into_untyped(value: Self) -> Result<Val> {330 Ok(Val::Arr(331 value332 .into_iter()333 .map(T::into_untyped)334 .collect::<Result<ArrValue>>()?,335 ))336 }337338 fn from_untyped(value: Val) -> Result<Self> {339 let Val::Arr(a) = value else {340 <Self as Typed>::TYPE.check(&value)?;341 unreachable!("typecheck should fail")342 };343 a.iter()344 .map(|r| r.and_then(T::from_untyped))345 .collect::<Result<Vec<T>>>()346 }347}348349impl<K: Typed + Ord, V: Typed> Typed for BTreeMap<K, V> {350 const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);351352 fn into_untyped(typed: Self) -> Result<Val> {353 let mut out = ObjValueBuilder::with_capacity(typed.len());354 for (k, v) in typed {355 let Some(key) = K::into_untyped(k)?.as_str() else {356 bail!("map key should serialize to string");357 };358 let value = V::into_untyped(v)?;359 out.member(key).value_unchecked(value);360 }361 Ok(Val::Obj(out.build()))362 }363364 fn from_untyped(value: Val) -> Result<Self> {365 Self::TYPE.check(&value)?;366 let obj = value.as_obj().expect("typecheck should fail");367368 let mut out = BTreeMap::new();369 if V::wants_lazy() {370 for key in obj.fields_ex(371 false,372 #[cfg(feature = "exp-preserve-order")]373 false,374 ) {375 let value = obj.get_lazy(key.clone()).expect("field exists");376 let value = V::from_lazy_untyped(value)?;377 let key = K::from_untyped(Val::Str(key.into()))?;378 let _ = out.insert(key, value);379 }380 } else {381 for (key, value) in obj.iter(382 #[cfg(feature = "exp-preserve-order")]383 false,384 ) {385 let key = K::from_untyped(Val::Str(key.into()))?;386 let value = V::from_untyped(value?)?;387 let _ = out.insert(key, value);388 }389 }390 Ok(out)391 }392}393394impl Typed for Val {395 const TYPE: &'static ComplexValType = &ComplexValType::Any;396397 fn into_untyped(typed: Self) -> Result<Val> {398 Ok(typed)399 }400 fn from_untyped(untyped: Val) -> Result<Self> {401 Ok(untyped)402 }403}404405// Hack406#[doc(hidden)]407impl<T> Typed for Result<T>408where409 T: Typed,410{411 const TYPE: &'static ComplexValType = &ComplexValType::Any;412413 fn into_untyped(_typed: Self) -> Result<Val> {414 panic!("do not use this conversion")415 }416417 fn from_untyped(_untyped: Val) -> Result<Self> {418 panic!("do not use this conversion")419 }420421 fn into_result(typed: Self) -> Result<Val> {422 typed.map(T::into_untyped)?423 }424}425426/// Specialization427impl Typed for IBytes {428 const TYPE: &'static ComplexValType =429 &ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));430431 fn into_untyped(value: Self) -> Result<Val> {432 Ok(Val::Arr(ArrValue::bytes(value)))433 }434435 fn from_untyped(value: Val) -> Result<Self> {436 match &value {437 Val::Arr(a) => {438 if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {439 return Ok(bytes.0.as_slice().into());440 };441 <Self as Typed>::TYPE.check(&value)?;442 // Any::downcast_ref::<ByteArray>(&a);443 let mut out = Vec::with_capacity(a.len());444 for e in a.iter() {445 let r = e?;446 out.push(u8::from_untyped(r)?);447 }448 Ok(out.as_slice().into())449 }450 _ => {451 <Self as Typed>::TYPE.check(&value)?;452 unreachable!()453 }454 }455 }456}457458pub struct M1;459impl Typed for M1 {460 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));461462 fn into_untyped(_: Self) -> Result<Val> {463 Ok(Val::Num(-1.0))464 }465466 fn from_untyped(value: Val) -> Result<Self> {467 <Self as Typed>::TYPE.check(&value)?;468 Ok(Self)469 }470}471472macro_rules! decl_either {473 ($($name: ident, $($id: ident)*);*) => {$(474 #[derive(Clone)]475 pub enum $name<$($id),*> {476 $($id($id)),*477 }478 impl<$($id),*> Typed for $name<$($id),*>479 where480 $($id: Typed,)*481 {482 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);483484 fn into_untyped(value: Self) -> Result<Val> {485 match value {$(486 $name::$id(v) => $id::into_untyped(v)487 ),*}488 }489490 fn from_untyped(value: Val) -> Result<Self> {491 $(492 if $id::TYPE.check(&value).is_ok() {493 $id::from_untyped(value).map(Self::$id)494 } else495 )* {496 <Self as Typed>::TYPE.check(&value)?;497 unreachable!()498 }499 }500 }501 )*}502}503decl_either!(504 Either1, A;505 Either2, A B;506 Either3, A B C;507 Either4, A B C D;508 Either5, A B C D E;509 Either6, A B C D E F;510 Either7, A B C D E F G511);512#[macro_export]513macro_rules! Either {514 ($a:ty) => {Either1<$a>};515 ($a:ty, $b:ty) => {Either2<$a, $b>};516 ($a:ty, $b:ty, $c:ty) => {Either3<$a, $b, $c>};517 ($a:ty, $b:ty, $c:ty, $d:ty) => {Either4<$a, $b, $c, $d>};518 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {Either5<$a, $b, $c, $d, $e>};519 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {Either6<$a, $b, $c, $d, $e, $f>};520 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {Either7<$a, $b, $c, $d, $e, $f, $g>};521}522pub use Either;523524pub type MyType = Either![u32, f64, String];525526impl Typed for ArrValue {527 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);528529 fn into_untyped(value: Self) -> Result<Val> {530 Ok(Val::Arr(value))531 }532533 fn from_untyped(value: Val) -> Result<Self> {534 <Self as Typed>::TYPE.check(&value)?;535 match value {536 Val::Arr(a) => Ok(a),537 _ => unreachable!(),538 }539 }540}541542impl Typed for FuncVal {543 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);544545 fn into_untyped(value: Self) -> Result<Val> {546 Ok(Val::Func(value))547 }548549 fn from_untyped(value: Val) -> Result<Self> {550 <Self as Typed>::TYPE.check(&value)?;551 match value {552 Val::Func(a) => Ok(a),553 _ => unreachable!(),554 }555 }556}557558impl Typed for Cc<FuncDesc> {559 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);560561 fn into_untyped(value: Self) -> Result<Val> {562 Ok(Val::Func(FuncVal::Normal(value)))563 }564565 fn from_untyped(value: Val) -> Result<Self> {566 <Self as Typed>::TYPE.check(&value)?;567 match value {568 Val::Func(FuncVal::Normal(desc)) => Ok(desc),569 Val::Func(_) => bail!("expected normal function, not builtin"),570 _ => unreachable!(),571 }572 }573}574575impl Typed for ObjValue {576 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);577578 fn into_untyped(value: Self) -> Result<Val> {579 Ok(Val::Obj(value))580 }581582 fn from_untyped(value: Val) -> Result<Self> {583 <Self as Typed>::TYPE.check(&value)?;584 match value {585 Val::Obj(a) => Ok(a),586 _ => unreachable!(),587 }588 }589}590591impl Typed for bool {592 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);593594 fn into_untyped(value: Self) -> Result<Val> {595 Ok(Val::Bool(value))596 }597598 fn from_untyped(value: Val) -> Result<Self> {599 <Self as Typed>::TYPE.check(&value)?;600 match value {601 Val::Bool(a) => Ok(a),602 _ => unreachable!(),603 }604 }605}606impl Typed for IndexableVal {607 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[608 &ComplexValType::Simple(ValType::Arr),609 &ComplexValType::Simple(ValType::Str),610 ]);611612 fn into_untyped(value: Self) -> Result<Val> {613 match value {614 IndexableVal::Str(s) => Ok(Val::Str(StrValue::Flat(s))),615 IndexableVal::Arr(a) => Ok(Val::Arr(a)),616 }617 }618619 fn from_untyped(value: Val) -> Result<Self> {620 <Self as Typed>::TYPE.check(&value)?;621 value.into_indexable()622 }623}624625pub struct Null;626impl Typed for Null {627 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);628629 fn into_untyped(_: Self) -> Result<Val> {630 Ok(Val::Null)631 }632633 fn from_untyped(value: Val) -> Result<Self> {634 <Self as Typed>::TYPE.check(&value)?;635 Ok(Self)636 }637}638639pub struct NativeFn<D: NativeDesc>(D::Value);640impl<D: NativeDesc> Deref for NativeFn<D> {641 type Target = D::Value;642643 fn deref(&self) -> &Self::Target {644 &self.0645 }646}647impl<D: NativeDesc> Typed for NativeFn<D> {648 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);649650 fn into_untyped(_typed: Self) -> Result<Val> {651 bail!("can only convert functions from jsonnet to native")652 }653654 fn from_untyped(untyped: Val) -> Result<Self> {655 Ok(Self(656 untyped657 .as_func()658 .expect("shape is checked")659 .into_native::<D>(),660 ))661 }662}1use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5pub use jrsonnet_macros::Typed;6use jrsonnet_types::{ComplexValType, ValType};78use crate::{9 arr::{ArrValue, BytesArray},10 bail,11 function::{native::NativeDesc, FuncDesc, FuncVal},12 typed::CheckType,13 val::{IndexableVal, ThunkMapper},14 ObjValue, ObjValueBuilder, Result, Thunk, Val,15};1617#[derive(Trace)]18struct FromUntyped<K: Trace>(PhantomData<fn() -> K>);19impl<K> ThunkMapper<Val> for FromUntyped<K>20where21 K: Typed + Trace,22{23 type Output = K;2425 fn map(self, from: Val) -> Result<Self::Output> {26 K::from_untyped(from)27 }28}29impl<K: Trace> Default for FromUntyped<K> {30 fn default() -> Self {31 Self(PhantomData)32 }33}3435pub trait TypedObj: Typed {36 fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;37 fn parse(obj: &ObjValue) -> Result<Self>;38 fn into_object(self) -> Result<ObjValue> {39 let mut builder = ObjValueBuilder::new();40 self.serialize(&mut builder)?;41 Ok(builder.build())42 }43}4445pub trait Typed: Sized {46 const TYPE: &'static ComplexValType;47 fn into_untyped(typed: Self) -> Result<Val>;48 fn into_lazy_untyped(typed: Self) -> Thunk<Val> {49 Thunk::from(Self::into_untyped(typed))50 }51 fn from_untyped(untyped: Val) -> Result<Self>;52 fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {53 Self::from_untyped(lazy.evaluate()?)54 }5556 // Whatever caller should use `into_lazy_untyped` instead of `into_untyped`57 fn provides_lazy() -> bool {58 false59 }6061 // Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible62 fn wants_lazy() -> bool {63 false64 }6566 /// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result67 /// This method returns identity in impl Typed for Result, and should not be overriden68 #[doc(hidden)]69 fn into_result(typed: Self) -> Result<Val> {70 let value = Self::into_untyped(typed)?;71 Ok(value)72 }73}7475impl<T> Typed for Thunk<T>76where77 T: Typed + Trace + Clone,78{79 const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);8081 fn into_untyped(typed: Self) -> Result<Val> {82 T::into_untyped(typed.evaluate()?)83 }8485 fn from_untyped(untyped: Val) -> Result<Self> {86 Self::from_lazy_untyped(Thunk::evaluated(untyped))87 }8889 fn provides_lazy() -> bool {90 true91 }9293 fn into_lazy_untyped(inner: Self) -> Thunk<Val> {94 #[derive(Trace)]95 struct IntoUntyped<K: Trace>(PhantomData<fn() -> K>);96 impl<K> ThunkMapper<K> for IntoUntyped<K>97 where98 K: Typed + Trace,99 {100 type Output = Val;101102 fn map(self, from: K) -> Result<Self::Output> {103 K::into_untyped(from)104 }105 }106 impl<K: Trace> Default for IntoUntyped<K> {107 fn default() -> Self {108 Self(PhantomData)109 }110 }111 inner.map(<IntoUntyped<T>>::default())112 }113114 fn wants_lazy() -> bool {115 true116 }117118 fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {119 Ok(inner.map(<FromUntyped<T>>::default()))120 }121}122123const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;124125macro_rules! impl_int {126 ($($ty:ty)*) => {$(127 impl Typed for $ty {128 const TYPE: &'static ComplexValType =129 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));130 fn from_untyped(value: Val) -> Result<Self> {131 <Self as Typed>::TYPE.check(&value)?;132 match value {133 Val::Num(n) => {134 #[allow(clippy::float_cmp)]135 if n.trunc() != n {136 bail!(137 "cannot convert number with fractional part to {}",138 stringify!($ty)139 )140 }141 Ok(n as Self)142 }143 _ => unreachable!(),144 }145 }146 fn into_untyped(value: Self) -> Result<Val> {147 Ok(Val::Num(value as f64))148 }149 }150 )*};151}152153impl_int!(i8 u8 i16 u16 i32 u32);154155macro_rules! impl_bounded_int {156 ($($name:ident = $ty:ty)*) => {$(157 #[derive(Clone, Copy)]158 pub struct $name<const MIN: $ty, const MAX: $ty>($ty);159 impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {160 pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {161 if value >= MIN && value <= MAX {162 Some(Self(value))163 } else {164 None165 }166 }167 pub const fn value(self) -> $ty {168 self.0169 }170 }171 impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {172 type Target = $ty;173 fn deref(&self) -> &Self::Target {174 &self.0175 }176 }177178 impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {179 const TYPE: &'static ComplexValType =180 &ComplexValType::BoundedNumber(181 Some(MIN as f64),182 Some(MAX as f64),183 );184185 fn from_untyped(value: Val) -> Result<Self> {186 <Self as Typed>::TYPE.check(&value)?;187 match value {188 Val::Num(n) => {189 #[allow(clippy::float_cmp)]190 if n.trunc() != n {191 bail!(192 "cannot convert number with fractional part to {}",193 stringify!($ty)194 )195 }196 Ok(Self(n as $ty))197 }198 _ => unreachable!(),199 }200 }201202 fn into_untyped(value: Self) -> Result<Val> {203 Ok(Val::Num(value.0 as f64))204 }205 }206 )*};207}208209impl_bounded_int!(210 BoundedI8 = i8211 BoundedI16 = i16212 BoundedI32 = i32213 BoundedI64 = i64214 BoundedUsize = usize215);216217impl Typed for f64 {218 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);219220 fn into_untyped(value: Self) -> Result<Val> {221 Ok(Val::Num(value))222 }223224 fn from_untyped(value: Val) -> Result<Self> {225 <Self as Typed>::TYPE.check(&value)?;226 match value {227 Val::Num(n) => Ok(n),228 _ => unreachable!(),229 }230 }231}232233pub struct PositiveF64(pub f64);234impl Typed for PositiveF64 {235 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);236237 fn into_untyped(value: Self) -> Result<Val> {238 Ok(Val::Num(value.0))239 }240241 fn from_untyped(value: Val) -> Result<Self> {242 <Self as Typed>::TYPE.check(&value)?;243 match value {244 Val::Num(n) => Ok(Self(n)),245 _ => unreachable!(),246 }247 }248}249impl Typed for usize {250 const TYPE: &'static ComplexValType =251 &ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));252253 fn into_untyped(value: Self) -> Result<Val> {254 if value > MAX_SAFE_INTEGER as Self {255 bail!("number is too large")256 }257 Ok(Val::Num(value as f64))258 }259260 fn from_untyped(value: Val) -> Result<Self> {261 <Self as Typed>::TYPE.check(&value)?;262 match value {263 Val::Num(n) => {264 #[allow(clippy::float_cmp)]265 if n.trunc() != n {266 bail!("cannot convert number with fractional part to usize")267 }268 Ok(n as Self)269 }270 _ => unreachable!(),271 }272 }273}274275impl Typed for IStr {276 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);277278 fn into_untyped(value: Self) -> Result<Val> {279 Ok(Val::string(value))280 }281282 fn from_untyped(value: Val) -> Result<Self> {283 <Self as Typed>::TYPE.check(&value)?;284 match value {285 Val::Str(s) => Ok(s.into_flat()),286 _ => unreachable!(),287 }288 }289}290291impl Typed for String {292 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);293294 fn into_untyped(value: Self) -> Result<Val> {295 Ok(Val::string(value))296 }297298 fn from_untyped(value: Val) -> Result<Self> {299 <Self as Typed>::TYPE.check(&value)?;300 match value {301 Val::Str(s) => Ok(s.to_string()),302 _ => unreachable!(),303 }304 }305}306307impl Typed for char {308 const TYPE: &'static ComplexValType = &ComplexValType::Char;309310 fn into_untyped(value: Self) -> Result<Val> {311 Ok(Val::string(value))312 }313314 fn from_untyped(value: Val) -> Result<Self> {315 <Self as Typed>::TYPE.check(&value)?;316 match value {317 Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),318 _ => unreachable!(),319 }320 }321}322323impl<T> Typed for Vec<T>324where325 T: Typed,326{327 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);328329 fn into_untyped(value: Self) -> Result<Val> {330 Ok(Val::Arr(331 value332 .into_iter()333 .map(T::into_untyped)334 .collect::<Result<ArrValue>>()?,335 ))336 }337338 fn from_untyped(value: Val) -> Result<Self> {339 let Val::Arr(a) = value else {340 <Self as Typed>::TYPE.check(&value)?;341 unreachable!("typecheck should fail")342 };343 a.iter()344 .map(|r| r.and_then(T::from_untyped))345 .collect::<Result<Vec<T>>>()346 }347}348349impl<K: Typed + Ord, V: Typed> Typed for BTreeMap<K, V> {350 const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);351352 fn into_untyped(typed: Self) -> Result<Val> {353 let mut out = ObjValueBuilder::with_capacity(typed.len());354 for (k, v) in typed {355 let Some(key) = K::into_untyped(k)?.as_str() else {356 bail!("map key should serialize to string");357 };358 let value = V::into_untyped(v)?;359 out.field(key).value(value);360 }361 Ok(Val::Obj(out.build()))362 }363364 fn from_untyped(value: Val) -> Result<Self> {365 Self::TYPE.check(&value)?;366 let obj = value.as_obj().expect("typecheck should fail");367368 let mut out = BTreeMap::new();369 if V::wants_lazy() {370 for key in obj.fields_ex(371 false,372 #[cfg(feature = "exp-preserve-order")]373 false,374 ) {375 let value = obj.get_lazy(key.clone()).expect("field exists");376 let value = V::from_lazy_untyped(value)?;377 let key = K::from_untyped(Val::Str(key.into()))?;378 let _ = out.insert(key, value);379 }380 } else {381 for (key, value) in obj.iter(382 #[cfg(feature = "exp-preserve-order")]383 false,384 ) {385 let key = K::from_untyped(Val::Str(key.into()))?;386 let value = V::from_untyped(value?)?;387 let _ = out.insert(key, value);388 }389 }390 Ok(out)391 }392}393394impl Typed for Val {395 const TYPE: &'static ComplexValType = &ComplexValType::Any;396397 fn into_untyped(typed: Self) -> Result<Val> {398 Ok(typed)399 }400 fn from_untyped(untyped: Val) -> Result<Self> {401 Ok(untyped)402 }403}404405// Hack406#[doc(hidden)]407impl<T> Typed for Result<T>408where409 T: Typed,410{411 const TYPE: &'static ComplexValType = &ComplexValType::Any;412413 fn into_untyped(_typed: Self) -> Result<Val> {414 panic!("do not use this conversion")415 }416417 fn from_untyped(_untyped: Val) -> Result<Self> {418 panic!("do not use this conversion")419 }420421 fn into_result(typed: Self) -> Result<Val> {422 typed.map(T::into_untyped)?423 }424}425426/// Specialization427impl Typed for IBytes {428 const TYPE: &'static ComplexValType =429 &ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));430431 fn into_untyped(value: Self) -> Result<Val> {432 Ok(Val::Arr(ArrValue::bytes(value)))433 }434435 fn from_untyped(value: Val) -> Result<Self> {436 match &value {437 Val::Arr(a) => {438 if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {439 return Ok(bytes.0.as_slice().into());440 };441 <Self as Typed>::TYPE.check(&value)?;442 // Any::downcast_ref::<ByteArray>(&a);443 let mut out = Vec::with_capacity(a.len());444 for e in a.iter() {445 let r = e?;446 out.push(u8::from_untyped(r)?);447 }448 Ok(out.as_slice().into())449 }450 _ => {451 <Self as Typed>::TYPE.check(&value)?;452 unreachable!()453 }454 }455 }456}457458pub struct M1;459impl Typed for M1 {460 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));461462 fn into_untyped(_: Self) -> Result<Val> {463 Ok(Val::Num(-1.0))464 }465466 fn from_untyped(value: Val) -> Result<Self> {467 <Self as Typed>::TYPE.check(&value)?;468 Ok(Self)469 }470}471472macro_rules! decl_either {473 ($($name: ident, $($id: ident)*);*) => {$(474 #[derive(Clone)]475 pub enum $name<$($id),*> {476 $($id($id)),*477 }478 impl<$($id),*> Typed for $name<$($id),*>479 where480 $($id: Typed,)*481 {482 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);483484 fn into_untyped(value: Self) -> Result<Val> {485 match value {$(486 $name::$id(v) => $id::into_untyped(v)487 ),*}488 }489490 fn from_untyped(value: Val) -> Result<Self> {491 $(492 if $id::TYPE.check(&value).is_ok() {493 $id::from_untyped(value).map(Self::$id)494 } else495 )* {496 <Self as Typed>::TYPE.check(&value)?;497 unreachable!()498 }499 }500 }501 )*}502}503decl_either!(504 Either1, A;505 Either2, A B;506 Either3, A B C;507 Either4, A B C D;508 Either5, A B C D E;509 Either6, A B C D E F;510 Either7, A B C D E F G511);512#[macro_export]513macro_rules! Either {514 ($a:ty) => {Either1<$a>};515 ($a:ty, $b:ty) => {Either2<$a, $b>};516 ($a:ty, $b:ty, $c:ty) => {Either3<$a, $b, $c>};517 ($a:ty, $b:ty, $c:ty, $d:ty) => {Either4<$a, $b, $c, $d>};518 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {Either5<$a, $b, $c, $d, $e>};519 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {Either6<$a, $b, $c, $d, $e, $f>};520 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {Either7<$a, $b, $c, $d, $e, $f, $g>};521}522pub use Either;523524pub type MyType = Either![u32, f64, String];525526impl Typed for ArrValue {527 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);528529 fn into_untyped(value: Self) -> Result<Val> {530 Ok(Val::Arr(value))531 }532533 fn from_untyped(value: Val) -> Result<Self> {534 <Self as Typed>::TYPE.check(&value)?;535 match value {536 Val::Arr(a) => Ok(a),537 _ => unreachable!(),538 }539 }540}541542impl Typed for FuncVal {543 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);544545 fn into_untyped(value: Self) -> Result<Val> {546 Ok(Val::Func(value))547 }548549 fn from_untyped(value: Val) -> Result<Self> {550 <Self as Typed>::TYPE.check(&value)?;551 match value {552 Val::Func(a) => Ok(a),553 _ => unreachable!(),554 }555 }556}557558impl Typed for Cc<FuncDesc> {559 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);560561 fn into_untyped(value: Self) -> Result<Val> {562 Ok(Val::Func(FuncVal::Normal(value)))563 }564565 fn from_untyped(value: Val) -> Result<Self> {566 <Self as Typed>::TYPE.check(&value)?;567 match value {568 Val::Func(FuncVal::Normal(desc)) => Ok(desc),569 Val::Func(_) => bail!("expected normal function, not builtin"),570 _ => unreachable!(),571 }572 }573}574575impl Typed for ObjValue {576 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);577578 fn into_untyped(value: Self) -> Result<Val> {579 Ok(Val::Obj(value))580 }581582 fn from_untyped(value: Val) -> Result<Self> {583 <Self as Typed>::TYPE.check(&value)?;584 match value {585 Val::Obj(a) => Ok(a),586 _ => unreachable!(),587 }588 }589}590591impl Typed for bool {592 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);593594 fn into_untyped(value: Self) -> Result<Val> {595 Ok(Val::Bool(value))596 }597598 fn from_untyped(value: Val) -> Result<Self> {599 <Self as Typed>::TYPE.check(&value)?;600 match value {601 Val::Bool(a) => Ok(a),602 _ => unreachable!(),603 }604 }605}606impl Typed for IndexableVal {607 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[608 &ComplexValType::Simple(ValType::Arr),609 &ComplexValType::Simple(ValType::Str),610 ]);611612 fn into_untyped(value: Self) -> Result<Val> {613 match value {614 IndexableVal::Str(s) => Ok(Val::string(s)),615 IndexableVal::Arr(a) => Ok(Val::Arr(a)),616 }617 }618619 fn from_untyped(value: Val) -> Result<Self> {620 <Self as Typed>::TYPE.check(&value)?;621 value.into_indexable()622 }623}624625pub struct Null;626impl Typed for Null {627 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);628629 fn into_untyped(_: Self) -> Result<Val> {630 Ok(Val::Null)631 }632633 fn from_untyped(value: Val) -> Result<Self> {634 <Self as Typed>::TYPE.check(&value)?;635 Ok(Self)636 }637}638639pub struct NativeFn<D: NativeDesc>(D::Value);640impl<D: NativeDesc> Deref for NativeFn<D> {641 type Target = D::Value;642643 fn deref(&self) -> &Self::Target {644 &self.0645 }646}647impl<D: NativeDesc> Typed for NativeFn<D> {648 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);649650 fn into_untyped(_typed: Self) -> Result<Val> {651 bail!("can only convert functions from jsonnet to native")652 }653654 fn from_untyped(untyped: Val) -> Result<Self> {655 Ok(Self(656 untyped657 .as_func()658 .expect("shape is checked")659 .into_native::<D>(),660 ))661 }662}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())))
}