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.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.rsdiffbeforeafterboth1use std::{2 cell::RefCell,3 fmt::{self, Debug, Display},4 mem::replace,5 rc::Rc,6};78use jrsonnet_gcmodule::{Cc, Trace};9use jrsonnet_interner::IStr;10use jrsonnet_types::ValType;1112pub use crate::arr::{ArrValue, ArrayLike};13use crate::{14 bail,15 error::{Error, ErrorKind::*},16 function::FuncVal,17 gc::{GcHashMap, TraceBox},18 manifest::{ManifestFormat, ToStringFormat},19 tb,20 typed::BoundedUsize,21 ObjValue, Result, Unbound, WeakObjValue,22};2324pub trait ThunkValue: Trace {25 type Output;26 fn get(self: Box<Self>) -> Result<Self::Output>;27}2829#[derive(Trace)]30enum ThunkInner<T: Trace> {31 Computed(T),32 Errored(Error),33 Waiting(TraceBox<dyn ThunkValue<Output = T>>),34 Pending,35}3637/// Lazily evaluated value38#[allow(clippy::module_name_repetitions)]39#[derive(Clone, Trace)]40pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);4142impl<T: Trace> Thunk<T> {43 pub fn evaluated(val: T) -> Self {44 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))45 }46 pub fn new(f: impl ThunkValue<Output = T> + 'static) -> Self {47 Self(Cc::new(RefCell::new(ThunkInner::Waiting(tb!(f)))))48 }49 pub fn errored(e: Error) -> Self {50 Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))51 }52 pub fn result(res: Result<T, Error>) -> Self {53 match res {54 Ok(o) => Self::evaluated(o),55 Err(e) => Self::errored(e),56 }57 }58}5960impl<T> Thunk<T>61where62 T: Clone + Trace,63{64 pub fn force(&self) -> Result<()> {65 self.evaluate()?;66 Ok(())67 }6869 /// Evaluate thunk, or return cached value70 ///71 /// # Errors72 ///73 /// - Lazy value evaluation returned error74 /// - This method was called during inner value evaluation75 pub fn evaluate(&self) -> Result<T> {76 match &*self.0.borrow() {77 ThunkInner::Computed(v) => return Ok(v.clone()),78 ThunkInner::Errored(e) => return Err(e.clone()),79 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),80 ThunkInner::Waiting(..) => (),81 };82 let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)83 else {84 unreachable!();85 };86 let new_value = match value.0.get() {87 Ok(v) => v,88 Err(e) => {89 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());90 return Err(e);91 }92 };93 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());94 Ok(new_value)95 }96}9798pub trait ThunkMapper<Input>: Trace {99 type Output;100 fn map(self, from: Input) -> Result<Self::Output>;101}102impl<Input> Thunk<Input>103where104 Input: Trace + Clone,105{106 pub fn map<M>(self, mapper: M) -> Thunk<M::Output>107 where108 M: ThunkMapper<Input>,109 M::Output: Trace,110 {111 #[derive(Trace)]112 struct Mapped<Input: Trace, Mapper: Trace> {113 inner: Thunk<Input>,114 mapper: Mapper,115 }116 impl<Input, Mapper> ThunkValue for Mapped<Input, Mapper>117 where118 Input: Trace + Clone,119 Mapper: ThunkMapper<Input>,120 {121 type Output = Mapper::Output;122123 fn get(self: Box<Self>) -> Result<Self::Output> {124 let value = self.inner.evaluate()?;125 let mapped = self.mapper.map(value)?;126 Ok(mapped)127 }128 }129130 Thunk::new(Mapped::<Input, M> {131 inner: self,132 mapper,133 })134 }135}136137impl<T: Trace> From<Result<T>> for Thunk<T> {138 fn from(value: Result<T>) -> Self {139 match value {140 Ok(o) => Self::evaluated(o),141 Err(e) => Self::errored(e),142 }143 }144}145146impl<T: Trace + Default> Default for Thunk<T> {147 fn default() -> Self {148 Self::evaluated(T::default())149 }150}151152type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);153154#[derive(Trace, Clone)]155pub struct CachedUnbound<I, T>156where157 I: Unbound<Bound = T>,158 T: Trace,159{160 cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,161 value: I,162}163impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {164 pub fn new(value: I) -> Self {165 Self {166 cache: Cc::new(RefCell::new(GcHashMap::new())),167 value,168 }169 }170}171impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {172 type Bound = T;173 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {174 let cache_key = (175 sup.as_ref().map(|s| s.clone().downgrade()),176 this.as_ref().map(|t| t.clone().downgrade()),177 );178 {179 if let Some(t) = self.cache.borrow().get(&cache_key) {180 return Ok(t.clone());181 }182 }183 let bound = self.value.bind(sup, this)?;184185 {186 let mut cache = self.cache.borrow_mut();187 cache.insert(cache_key, bound.clone());188 }189190 Ok(bound)191 }192}193194impl<T: Debug + Trace> Debug for Thunk<T> {195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {196 write!(f, "Lazy")197 }198}199impl<T: Trace> PartialEq for Thunk<T> {200 fn eq(&self, other: &Self) -> bool {201 Cc::ptr_eq(&self.0, &other.0)202 }203}204205/// Represents a Jsonnet value, which can be sliced or indexed (string or array).206#[allow(clippy::module_name_repetitions)]207pub enum IndexableVal {208 /// String.209 Str(IStr),210 /// Array.211 Arr(ArrValue),212}213impl IndexableVal {214 pub fn to_array(self) -> ArrValue {215 match self {216 IndexableVal::Str(s) => ArrValue::chars(s.chars()),217 IndexableVal::Arr(arr) => arr,218 }219 }220 /// Slice the value.221 ///222 /// # Implementation223 ///224 /// For strings, will create a copy of specified interval.225 ///226 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.227 pub fn slice(228 self,229 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,230 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,231 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,232 ) -> Result<Self> {233 match &self {234 IndexableVal::Str(s) => {235 let index = index.as_deref().copied().unwrap_or(0);236 let end = end.as_deref().copied().unwrap_or(usize::MAX);237 let step = step.as_deref().copied().unwrap_or(1);238239 if index >= end {240 return Ok(Self::Str("".into()));241 }242243 Ok(Self::Str(244 (s.chars()245 .skip(index)246 .take(end - index)247 .step_by(step)248 .collect::<String>())249 .into(),250 ))251 }252 IndexableVal::Arr(arr) => {253 let index = index.as_deref().copied().unwrap_or(0);254 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());255 let step = step.as_deref().copied().unwrap_or(1);256257 if index >= end {258 return Ok(Self::Arr(ArrValue::empty()));259 }260261 Ok(Self::Arr(262 arr.clone()263 .slice(Some(index), Some(end), Some(step))264 .expect("arguments checked"),265 ))266 }267 }268 }269}270271#[derive(Debug, Clone, Trace)]272pub enum StrValue {273 Flat(IStr),274 Tree(Rc<(StrValue, StrValue, usize)>),275}276impl StrValue {277 pub fn concat(a: StrValue, b: StrValue) -> Self {278 // TODO: benchmark for an optimal value, currently just a arbitrary choice279 const STRING_EXTEND_THRESHOLD: usize = 100;280281 if a.is_empty() {282 b283 } else if b.is_empty() {284 a285 } else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {286 Self::Flat(format!("{a}{b}").into())287 } else {288 let len = a.len() + b.len();289 Self::Tree(Rc::new((a, b, len)))290 }291 }292 pub fn into_flat(self) -> IStr {293 #[cold]294 fn write_buf(s: &StrValue, out: &mut String) {295 match s {296 StrValue::Flat(f) => out.push_str(f),297 StrValue::Tree(t) => {298 write_buf(&t.0, out);299 write_buf(&t.1, out);300 }301 }302 }303 match self {304 StrValue::Flat(f) => f,305 StrValue::Tree(_) => {306 let mut buf = String::with_capacity(self.len());307 write_buf(&self, &mut buf);308 buf.into()309 }310 }311 }312 pub fn len(&self) -> usize {313 match self {314 StrValue::Flat(v) => v.len(),315 StrValue::Tree(t) => t.2,316 }317 }318 pub fn is_empty(&self) -> bool {319 match self {320 Self::Flat(v) => v.is_empty(),321 // Can't create non-flat empty string322 Self::Tree(_) => false,323 }324 }325}326impl From<&str> for StrValue {327 fn from(value: &str) -> Self {328 Self::Flat(value.into())329 }330}331impl From<String> for StrValue {332 fn from(value: String) -> Self {333 Self::Flat(value.into())334 }335}336impl From<IStr> for StrValue {337 fn from(value: IStr) -> Self {338 Self::Flat(value)339 }340}341impl Display for StrValue {342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {343 match self {344 StrValue::Flat(v) => write!(f, "{v}"),345 StrValue::Tree(t) => {346 write!(f, "{}", t.0)?;347 write!(f, "{}", t.1)348 }349 }350 }351}352impl PartialEq for StrValue {353 fn eq(&self, other: &Self) -> bool {354 let a = self.clone().into_flat();355 let b = other.clone().into_flat();356 a == b357 }358}359impl Eq for StrValue {}360impl PartialOrd for StrValue {361 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {362 Some(self.cmp(other))363 }364}365impl Ord for StrValue {366 fn cmp(&self, other: &Self) -> std::cmp::Ordering {367 let a = self.clone().into_flat();368 let b = other.clone().into_flat();369 a.cmp(&b)370 }371}372373/// Represents any valid Jsonnet value.374#[derive(Debug, Clone, Trace, Default)]375pub enum Val {376 /// Represents a Jsonnet boolean.377 Bool(bool),378 /// Represents a Jsonnet null value.379 #[default]380 Null,381 /// Represents a Jsonnet string.382 Str(StrValue),383 /// Represents a Jsonnet number.384 /// Should be finite, and not NaN385 /// This restriction isn't enforced by enum, as enum field can't be marked as private386 Num(f64),387 /// Experimental bigint388 #[cfg(feature = "exp-bigint")]389 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),390 /// Represents a Jsonnet array.391 Arr(ArrValue),392 /// Represents a Jsonnet object.393 Obj(ObjValue),394 /// Represents a Jsonnet function.395 Func(FuncVal),396}397398#[cfg(target_pointer_width = "64")]399static_assertions::assert_eq_size!(Val, [u8; 24]);400401impl From<IndexableVal> for Val {402 fn from(v: IndexableVal) -> Self {403 match v {404 IndexableVal::Str(s) => Self::Str(StrValue::Flat(s)),405 IndexableVal::Arr(a) => Self::Arr(a),406 }407 }408}409410impl Val {411 pub const fn as_bool(&self) -> Option<bool> {412 match self {413 Self::Bool(v) => Some(*v),414 _ => None,415 }416 }417 pub const fn as_null(&self) -> Option<()> {418 match self {419 Self::Null => Some(()),420 _ => None,421 }422 }423 pub fn as_str(&self) -> Option<IStr> {424 match self {425 Self::Str(s) => Some(s.clone().into_flat()),426 _ => None,427 }428 }429 pub const fn as_num(&self) -> Option<f64> {430 match self {431 Self::Num(n) => Some(*n),432 _ => None,433 }434 }435 pub fn as_arr(&self) -> Option<ArrValue> {436 match self {437 Self::Arr(a) => Some(a.clone()),438 _ => None,439 }440 }441 pub fn as_obj(&self) -> Option<ObjValue> {442 match self {443 Self::Obj(o) => Some(o.clone()),444 _ => None,445 }446 }447 pub fn as_func(&self) -> Option<FuncVal> {448 match self {449 Self::Func(f) => Some(f.clone()),450 _ => None,451 }452 }453454 /// Creates `Val::Num` after checking for numeric overflow.455 /// As numbers are `f64`, we can just check for their finity.456 pub fn new_checked_num(num: f64) -> Result<Self> {457 if num.is_finite() {458 Ok(Self::Num(num))459 } else {460 bail!("overflow")461 }462 }463464 pub const fn value_type(&self) -> ValType {465 match self {466 Self::Str(..) => ValType::Str,467 Self::Num(..) => ValType::Num,468 #[cfg(feature = "exp-bigint")]469 Self::BigInt(..) => ValType::BigInt,470 Self::Arr(..) => ValType::Arr,471 Self::Obj(..) => ValType::Obj,472 Self::Bool(_) => ValType::Bool,473 Self::Null => ValType::Null,474 Self::Func(..) => ValType::Func,475 }476 }477478 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {479 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {480 manifest.manifest(val.clone())481 }482 manifest_dyn(self, &format)483 }484485 pub fn to_string(&self) -> Result<IStr> {486 Ok(match self {487 Self::Bool(true) => "true".into(),488 Self::Bool(false) => "false".into(),489 Self::Null => "null".into(),490 Self::Str(s) => s.clone().into_flat(),491 _ => self.manifest(ToStringFormat).map(IStr::from)?,492 })493 }494495 pub fn into_indexable(self) -> Result<IndexableVal> {496 Ok(match self {497 Val::Str(s) => IndexableVal::Str(s.into_flat()),498 Val::Arr(arr) => IndexableVal::Arr(arr),499 _ => bail!(ValueIsNotIndexable(self.value_type())),500 })501 }502}503504const fn is_function_like(val: &Val) -> bool {505 matches!(val, Val::Func(_))506}507508/// Native implementation of `std.primitiveEquals`509pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {510 Ok(match (val_a, val_b) {511 (Val::Bool(a), Val::Bool(b)) => a == b,512 (Val::Null, Val::Null) => true,513 (Val::Str(a), Val::Str(b)) => a == b,514 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,515 #[cfg(feature = "exp-bigint")]516 (Val::BigInt(a), Val::BigInt(b)) => a == b,517 (Val::Arr(_), Val::Arr(_)) => {518 bail!("primitiveEquals operates on primitive types, got array")519 }520 (Val::Obj(_), Val::Obj(_)) => {521 bail!("primitiveEquals operates on primitive types, got object")522 }523 (a, b) if is_function_like(a) && is_function_like(b) => {524 bail!("cannot test equality of functions")525 }526 (_, _) => false,527 })528}529530/// Native implementation of `std.equals`531pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {532 if val_a.value_type() != val_b.value_type() {533 return Ok(false);534 }535 match (val_a, val_b) {536 (Val::Arr(a), Val::Arr(b)) => {537 if ArrValue::ptr_eq(a, b) {538 return Ok(true);539 }540 if a.len() != b.len() {541 return Ok(false);542 }543 for (a, b) in a.iter().zip(b.iter()) {544 if !equals(&a?, &b?)? {545 return Ok(false);546 }547 }548 Ok(true)549 }550 (Val::Obj(a), Val::Obj(b)) => {551 if ObjValue::ptr_eq(a, b) {552 return Ok(true);553 }554 let fields = a.fields(555 #[cfg(feature = "exp-preserve-order")]556 false,557 );558 if fields559 != b.fields(560 #[cfg(feature = "exp-preserve-order")]561 false,562 ) {563 return Ok(false);564 }565 for field in fields {566 if !equals(567 &a.get(field.clone())?.expect("field exists"),568 &b.get(field)?.expect("field exists"),569 )? {570 return Ok(false);571 }572 }573 Ok(true)574 }575 (a, b) => Ok(primitive_equals(a, b)?),576 }577}1use std::{2 cell::RefCell,3 fmt::{self, Debug, Display},4 mem::replace,5 rc::Rc,6};78use jrsonnet_gcmodule::{Cc, Trace};9use jrsonnet_interner::IStr;10use jrsonnet_types::ValType;1112pub use crate::arr::{ArrValue, ArrayLike};13use crate::{14 bail,15 error::{Error, ErrorKind::*},16 function::FuncVal,17 gc::{GcHashMap, TraceBox},18 manifest::{ManifestFormat, ToStringFormat},19 tb,20 typed::BoundedUsize,21 ObjValue, Result, Unbound, WeakObjValue,22};2324pub trait ThunkValue: Trace {25 type Output;26 fn get(self: Box<Self>) -> Result<Self::Output>;27}2829#[derive(Trace)]30enum ThunkInner<T: Trace> {31 Computed(T),32 Errored(Error),33 Waiting(TraceBox<dyn ThunkValue<Output = T>>),34 Pending,35}3637/// Lazily evaluated value38#[allow(clippy::module_name_repetitions)]39#[derive(Clone, Trace)]40pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);4142impl<T: Trace> Thunk<T> {43 pub fn evaluated(val: T) -> Self {44 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))45 }46 pub fn new(f: impl ThunkValue<Output = T> + 'static) -> Self {47 Self(Cc::new(RefCell::new(ThunkInner::Waiting(tb!(f)))))48 }49 pub fn errored(e: Error) -> Self {50 Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))51 }52 pub fn result(res: Result<T, Error>) -> Self {53 match res {54 Ok(o) => Self::evaluated(o),55 Err(e) => Self::errored(e),56 }57 }58}5960impl<T> Thunk<T>61where62 T: Clone + Trace,63{64 pub fn force(&self) -> Result<()> {65 self.evaluate()?;66 Ok(())67 }6869 /// Evaluate thunk, or return cached value70 ///71 /// # Errors72 ///73 /// - Lazy value evaluation returned error74 /// - This method was called during inner value evaluation75 pub fn evaluate(&self) -> Result<T> {76 match &*self.0.borrow() {77 ThunkInner::Computed(v) => return Ok(v.clone()),78 ThunkInner::Errored(e) => return Err(e.clone()),79 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),80 ThunkInner::Waiting(..) => (),81 };82 let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)83 else {84 unreachable!();85 };86 let new_value = match value.0.get() {87 Ok(v) => v,88 Err(e) => {89 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());90 return Err(e);91 }92 };93 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());94 Ok(new_value)95 }96}9798pub trait ThunkMapper<Input>: Trace {99 type Output;100 fn map(self, from: Input) -> Result<Self::Output>;101}102impl<Input> Thunk<Input>103where104 Input: Trace + Clone,105{106 pub fn map<M>(self, mapper: M) -> Thunk<M::Output>107 where108 M: ThunkMapper<Input>,109 M::Output: Trace,110 {111 #[derive(Trace)]112 struct Mapped<Input: Trace, Mapper: Trace> {113 inner: Thunk<Input>,114 mapper: Mapper,115 }116 impl<Input, Mapper> ThunkValue for Mapped<Input, Mapper>117 where118 Input: Trace + Clone,119 Mapper: ThunkMapper<Input>,120 {121 type Output = Mapper::Output;122123 fn get(self: Box<Self>) -> Result<Self::Output> {124 let value = self.inner.evaluate()?;125 let mapped = self.mapper.map(value)?;126 Ok(mapped)127 }128 }129130 Thunk::new(Mapped::<Input, M> {131 inner: self,132 mapper,133 })134 }135}136137impl<T: Trace> From<Result<T>> for Thunk<T> {138 fn from(value: Result<T>) -> Self {139 match value {140 Ok(o) => Self::evaluated(o),141 Err(e) => Self::errored(e),142 }143 }144}145impl<T, V: Trace> From<T> for Thunk<V>146where147 T: ThunkValue<Output = V>,148{149 fn from(value: T) -> Self {150 Thunk::new(value)151 }152}153154impl<T: Trace + Default> Default for Thunk<T> {155 fn default() -> Self {156 Self::evaluated(T::default())157 }158}159160type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);161162#[derive(Trace, Clone)]163pub struct CachedUnbound<I, T>164where165 I: Unbound<Bound = T>,166 T: Trace,167{168 cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,169 value: I,170}171impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {172 pub fn new(value: I) -> Self {173 Self {174 cache: Cc::new(RefCell::new(GcHashMap::new())),175 value,176 }177 }178}179impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {180 type Bound = T;181 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {182 let cache_key = (183 sup.as_ref().map(|s| s.clone().downgrade()),184 this.as_ref().map(|t| t.clone().downgrade()),185 );186 {187 if let Some(t) = self.cache.borrow().get(&cache_key) {188 return Ok(t.clone());189 }190 }191 let bound = self.value.bind(sup, this)?;192193 {194 let mut cache = self.cache.borrow_mut();195 cache.insert(cache_key, bound.clone());196 }197198 Ok(bound)199 }200}201202impl<T: Debug + Trace> Debug for Thunk<T> {203 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {204 write!(f, "Lazy")205 }206}207impl<T: Trace> PartialEq for Thunk<T> {208 fn eq(&self, other: &Self) -> bool {209 Cc::ptr_eq(&self.0, &other.0)210 }211}212213/// Represents a Jsonnet value, which can be sliced or indexed (string or array).214#[allow(clippy::module_name_repetitions)]215pub enum IndexableVal {216 /// String.217 Str(IStr),218 /// Array.219 Arr(ArrValue),220}221impl IndexableVal {222 pub fn to_array(self) -> ArrValue {223 match self {224 IndexableVal::Str(s) => ArrValue::chars(s.chars()),225 IndexableVal::Arr(arr) => arr,226 }227 }228 /// Slice the value.229 ///230 /// # Implementation231 ///232 /// For strings, will create a copy of specified interval.233 ///234 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.235 pub fn slice(236 self,237 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,238 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,239 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,240 ) -> Result<Self> {241 match &self {242 IndexableVal::Str(s) => {243 let index = index.as_deref().copied().unwrap_or(0);244 let end = end.as_deref().copied().unwrap_or(usize::MAX);245 let step = step.as_deref().copied().unwrap_or(1);246247 if index >= end {248 return Ok(Self::Str("".into()));249 }250251 Ok(Self::Str(252 (s.chars()253 .skip(index)254 .take(end - index)255 .step_by(step)256 .collect::<String>())257 .into(),258 ))259 }260 IndexableVal::Arr(arr) => {261 let index = index.as_deref().copied().unwrap_or(0);262 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());263 let step = step.as_deref().copied().unwrap_or(1);264265 if index >= end {266 return Ok(Self::Arr(ArrValue::empty()));267 }268269 Ok(Self::Arr(270 arr.clone()271 .slice(Some(index), Some(end), Some(step))272 .expect("arguments checked"),273 ))274 }275 }276 }277}278279#[derive(Debug, Clone, Trace)]280pub enum StrValue {281 Flat(IStr),282 Tree(Rc<(StrValue, StrValue, usize)>),283}284impl StrValue {285 pub fn concat(a: StrValue, b: StrValue) -> Self {286 // TODO: benchmark for an optimal value, currently just a arbitrary choice287 const STRING_EXTEND_THRESHOLD: usize = 100;288289 if a.is_empty() {290 b291 } else if b.is_empty() {292 a293 } else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {294 Self::Flat(format!("{a}{b}").into())295 } else {296 let len = a.len() + b.len();297 Self::Tree(Rc::new((a, b, len)))298 }299 }300 pub fn into_flat(self) -> IStr {301 #[cold]302 fn write_buf(s: &StrValue, out: &mut String) {303 match s {304 StrValue::Flat(f) => out.push_str(f),305 StrValue::Tree(t) => {306 write_buf(&t.0, out);307 write_buf(&t.1, out);308 }309 }310 }311 match self {312 StrValue::Flat(f) => f,313 StrValue::Tree(_) => {314 let mut buf = String::with_capacity(self.len());315 write_buf(&self, &mut buf);316 buf.into()317 }318 }319 }320 pub fn len(&self) -> usize {321 match self {322 StrValue::Flat(v) => v.len(),323 StrValue::Tree(t) => t.2,324 }325 }326 pub fn is_empty(&self) -> bool {327 match self {328 Self::Flat(v) => v.is_empty(),329 // Can't create non-flat empty string330 Self::Tree(_) => false,331 }332 }333}334impl<T> From<T> for StrValue335where336 IStr: From<T>,337{338 fn from(value: T) -> Self {339 Self::Flat(IStr::from(value))340 }341}342impl Display for StrValue {343 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {344 match self {345 StrValue::Flat(v) => write!(f, "{v}"),346 StrValue::Tree(t) => {347 write!(f, "{}", t.0)?;348 write!(f, "{}", t.1)349 }350 }351 }352}353impl PartialEq for StrValue {354 fn eq(&self, other: &Self) -> bool {355 let a = self.clone().into_flat();356 let b = other.clone().into_flat();357 a == b358 }359}360impl Eq for StrValue {}361impl PartialOrd for StrValue {362 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {363 Some(self.cmp(other))364 }365}366impl Ord for StrValue {367 fn cmp(&self, other: &Self) -> std::cmp::Ordering {368 let a = self.clone().into_flat();369 let b = other.clone().into_flat();370 a.cmp(&b)371 }372}373374/// Represents any valid Jsonnet value.375#[derive(Debug, Clone, Trace, Default)]376pub enum Val {377 /// Represents a Jsonnet boolean.378 Bool(bool),379 /// Represents a Jsonnet null value.380 #[default]381 Null,382 /// Represents a Jsonnet string.383 Str(StrValue),384 /// Represents a Jsonnet number.385 /// Should be finite, and not NaN386 /// This restriction isn't enforced by enum, as enum field can't be marked as private387 Num(f64),388 /// Experimental bigint389 #[cfg(feature = "exp-bigint")]390 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),391 /// Represents a Jsonnet array.392 Arr(ArrValue),393 /// Represents a Jsonnet object.394 Obj(ObjValue),395 /// Represents a Jsonnet function.396 Func(FuncVal),397}398399#[cfg(target_pointer_width = "64")]400static_assertions::assert_eq_size!(Val, [u8; 24]);401402impl From<IndexableVal> for Val {403 fn from(v: IndexableVal) -> Self {404 match v {405 IndexableVal::Str(s) => Self::string(s),406 IndexableVal::Arr(a) => Self::Arr(a),407 }408 }409}410411impl Val {412 pub const fn as_bool(&self) -> Option<bool> {413 match self {414 Self::Bool(v) => Some(*v),415 _ => None,416 }417 }418 pub const fn as_null(&self) -> Option<()> {419 match self {420 Self::Null => Some(()),421 _ => None,422 }423 }424 pub fn as_str(&self) -> Option<IStr> {425 match self {426 Self::Str(s) => Some(s.clone().into_flat()),427 _ => None,428 }429 }430 pub const fn as_num(&self) -> Option<f64> {431 match self {432 Self::Num(n) => Some(*n),433 _ => None,434 }435 }436 pub fn as_arr(&self) -> Option<ArrValue> {437 match self {438 Self::Arr(a) => Some(a.clone()),439 _ => None,440 }441 }442 pub fn as_obj(&self) -> Option<ObjValue> {443 match self {444 Self::Obj(o) => Some(o.clone()),445 _ => None,446 }447 }448 pub fn as_func(&self) -> Option<FuncVal> {449 match self {450 Self::Func(f) => Some(f.clone()),451 _ => None,452 }453 }454455 /// Creates `Val::Num` after checking for numeric overflow.456 /// As numbers are `f64`, we can just check for their finity.457 pub fn new_checked_num(num: f64) -> Result<Self> {458 if num.is_finite() {459 Ok(Self::Num(num))460 } else {461 bail!("overflow")462 }463 }464465 pub const fn value_type(&self) -> ValType {466 match self {467 Self::Str(..) => ValType::Str,468 Self::Num(..) => ValType::Num,469 #[cfg(feature = "exp-bigint")]470 Self::BigInt(..) => ValType::BigInt,471 Self::Arr(..) => ValType::Arr,472 Self::Obj(..) => ValType::Obj,473 Self::Bool(_) => ValType::Bool,474 Self::Null => ValType::Null,475 Self::Func(..) => ValType::Func,476 }477 }478479 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {480 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {481 manifest.manifest(val.clone())482 }483 manifest_dyn(self, &format)484 }485486 pub fn to_string(&self) -> Result<IStr> {487 Ok(match self {488 Self::Bool(true) => "true".into(),489 Self::Bool(false) => "false".into(),490 Self::Null => "null".into(),491 Self::Str(s) => s.clone().into_flat(),492 _ => self.manifest(ToStringFormat).map(IStr::from)?,493 })494 }495496 pub fn into_indexable(self) -> Result<IndexableVal> {497 Ok(match self {498 Val::Str(s) => IndexableVal::Str(s.into_flat()),499 Val::Arr(arr) => IndexableVal::Arr(arr),500 _ => bail!(ValueIsNotIndexable(self.value_type())),501 })502 }503504 pub fn function(function: impl Into<FuncVal>) -> Self {505 Self::Func(function.into())506 }507 pub fn string(string: impl Into<StrValue>) -> Self {508 Self::Str(string.into())509 }510}511512impl From<IStr> for Val {513 fn from(value: IStr) -> Self {514 Self::string(value)515 }516}517impl From<String> for Val {518 fn from(value: String) -> Self {519 Self::string(value)520 }521}522impl From<&str> for Val {523 fn from(value: &str) -> Self {524 Self::string(value)525 }526}527impl From<ObjValue> for Val {528 fn from(value: ObjValue) -> Self {529 Self::Obj(value)530 }531}532533const fn is_function_like(val: &Val) -> bool {534 matches!(val, Val::Func(_))535}536537/// Native implementation of `std.primitiveEquals`538pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {539 Ok(match (val_a, val_b) {540 (Val::Bool(a), Val::Bool(b)) => a == b,541 (Val::Null, Val::Null) => true,542 (Val::Str(a), Val::Str(b)) => a == b,543 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,544 #[cfg(feature = "exp-bigint")]545 (Val::BigInt(a), Val::BigInt(b)) => a == b,546 (Val::Arr(_), Val::Arr(_)) => {547 bail!("primitiveEquals operates on primitive types, got array")548 }549 (Val::Obj(_), Val::Obj(_)) => {550 bail!("primitiveEquals operates on primitive types, got object")551 }552 (a, b) if is_function_like(a) && is_function_like(b) => {553 bail!("cannot test equality of functions")554 }555 (_, _) => false,556 })557}558559/// Native implementation of `std.equals`560pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {561 if val_a.value_type() != val_b.value_type() {562 return Ok(false);563 }564 match (val_a, val_b) {565 (Val::Arr(a), Val::Arr(b)) => {566 if ArrValue::ptr_eq(a, b) {567 return Ok(true);568 }569 if a.len() != b.len() {570 return Ok(false);571 }572 for (a, b) in a.iter().zip(b.iter()) {573 if !equals(&a?, &b?)? {574 return Ok(false);575 }576 }577 Ok(true)578 }579 (Val::Obj(a), Val::Obj(b)) => {580 if ObjValue::ptr_eq(a, b) {581 return Ok(true);582 }583 let fields = a.fields(584 #[cfg(feature = "exp-preserve-order")]585 false,586 );587 if fields588 != b.fields(589 #[cfg(feature = "exp-preserve-order")]590 false,591 ) {592 return Ok(false);593 }594 for field in fields {595 if !equals(596 &a.get(field.clone())?.expect("field exists"),597 &b.get(field)?.expect("field exists"),598 )? {599 return Ok(false);600 }601 }602 Ok(true)603 }604 (a, b) => Ok(primitive_equals(a, b)?),605 }606}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())))
}