difftreelog
refactor turn Thunk structure around to reduce allocations
in: master
9 files changed
.gitignorediffbeforeafterboth--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,10 @@
.vscode
.direnv
+# Nix artifacts
+/result
+/result-*
+
cache
jsonnet-cpp
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -7,7 +7,7 @@
use super::ArrValue;
use crate::{
error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, typed::Typed,
- Context, Error, ObjValue, Result, Thunk, Val,
+ val::ThunkValue, Context, Error, ObjValue, Result, Thunk, Val,
};
pub trait ArrayLike: Any + Trace + Debug {
@@ -191,9 +191,25 @@
ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}
};
- let arr_thunk = self.clone();
- Some(Thunk!(move || {
- arr_thunk.get(index).transpose().expect("index checked")
+ #[derive(Trace)]
+ struct ExprArrThunk {
+ expr: ExprArray,
+ index: usize,
+ }
+ impl ThunkValue for ExprArrThunk {
+ type Output = Val;
+
+ fn get(&self) -> Result<Self::Output> {
+ self.expr
+ .get(self.index)
+ .transpose()
+ .expect("index checked")
+ }
+ }
+
+ Some(Thunk::new(ExprArrThunk {
+ expr: self.clone(),
+ index,
}))
}
fn get_cheap(&self, _index: usize) -> Option<Val> {
@@ -484,9 +500,22 @@
ArrayThunk::Waiting(()) | ArrayThunk::Pending => {}
};
- let arr_thunk = self.clone();
- Some(Thunk!(move || {
- arr_thunk.get(index).transpose().expect("index checked")
+ #[derive(Trace)]
+ struct MappedArrayThunk<const WITH_INDEX: bool> {
+ arr: MappedArray<WITH_INDEX>,
+ index: usize,
+ }
+ impl<const WITH_INDEX: bool> ThunkValue for MappedArrayThunk<WITH_INDEX> {
+ type Output = Val;
+
+ fn get(&self) -> Result<Self::Output> {
+ self.arr.get(self.index).transpose().expect("index checked")
+ }
+ }
+
+ Some(Thunk::new(MappedArrayThunk {
+ arr: self.clone(),
+ index,
}))
}
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -40,8 +40,9 @@
impl<T: Trace + Clone> ThunkValue for Pending<T> {
type Output = T;
- fn get(self: Box<Self>) -> Result<Self::Output> {
+ fn get(&self) -> Result<Self::Output> {
let Some(value) = self.0.get() else {
+ // TODO: Other error?
bail!(InfiniteRecursionDetected);
};
Ok(value.clone())
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -23,7 +23,7 @@
gc::WithCapacityExt as _,
identity_hash, in_frame,
operator::evaluate_add_op,
- val::ArrValue,
+ val::{ArrValue, ThunkValue},
CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
};
@@ -753,13 +753,45 @@
if !self.has_field_ex(key.clone(), true) {
return None;
}
- let obj = self.clone();
+ #[derive(Trace)]
+ struct ObjFieldThunk {
+ obj: ObjValue,
+ key: IStr,
+ }
+ impl ThunkValue for ObjFieldThunk {
+ type Output = Val;
- Some(Thunk!(move || Ok(obj.get(key)?.expect("field exists"))))
+ fn get(&self) -> Result<Self::Output> {
+ self.obj
+ .get(self.key.clone())
+ .transpose()
+ .expect("field existence checked")
+ }
+ }
+
+ Some(Thunk::new(ObjFieldThunk {
+ obj: self.clone(),
+ key,
+ }))
}
pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {
- let obj = self.clone();
- Thunk!(move || obj.get_or_bail(key))
+ #[derive(Trace)]
+ struct ObjFieldThunk {
+ obj: ObjValue,
+ key: IStr,
+ }
+ impl ThunkValue for ObjFieldThunk {
+ type Output = Val;
+
+ fn get(&self) -> Result<Self::Output> {
+ self.obj.get_or_bail(self.key.clone())
+ }
+ }
+
+ Thunk::new(ObjFieldThunk {
+ obj: self.clone(),
+ key,
+ })
}
pub fn ptr_eq(a: &Self, b: &Self) -> bool {
Cc::ptr_eq(&a.0, &b.0)
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use std::{2 cell::RefCell,3 cmp::Ordering,4 fmt::{self, Debug, Display},5 mem::replace,6 num::NonZeroU32,7 ops::Deref,8 rc::Rc,9};1011use jrsonnet_gcmodule::{Acyclic, Cc, Trace, TraceBox};12use jrsonnet_interner::IStr;13pub use jrsonnet_macros::Thunk;14use jrsonnet_types::ValType;15use rustc_hash::FxHashMap;16use thiserror::Error;1718pub use crate::arr::{ArrValue, ArrayLike};19use crate::{20 bail,21 error::{Error, ErrorKind::*},22 function::FuncVal,23 gc::WithCapacityExt as _,24 manifest::{ManifestFormat, ToStringFormat},25 typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},26 ObjValue, Result, SupThis, Unbound, WeakSupThis,27};2829pub trait ThunkValue: Trace {30 type Output;31 fn get(self: Box<Self>) -> Result<Self::Output>;32}3334#[derive(Trace)]35pub struct ThunkValueClosure<D: Trace, O: 'static> {36 env: D,37 // Carries no data, as it is not a real closure, all the38 // captured environment is stored in `env` field.39 #[trace(skip)]40 closure: fn(D) -> Result<O>,41}42impl<D: Trace, O: 'static> ThunkValueClosure<D, O> {43 pub fn new(env: D, closure: fn(D) -> Result<O>) -> Self {44 Self { env, closure }45 }46}47impl<D: Trace, O: 'static> ThunkValue for ThunkValueClosure<D, O> {48 type Output = O;4950 fn get(self: Box<Self>) -> Result<Self::Output> {51 (self.closure)(self.env)52 }53}5455#[derive(Trace)]56enum ThunkInner<T: Trace> {57 Computed(T),58 Errored(Error),59 Waiting(TraceBox<dyn ThunkValue<Output = T>>),60 Pending,61}6263/// Lazily evaluated value64#[allow(clippy::module_name_repetitions)]65#[derive(Clone, Trace)]66pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);6768impl<T: Trace> Thunk<T> {69 pub fn evaluated(val: T) -> Self {70 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))71 }72 pub fn new(f: impl ThunkValue<Output = T> + 'static) -> Self {73 Self(Cc::new(RefCell::new(ThunkInner::Waiting(TraceBox(74 Box::new(f),75 )))))76 }77 pub fn errored(e: Error) -> Self {78 Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))79 }80 pub fn result(res: Result<T, Error>) -> Self {81 match res {82 Ok(o) => Self::evaluated(o),83 Err(e) => Self::errored(e),84 }85 }86}8788impl<T> Thunk<T>89where90 T: Clone + Trace,91{92 pub fn force(&self) -> Result<()> {93 self.evaluate()?;94 Ok(())95 }9697 /// Evaluate thunk, or return cached value98 ///99 /// # Errors100 ///101 /// - Lazy value evaluation returned error102 /// - This method was called during inner value evaluation103 pub fn evaluate(&self) -> Result<T> {104 match &*self.0.borrow() {105 ThunkInner::Computed(v) => return Ok(v.clone()),106 ThunkInner::Errored(e) => return Err(e.clone()),107 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),108 ThunkInner::Waiting(..) => (),109 };110 let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)111 else {112 unreachable!();113 };114 let new_value = match value.0.get() {115 Ok(v) => v,116 Err(e) => {117 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());118 return Err(e);119 }120 };121 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());122 Ok(new_value)123 }124}125126pub trait ThunkMapper<Input>: Trace {127 type Output;128 fn map(self, from: Input) -> Result<Self::Output>;129}130impl<Input> Thunk<Input>131where132 Input: Trace + Clone,133{134 pub fn map<M>(self, mapper: M) -> Thunk<M::Output>135 where136 M: ThunkMapper<Input>,137 M::Output: Trace,138 {139 let inner = self;140 Thunk!(move || {141 let value = inner.evaluate()?;142 let mapped = mapper.map(value)?;143 Ok(mapped)144 })145 }146}147148impl<T: Trace> From<Result<T>> for Thunk<T> {149 fn from(value: Result<T>) -> Self {150 match value {151 Ok(o) => Self::evaluated(o),152 Err(e) => Self::errored(e),153 }154 }155}156impl<T, V: Trace> From<T> for Thunk<V>157where158 T: ThunkValue<Output = V>,159{160 fn from(value: T) -> Self {161 Self::new(value)162 }163}164165impl<T: Trace + Default> Default for Thunk<T> {166 fn default() -> Self {167 Self::evaluated(T::default())168 }169}170171#[derive(Trace, Clone)]172pub struct CachedUnbound<I, T>173where174 I: Unbound<Bound = T>,175 T: Trace,176{177 cache: Cc<RefCell<FxHashMap<WeakSupThis, T>>>,178 value: I,179}180impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {181 pub fn new(value: I) -> Self {182 Self {183 cache: Cc::new(RefCell::new(FxHashMap::new())),184 value,185 }186 }187}188impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {189 type Bound = T;190 fn bind(&self, sup_this: SupThis) -> Result<T> {191 let cache_key = sup_this.clone().downgrade();192 {193 if let Some(t) = self.cache.borrow().get(&cache_key) {194 return Ok(t.clone());195 }196 }197 let bound = self.value.bind(sup_this)?;198199 {200 let mut cache = self.cache.borrow_mut();201 cache.insert(cache_key, bound.clone());202 }203204 Ok(bound)205 }206}207208impl<T: Debug + Trace> Debug for Thunk<T> {209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {210 write!(f, "Lazy")211 }212}213impl<T: Trace> PartialEq for Thunk<T> {214 fn eq(&self, other: &Self) -> bool {215 Cc::ptr_eq(&self.0, &other.0)216 }217}218219/// Represents a Jsonnet value, which can be sliced or indexed (string or array).220#[allow(clippy::module_name_repetitions)]221pub enum IndexableVal {222 /// String.223 Str(IStr),224 /// Array.225 Arr(ArrValue),226}227impl IndexableVal {228 pub fn is_empty(&self) -> bool {229 match self {230 Self::Str(s) => s.is_empty(),231 Self::Arr(s) => s.is_empty(),232 }233 }234235 pub fn to_array(self) -> ArrValue {236 match self {237 Self::Str(s) => ArrValue::chars(s.chars()),238 Self::Arr(arr) => arr,239 }240 }241 /// Slice the value.242 ///243 /// # Implementation244 ///245 /// For strings, will create a copy of specified interval.246 ///247 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.248 pub fn slice(249 self,250 index: Option<i32>,251 end: Option<i32>,252 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,253 ) -> Result<Self> {254 match &self {255 Self::Str(s) => {256 let mut computed_len = None;257 let mut get_len = || {258 computed_len.map_or_else(259 || {260 let len = s.chars().count();261 let _ = computed_len.insert(len);262 len263 },264 |len| len,265 )266 };267 let mut get_idx = |pos: Option<i32>, default| {268 match pos {269 Some(v) if v < 0 => get_len().saturating_sub((-v) as usize),270 // No need to clamp, as iterator interface is used271 Some(v) => v as usize,272 None => default,273 }274 };275276 let index = get_idx(index, 0);277 let end = get_idx(end, usize::MAX);278 let step = step.as_deref().copied().unwrap_or(1);279280 if index >= end {281 return Ok(Self::Str("".into()));282 }283284 Ok(Self::Str(285 (s.chars()286 .skip(index)287 .take(end - index)288 .step_by(step)289 .collect::<String>())290 .into(),291 ))292 }293 Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice(294 index,295 end,296 step.map(|v| NonZeroU32::new(v.value() as u32).expect("bounded != 0")),297 ))),298 }299 }300}301302#[derive(Debug, Clone, Acyclic)]303pub enum StrValue {304 Flat(IStr),305 Tree(Rc<(StrValue, StrValue, usize)>),306}307impl StrValue {308 pub fn concat(a: Self, b: Self) -> Self {309 // TODO: benchmark for an optimal value, currently just a arbitrary choice310 const STRING_EXTEND_THRESHOLD: usize = 100;311312 if a.is_empty() {313 b314 } else if b.is_empty() {315 a316 } else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {317 Self::Flat(format!("{a}{b}").into())318 } else {319 let len = a.len() + b.len();320 Self::Tree(Rc::new((a, b, len)))321 }322 }323 pub fn into_flat(self) -> IStr {324 #[cold]325 fn write_buf(s: &StrValue, out: &mut String) {326 match s {327 StrValue::Flat(f) => out.push_str(f),328 StrValue::Tree(t) => {329 write_buf(&t.0, out);330 write_buf(&t.1, out);331 }332 }333 }334 match self {335 Self::Flat(f) => f,336 Self::Tree(_) => {337 let mut buf = String::with_capacity(self.len());338 write_buf(&self, &mut buf);339 buf.into()340 }341 }342 }343 pub fn len(&self) -> usize {344 match self {345 Self::Flat(v) => v.len(),346 Self::Tree(t) => t.2,347 }348 }349 pub fn is_empty(&self) -> bool {350 match self {351 Self::Flat(v) => v.is_empty(),352 // Can't create non-flat empty string353 Self::Tree(_) => false,354 }355 }356}357impl<T> From<T> for StrValue358where359 IStr: From<T>,360{361 fn from(value: T) -> Self {362 Self::Flat(IStr::from(value))363 }364}365impl Display for StrValue {366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {367 match self {368 Self::Flat(v) => write!(f, "{v}"),369 Self::Tree(t) => {370 write!(f, "{}", t.0)?;371 write!(f, "{}", t.1)372 }373 }374 }375}376impl PartialEq for StrValue {377 // False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.378 #[allow(clippy::unconditional_recursion)]379 fn eq(&self, other: &Self) -> bool {380 let a = self.clone().into_flat();381 let b = other.clone().into_flat();382 a == b383 }384}385impl Eq for StrValue {}386impl PartialOrd for StrValue {387 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {388 Some(self.cmp(other))389 }390}391impl Ord for StrValue {392 fn cmp(&self, other: &Self) -> Ordering {393 let a = self.clone().into_flat();394 let b = other.clone().into_flat();395 a.cmp(&b)396 }397}398399/// Represents jsonnet number400/// Jsonnet numbers are finite f64, with NaNs disallowed401#[derive(Trace, Clone, Copy)]402#[repr(transparent)]403pub struct NumValue(f64);404impl NumValue {405 /// Creates a [`NumValue`], if value is finite and not NaN406 pub fn new(v: f64) -> Option<Self> {407 if !v.is_finite() {408 return None;409 }410 Some(Self(v))411 }412 #[inline]413 pub const fn get(&self) -> f64 {414 self.0415 }416 pub(crate) fn truncate_for_bitwise(&self) -> Result<i64> {417 if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {418 bail!("numberic value outside of safe integer range for bitwise operation");419 }420 Ok(self.0 as i64)421 }422}423impl PartialEq for NumValue {424 fn eq(&self, other: &Self) -> bool {425 self.0 == other.0426 }427}428impl Eq for NumValue {}429impl Ord for NumValue {430 #[inline]431 fn cmp(&self, other: &Self) -> Ordering {432 // Can't use `total_cmp`: its behavior for `-0` and `0`433 // is not following wanted.434 unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }435 }436}437impl PartialOrd for NumValue {438 #[inline]439 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {440 Some(self.cmp(other))441 }442}443impl Debug for NumValue {444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {445 Debug::fmt(&self.0, f)446 }447}448impl Display for NumValue {449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {450 Display::fmt(&self.0, f)451 }452}453impl Deref for NumValue {454 type Target = f64;455456 #[inline]457 fn deref(&self) -> &Self::Target {458 &self.0459 }460}461macro_rules! impl_num {462 ($($ty:ty),+) => {$(463 impl From<$ty> for NumValue {464 #[inline]465 fn from(value: $ty) -> Self {466 Self(value.into())467 }468 }469 )+};470}471impl_num!(i8, u8, i16, u16, i32, u32);472473#[derive(Clone, Copy, Debug, Error, Trace)]474pub enum ConvertNumValueError {475 #[error("overflow")]476 Overflow,477 #[error("underflow")]478 Underflow,479 #[error("non-finite")]480 NonFinite,481}482impl From<ConvertNumValueError> for Error {483 fn from(e: ConvertNumValueError) -> Self {484 Self::new(e.into())485 }486}487488macro_rules! impl_try_num {489 ($($ty:ty),+) => {$(490 impl TryFrom<$ty> for NumValue {491 type Error = ConvertNumValueError;492 #[inline]493 fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {494 let value = value as f64;495 if value < MIN_SAFE_INTEGER {496 return Err(ConvertNumValueError::Underflow)497 } else if value > MAX_SAFE_INTEGER {498 return Err(ConvertNumValueError::Overflow)499 }500 // Number is finite.501 Ok(Self(value))502 }503 }504 )+};505}506impl_try_num!(usize, isize, i64, u64);507508impl TryFrom<f64> for NumValue {509 type Error = ConvertNumValueError;510511 #[inline]512 fn try_from(value: f64) -> Result<Self, Self::Error> {513 Self::new(value).ok_or(ConvertNumValueError::NonFinite)514 }515}516impl TryFrom<f32> for NumValue {517 type Error = ConvertNumValueError;518519 #[inline]520 fn try_from(value: f32) -> Result<Self, Self::Error> {521 Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)522 }523}524525/// Represents any valid Jsonnet value.526#[derive(Debug, Clone, Trace, Default)]527pub enum Val {528 /// Represents a Jsonnet boolean.529 Bool(bool),530 /// Represents a Jsonnet null value.531 #[default]532 Null,533 /// Represents a Jsonnet string.534 Str(StrValue),535 /// Represents a Jsonnet number.536 /// Should be finite, and not NaN537 /// This restriction isn't enforced by enum, as enum field can't be marked as private538 Num(NumValue),539 /// Experimental bigint540 #[cfg(feature = "exp-bigint")]541 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),542 /// Represents a Jsonnet array.543 Arr(ArrValue),544 /// Represents a Jsonnet object.545 Obj(ObjValue),546 /// Represents a Jsonnet function.547 Func(FuncVal),548}549550#[cfg(target_pointer_width = "64")]551static_assertions::assert_eq_size!(Val, [u8; 24]);552553impl From<IndexableVal> for Val {554 fn from(v: IndexableVal) -> Self {555 match v {556 IndexableVal::Str(s) => Self::string(s),557 IndexableVal::Arr(a) => Self::Arr(a),558 }559 }560}561562impl Val {563 pub const fn as_bool(&self) -> Option<bool> {564 match self {565 Self::Bool(v) => Some(*v),566 _ => None,567 }568 }569 pub const fn as_null(&self) -> Option<()> {570 match self {571 Self::Null => Some(()),572 _ => None,573 }574 }575 pub fn as_str(&self) -> Option<IStr> {576 match self {577 Self::Str(s) => Some(s.clone().into_flat()),578 _ => None,579 }580 }581 pub const fn as_num(&self) -> Option<f64> {582 match self {583 Self::Num(n) => Some(n.get()),584 _ => None,585 }586 }587 #[cfg(feature = "exp-bigint")]588 pub fn as_bigint(&self) -> Option<num_bigint::BigInt> {589 match self {590 Self::BigInt(n) => Some(*n.clone()),591 _ => None,592 }593 }594 pub fn as_arr(&self) -> Option<ArrValue> {595 match self {596 Self::Arr(a) => Some(a.clone()),597 _ => None,598 }599 }600 pub fn as_obj(&self) -> Option<ObjValue> {601 match self {602 Self::Obj(o) => Some(o.clone()),603 _ => None,604 }605 }606 pub fn as_func(&self) -> Option<FuncVal> {607 match self {608 Self::Func(f) => Some(f.clone()),609 _ => None,610 }611 }612613 pub const fn value_type(&self) -> ValType {614 match self {615 Self::Str(..) => ValType::Str,616 Self::Num(..) => ValType::Num,617 #[cfg(feature = "exp-bigint")]618 Self::BigInt(..) => ValType::BigInt,619 Self::Arr(..) => ValType::Arr,620 Self::Obj(..) => ValType::Obj,621 Self::Bool(_) => ValType::Bool,622 Self::Null => ValType::Null,623 Self::Func(..) => ValType::Func,624 }625 }626627 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {628 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {629 manifest.manifest(val.clone())630 }631 manifest_dyn(self, &format)632 }633634 pub fn to_string(&self) -> Result<IStr> {635 Ok(match self {636 Self::Bool(true) => "true".into(),637 Self::Bool(false) => "false".into(),638 Self::Null => "null".into(),639 Self::Str(s) => s.clone().into_flat(),640 _ => self.manifest(ToStringFormat).map(IStr::from)?,641 })642 }643644 pub fn into_indexable(self) -> Result<IndexableVal> {645 Ok(match self {646 Self::Str(s) => IndexableVal::Str(s.into_flat()),647 Self::Arr(arr) => IndexableVal::Arr(arr),648 _ => bail!(ValueIsNotIndexable(self.value_type())),649 })650 }651652 pub fn function(function: impl Into<FuncVal>) -> Self {653 Self::Func(function.into())654 }655 pub fn string(string: impl Into<StrValue>) -> Self {656 Self::Str(string.into())657 }658 pub fn num(num: impl Into<NumValue>) -> Self {659 Self::Num(num.into())660 }661 pub fn try_num<V, E>(num: V) -> Result<Self, E>662 where663 NumValue: TryFrom<V, Error = E>,664 {665 Ok(Self::Num(num.try_into()?))666 }667}668669impl From<IStr> for Val {670 fn from(value: IStr) -> Self {671 Self::string(value)672 }673}674impl From<String> for Val {675 fn from(value: String) -> Self {676 Self::string(value)677 }678}679impl From<&str> for Val {680 fn from(value: &str) -> Self {681 Self::string(value)682 }683}684impl From<ObjValue> for Val {685 fn from(value: ObjValue) -> Self {686 Self::Obj(value)687 }688}689690const fn is_function_like(val: &Val) -> bool {691 matches!(val, Val::Func(_))692}693694/// Native implementation of `std.primitiveEquals`695pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {696 Ok(match (val_a, val_b) {697 (Val::Bool(a), Val::Bool(b)) => a == b,698 (Val::Null, Val::Null) => true,699 (Val::Str(a), Val::Str(b)) => a == b,700 (Val::Num(a), Val::Num(b)) => (a.get() - b.get()).abs() <= f64::EPSILON,701 #[cfg(feature = "exp-bigint")]702 (Val::BigInt(a), Val::BigInt(b)) => a == b,703 (Val::Arr(_), Val::Arr(_)) => {704 bail!("primitiveEquals operates on primitive types, got array")705 }706 (Val::Obj(_), Val::Obj(_)) => {707 bail!("primitiveEquals operates on primitive types, got object")708 }709 (a, b) if is_function_like(a) && is_function_like(b) => {710 bail!("cannot test equality of functions")711 }712 (_, _) => false,713 })714}715716/// Native implementation of `std.equals`717pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {718 if val_a.value_type() != val_b.value_type() {719 return Ok(false);720 }721 match (val_a, val_b) {722 (Val::Arr(a), Val::Arr(b)) => {723 if ArrValue::ptr_eq(a, b) {724 return Ok(true);725 }726 if a.len() != b.len() {727 return Ok(false);728 }729 for (a, b) in a.iter().zip(b.iter()) {730 if !equals(&a?, &b?)? {731 return Ok(false);732 }733 }734 Ok(true)735 }736 (Val::Obj(a), Val::Obj(b)) => {737 if ObjValue::ptr_eq(a, b) {738 return Ok(true);739 }740 let fields = a.fields(741 #[cfg(feature = "exp-preserve-order")]742 false,743 );744 if fields745 != b.fields(746 #[cfg(feature = "exp-preserve-order")]747 false,748 ) {749 return Ok(false);750 }751 for field in fields {752 if !equals(753 &a.get(field.clone())?.expect("field exists"),754 &b.get(field)?.expect("field exists"),755 )? {756 return Ok(false);757 }758 }759 Ok(true)760 }761 (a, b) => Ok(primitive_equals(a, b)?),762 }763}1use std::{2 cell::RefCell,3 cmp::Ordering,4 fmt::{self, Debug, Display},5 marker::PhantomData,6 mem::replace,7 num::NonZeroU32,8 ops::Deref,9 rc::Rc,10};1112use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace};13use jrsonnet_interner::IStr;14pub use jrsonnet_macros::Thunk;15use jrsonnet_types::ValType;16use rustc_hash::FxHashMap;17use thiserror::Error;1819pub use crate::arr::{ArrValue, ArrayLike};20use crate::{21 bail,22 error::{Error, ErrorKind::*},23 function::FuncVal,24 gc::WithCapacityExt as _,25 manifest::{ManifestFormat, ToStringFormat},26 typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},27 ObjValue, Result, SupThis, Unbound, WeakSupThis,28};2930pub trait ThunkValue: Trace {31 type Output;32 fn get(&self) -> Result<Self::Output>;33}3435#[derive(Trace)]36enum MemoizedClusureThunkInner<D: Trace, T: Trace> {37 Computed(T),38 Errored(Error),39 Waiting {40 env: D,41 // Carries no data, as it is not a real closure, all the42 // captured environment is stored in `env` field.43 #[trace(skip)]44 closure: fn(D) -> Result<T>,45 },46 Pending,47}48#[derive(Trace)]49pub struct MemoizedClosureThunk<D: Trace, T: Trace>(RefCell<MemoizedClusureThunkInner<D, T>>);50impl<D: Trace, T: Trace> MemoizedClosureThunk<D, T> {51 pub fn new(env: D, closure: fn(D) -> Result<T>) -> Self {52 Self(RefCell::new(MemoizedClusureThunkInner::Waiting {53 env,54 closure,55 }))56 }57}5859impl<D: Trace, T: Trace + Clone> ThunkValue for MemoizedClosureThunk<D, T> {60 type Output = T;6162 fn get(&self) -> Result<Self::Output> {63 match &*self.0.borrow() {64 MemoizedClusureThunkInner::Computed(v) => return Ok(v.clone()),65 MemoizedClusureThunkInner::Errored(e) => return Err(e.clone()),66 MemoizedClusureThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),67 MemoizedClusureThunkInner::Waiting { .. } => (),68 };69 let MemoizedClusureThunkInner::Waiting { env, closure } = replace(70 &mut *self.0.borrow_mut(),71 MemoizedClusureThunkInner::Pending,72 ) else {73 unreachable!();74 };75 let new_value = match closure(env) {76 Ok(v) => v,77 Err(e) => {78 *self.0.borrow_mut() = MemoizedClusureThunkInner::Errored(e.clone());79 return Err(e);80 }81 };82 *self.0.borrow_mut() = MemoizedClusureThunkInner::Computed(new_value.clone());83 Ok(new_value)84 }85}8687cc_dyn!(88 /// Lazily evaluated value89 #[derive(Clone)] Thunk<V: Trace>,90 ThunkValue<Output = V>,91 pub fn new() {...}92);9394impl<T: Trace> Thunk<T> {95 pub fn evaluated(val: T) -> Self96 where97 T: Clone,98 {99 #[derive(Trace)]100 struct EvaluatedThunk<T: Trace>(T);101 impl<T> ThunkValue for EvaluatedThunk<T>102 where103 T: Clone + Trace,104 {105 type Output = T;106107 fn get(&self) -> Result<Self::Output> {108 Ok(self.0.clone())109 }110 }111 Self::new(EvaluatedThunk(val))112 }113 pub fn errored(e: Error) -> Self {114 #[derive(Trace)]115 struct ErroredThunk<T: Trace>(Error, PhantomData<T>);116 impl<T> ThunkValue for ErroredThunk<T>117 where118 T: Trace,119 {120 type Output = T;121122 fn get(&self) -> Result<Self::Output> {123 Err(self.0.clone())124 }125 }126 Self::new(ErroredThunk(e, PhantomData))127 }128 pub fn result(res: Result<T, Error>) -> Self129 where130 T: Clone,131 {132 match res {133 Ok(o) => Self::evaluated(o),134 Err(e) => Self::errored(e),135 }136 }137}138139impl<T> Thunk<T>140where141 T: Clone + Trace,142{143 pub fn force(&self) -> Result<()> {144 self.evaluate()?;145 Ok(())146 }147148 /// Evaluate thunk, or return cached value149 ///150 /// # Errors151 ///152 /// - Lazy value evaluation returned error153 /// - This method was called during inner value evaluation154 pub fn evaluate(&self) -> Result<T> {155 self.0.get()156 }157}158159pub trait ThunkMapper<Input>: Trace {160 type Output;161 fn map(self, from: Input) -> Result<Self::Output>;162}163impl<Input> Thunk<Input>164where165 Input: Trace + Clone,166{167 pub fn map<M>(self, mapper: M) -> Thunk<M::Output>168 where169 M: ThunkMapper<Input>,170 M::Output: Trace + Clone,171 {172 let inner = self;173 Thunk!(move || {174 let value = inner.evaluate()?;175 let mapped = mapper.map(value)?;176 Ok(mapped)177 })178 }179}180181impl<T: Trace + Clone> From<Result<T>> for Thunk<T> {182 fn from(value: Result<T>) -> Self {183 match value {184 Ok(o) => Self::evaluated(o),185 Err(e) => Self::errored(e),186 }187 }188}189impl<T, V: Trace> From<T> for Thunk<V>190where191 T: ThunkValue<Output = V>,192{193 fn from(value: T) -> Self {194 Self::new(value)195 }196}197198impl<T: Trace + Default + Clone> Default for Thunk<T> {199 fn default() -> Self {200 Self::evaluated(T::default())201 }202}203204#[derive(Trace, Clone)]205pub struct CachedUnbound<I, T>206where207 I: Unbound<Bound = T>,208 T: Trace,209{210 cache: Cc<RefCell<FxHashMap<WeakSupThis, T>>>,211 value: I,212}213impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {214 pub fn new(value: I) -> Self {215 Self {216 cache: Cc::new(RefCell::new(FxHashMap::new())),217 value,218 }219 }220}221impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {222 type Bound = T;223 fn bind(&self, sup_this: SupThis) -> Result<T> {224 let cache_key = sup_this.clone().downgrade();225 {226 if let Some(t) = self.cache.borrow().get(&cache_key) {227 return Ok(t.clone());228 }229 }230 let bound = self.value.bind(sup_this)?;231232 {233 let mut cache = self.cache.borrow_mut();234 cache.insert(cache_key, bound.clone());235 }236237 Ok(bound)238 }239}240241impl<T: Debug + Trace> Debug for Thunk<T> {242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {243 write!(f, "Lazy")244 }245}246impl<T: Trace> PartialEq for Thunk<T> {247 fn eq(&self, other: &Self) -> bool {248 Cc::ptr_eq(&self.0, &other.0)249 }250}251252/// Represents a Jsonnet value, which can be sliced or indexed (string or array).253#[allow(clippy::module_name_repetitions)]254pub enum IndexableVal {255 /// String.256 Str(IStr),257 /// Array.258 Arr(ArrValue),259}260impl IndexableVal {261 pub fn is_empty(&self) -> bool {262 match self {263 Self::Str(s) => s.is_empty(),264 Self::Arr(s) => s.is_empty(),265 }266 }267268 pub fn to_array(self) -> ArrValue {269 match self {270 Self::Str(s) => ArrValue::chars(s.chars()),271 Self::Arr(arr) => arr,272 }273 }274 /// Slice the value.275 ///276 /// # Implementation277 ///278 /// For strings, will create a copy of specified interval.279 ///280 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.281 pub fn slice(282 self,283 index: Option<i32>,284 end: Option<i32>,285 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,286 ) -> Result<Self> {287 match &self {288 Self::Str(s) => {289 let mut computed_len = None;290 let mut get_len = || {291 computed_len.map_or_else(292 || {293 let len = s.chars().count();294 let _ = computed_len.insert(len);295 len296 },297 |len| len,298 )299 };300 let mut get_idx = |pos: Option<i32>, default| {301 match pos {302 Some(v) if v < 0 => get_len().saturating_sub((-v) as usize),303 // No need to clamp, as iterator interface is used304 Some(v) => v as usize,305 None => default,306 }307 };308309 let index = get_idx(index, 0);310 let end = get_idx(end, usize::MAX);311 let step = step.as_deref().copied().unwrap_or(1);312313 if index >= end {314 return Ok(Self::Str("".into()));315 }316317 Ok(Self::Str(318 (s.chars()319 .skip(index)320 .take(end - index)321 .step_by(step)322 .collect::<String>())323 .into(),324 ))325 }326 Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice(327 index,328 end,329 step.map(|v| NonZeroU32::new(v.value() as u32).expect("bounded != 0")),330 ))),331 }332 }333}334335#[derive(Debug, Clone, Acyclic)]336pub enum StrValue {337 Flat(IStr),338 Tree(Rc<(StrValue, StrValue, usize)>),339}340impl StrValue {341 pub fn concat(a: Self, b: Self) -> Self {342 // TODO: benchmark for an optimal value, currently just a arbitrary choice343 const STRING_EXTEND_THRESHOLD: usize = 100;344345 if a.is_empty() {346 b347 } else if b.is_empty() {348 a349 } else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {350 Self::Flat(format!("{a}{b}").into())351 } else {352 let len = a.len() + b.len();353 Self::Tree(Rc::new((a, b, len)))354 }355 }356 pub fn into_flat(self) -> IStr {357 #[cold]358 fn write_buf(s: &StrValue, out: &mut String) {359 match s {360 StrValue::Flat(f) => out.push_str(f),361 StrValue::Tree(t) => {362 write_buf(&t.0, out);363 write_buf(&t.1, out);364 }365 }366 }367 match self {368 Self::Flat(f) => f,369 Self::Tree(_) => {370 let mut buf = String::with_capacity(self.len());371 write_buf(&self, &mut buf);372 buf.into()373 }374 }375 }376 pub fn len(&self) -> usize {377 match self {378 Self::Flat(v) => v.len(),379 Self::Tree(t) => t.2,380 }381 }382 pub fn is_empty(&self) -> bool {383 match self {384 Self::Flat(v) => v.is_empty(),385 // Can't create non-flat empty string386 Self::Tree(_) => false,387 }388 }389}390impl<T> From<T> for StrValue391where392 IStr: From<T>,393{394 fn from(value: T) -> Self {395 Self::Flat(IStr::from(value))396 }397}398impl Display for StrValue {399 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {400 match self {401 Self::Flat(v) => write!(f, "{v}"),402 Self::Tree(t) => {403 write!(f, "{}", t.0)?;404 write!(f, "{}", t.1)405 }406 }407 }408}409impl PartialEq for StrValue {410 // False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.411 #[allow(clippy::unconditional_recursion)]412 fn eq(&self, other: &Self) -> bool {413 let a = self.clone().into_flat();414 let b = other.clone().into_flat();415 a == b416 }417}418impl Eq for StrValue {}419impl PartialOrd for StrValue {420 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {421 Some(self.cmp(other))422 }423}424impl Ord for StrValue {425 fn cmp(&self, other: &Self) -> Ordering {426 let a = self.clone().into_flat();427 let b = other.clone().into_flat();428 a.cmp(&b)429 }430}431432/// Represents jsonnet number433/// Jsonnet numbers are finite f64, with NaNs disallowed434#[derive(Trace, Clone, Copy)]435#[repr(transparent)]436pub struct NumValue(f64);437impl NumValue {438 /// Creates a [`NumValue`], if value is finite and not NaN439 pub fn new(v: f64) -> Option<Self> {440 if !v.is_finite() {441 return None;442 }443 Some(Self(v))444 }445 #[inline]446 pub const fn get(&self) -> f64 {447 self.0448 }449 pub(crate) fn truncate_for_bitwise(&self) -> Result<i64> {450 if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {451 bail!("numberic value outside of safe integer range for bitwise operation");452 }453 Ok(self.0 as i64)454 }455}456impl PartialEq for NumValue {457 fn eq(&self, other: &Self) -> bool {458 self.0 == other.0459 }460}461impl Eq for NumValue {}462impl Ord for NumValue {463 #[inline]464 fn cmp(&self, other: &Self) -> Ordering {465 // Can't use `total_cmp`: its behavior for `-0` and `0`466 // is not following wanted.467 unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }468 }469}470impl PartialOrd for NumValue {471 #[inline]472 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {473 Some(self.cmp(other))474 }475}476impl Debug for NumValue {477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {478 Debug::fmt(&self.0, f)479 }480}481impl Display for NumValue {482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {483 Display::fmt(&self.0, f)484 }485}486impl Deref for NumValue {487 type Target = f64;488489 #[inline]490 fn deref(&self) -> &Self::Target {491 &self.0492 }493}494macro_rules! impl_num {495 ($($ty:ty),+) => {$(496 impl From<$ty> for NumValue {497 #[inline]498 fn from(value: $ty) -> Self {499 Self(value.into())500 }501 }502 )+};503}504impl_num!(i8, u8, i16, u16, i32, u32);505506#[derive(Clone, Copy, Debug, Error, Trace)]507pub enum ConvertNumValueError {508 #[error("overflow")]509 Overflow,510 #[error("underflow")]511 Underflow,512 #[error("non-finite")]513 NonFinite,514}515impl From<ConvertNumValueError> for Error {516 fn from(e: ConvertNumValueError) -> Self {517 Self::new(e.into())518 }519}520521macro_rules! impl_try_num {522 ($($ty:ty),+) => {$(523 impl TryFrom<$ty> for NumValue {524 type Error = ConvertNumValueError;525 #[inline]526 fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {527 let value = value as f64;528 if value < MIN_SAFE_INTEGER {529 return Err(ConvertNumValueError::Underflow)530 } else if value > MAX_SAFE_INTEGER {531 return Err(ConvertNumValueError::Overflow)532 }533 // Number is finite.534 Ok(Self(value))535 }536 }537 )+};538}539impl_try_num!(usize, isize, i64, u64);540541impl TryFrom<f64> for NumValue {542 type Error = ConvertNumValueError;543544 #[inline]545 fn try_from(value: f64) -> Result<Self, Self::Error> {546 Self::new(value).ok_or(ConvertNumValueError::NonFinite)547 }548}549impl TryFrom<f32> for NumValue {550 type Error = ConvertNumValueError;551552 #[inline]553 fn try_from(value: f32) -> Result<Self, Self::Error> {554 Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)555 }556}557558/// Represents any valid Jsonnet value.559#[derive(Debug, Clone, Trace, Default)]560pub enum Val {561 /// Represents a Jsonnet boolean.562 Bool(bool),563 /// Represents a Jsonnet null value.564 #[default]565 Null,566 /// Represents a Jsonnet string.567 Str(StrValue),568 /// Represents a Jsonnet number.569 /// Should be finite, and not NaN570 /// This restriction isn't enforced by enum, as enum field can't be marked as private571 Num(NumValue),572 /// Experimental bigint573 #[cfg(feature = "exp-bigint")]574 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),575 /// Represents a Jsonnet array.576 Arr(ArrValue),577 /// Represents a Jsonnet object.578 Obj(ObjValue),579 /// Represents a Jsonnet function.580 Func(FuncVal),581}582583#[cfg(target_pointer_width = "64")]584static_assertions::assert_eq_size!(Val, [u8; 24]);585586impl From<IndexableVal> for Val {587 fn from(v: IndexableVal) -> Self {588 match v {589 IndexableVal::Str(s) => Self::string(s),590 IndexableVal::Arr(a) => Self::Arr(a),591 }592 }593}594595impl Val {596 pub const fn as_bool(&self) -> Option<bool> {597 match self {598 Self::Bool(v) => Some(*v),599 _ => None,600 }601 }602 pub const fn as_null(&self) -> Option<()> {603 match self {604 Self::Null => Some(()),605 _ => None,606 }607 }608 pub fn as_str(&self) -> Option<IStr> {609 match self {610 Self::Str(s) => Some(s.clone().into_flat()),611 _ => None,612 }613 }614 pub const fn as_num(&self) -> Option<f64> {615 match self {616 Self::Num(n) => Some(n.get()),617 _ => None,618 }619 }620 #[cfg(feature = "exp-bigint")]621 pub fn as_bigint(&self) -> Option<num_bigint::BigInt> {622 match self {623 Self::BigInt(n) => Some(*n.clone()),624 _ => None,625 }626 }627 pub fn as_arr(&self) -> Option<ArrValue> {628 match self {629 Self::Arr(a) => Some(a.clone()),630 _ => None,631 }632 }633 pub fn as_obj(&self) -> Option<ObjValue> {634 match self {635 Self::Obj(o) => Some(o.clone()),636 _ => None,637 }638 }639 pub fn as_func(&self) -> Option<FuncVal> {640 match self {641 Self::Func(f) => Some(f.clone()),642 _ => None,643 }644 }645646 pub const fn value_type(&self) -> ValType {647 match self {648 Self::Str(..) => ValType::Str,649 Self::Num(..) => ValType::Num,650 #[cfg(feature = "exp-bigint")]651 Self::BigInt(..) => ValType::BigInt,652 Self::Arr(..) => ValType::Arr,653 Self::Obj(..) => ValType::Obj,654 Self::Bool(_) => ValType::Bool,655 Self::Null => ValType::Null,656 Self::Func(..) => ValType::Func,657 }658 }659660 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {661 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {662 manifest.manifest(val.clone())663 }664 manifest_dyn(self, &format)665 }666667 pub fn to_string(&self) -> Result<IStr> {668 Ok(match self {669 Self::Bool(true) => "true".into(),670 Self::Bool(false) => "false".into(),671 Self::Null => "null".into(),672 Self::Str(s) => s.clone().into_flat(),673 _ => self.manifest(ToStringFormat).map(IStr::from)?,674 })675 }676677 pub fn into_indexable(self) -> Result<IndexableVal> {678 Ok(match self {679 Self::Str(s) => IndexableVal::Str(s.into_flat()),680 Self::Arr(arr) => IndexableVal::Arr(arr),681 _ => bail!(ValueIsNotIndexable(self.value_type())),682 })683 }684685 pub fn function(function: impl Into<FuncVal>) -> Self {686 Self::Func(function.into())687 }688 pub fn string(string: impl Into<StrValue>) -> Self {689 Self::Str(string.into())690 }691 pub fn num(num: impl Into<NumValue>) -> Self {692 Self::Num(num.into())693 }694 pub fn try_num<V, E>(num: V) -> Result<Self, E>695 where696 NumValue: TryFrom<V, Error = E>,697 {698 Ok(Self::Num(num.try_into()?))699 }700}701702impl From<IStr> for Val {703 fn from(value: IStr) -> Self {704 Self::string(value)705 }706}707impl From<String> for Val {708 fn from(value: String) -> Self {709 Self::string(value)710 }711}712impl From<&str> for Val {713 fn from(value: &str) -> Self {714 Self::string(value)715 }716}717impl From<ObjValue> for Val {718 fn from(value: ObjValue) -> Self {719 Self::Obj(value)720 }721}722723const fn is_function_like(val: &Val) -> bool {724 matches!(val, Val::Func(_))725}726727/// Native implementation of `std.primitiveEquals`728pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {729 Ok(match (val_a, val_b) {730 (Val::Bool(a), Val::Bool(b)) => a == b,731 (Val::Null, Val::Null) => true,732 (Val::Str(a), Val::Str(b)) => a == b,733 (Val::Num(a), Val::Num(b)) => (a.get() - b.get()).abs() <= f64::EPSILON,734 #[cfg(feature = "exp-bigint")]735 (Val::BigInt(a), Val::BigInt(b)) => a == b,736 (Val::Arr(_), Val::Arr(_)) => {737 bail!("primitiveEquals operates on primitive types, got array")738 }739 (Val::Obj(_), Val::Obj(_)) => {740 bail!("primitiveEquals operates on primitive types, got object")741 }742 (a, b) if is_function_like(a) && is_function_like(b) => {743 bail!("cannot test equality of functions")744 }745 (_, _) => false,746 })747}748749/// Native implementation of `std.equals`750pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {751 if val_a.value_type() != val_b.value_type() {752 return Ok(false);753 }754 match (val_a, val_b) {755 (Val::Arr(a), Val::Arr(b)) => {756 if ArrValue::ptr_eq(a, b) {757 return Ok(true);758 }759 if a.len() != b.len() {760 return Ok(false);761 }762 for (a, b) in a.iter().zip(b.iter()) {763 if !equals(&a?, &b?)? {764 return Ok(false);765 }766 }767 Ok(true)768 }769 (Val::Obj(a), Val::Obj(b)) => {770 if ObjValue::ptr_eq(a, b) {771 return Ok(true);772 }773 let fields = a.fields(774 #[cfg(feature = "exp-preserve-order")]775 false,776 );777 if fields778 != b.fields(779 #[cfg(feature = "exp-preserve-order")]780 false,781 ) {782 return Ok(false);783 }784 for field in fields {785 if !equals(786 &a.get(field.clone())?.expect("field exists"),787 &b.get(field)?.expect("field exists"),788 )? {789 return Ok(false);790 }791 }792 Ok(true)793 }794 (a, b) => Ok(primitive_equals(a, b)?),795 }796}crates/jrsonnet-formatter/src/comments.rsdiffbeforeafterboth--- a/crates/jrsonnet-formatter/src/comments.rs
+++ b/crates/jrsonnet-formatter/src/comments.rs
@@ -73,7 +73,10 @@
p!(out, str(" "));
}
p!(out, str("/* ") string(lines[0].trim().to_string()) str(" */"));
- if matches!(loc, CommentLocation::AboveItem | CommentLocation::EndOfItems) {
+ if matches!(
+ loc,
+ CommentLocation::AboveItem | CommentLocation::EndOfItems
+ ) {
p!(out, nl);
}
} else if !lines.is_empty() {
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -879,6 +879,6 @@
quote! {{
#move_check
#(#trace_check)*
- ::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::ThunkValueClosure::new(#env, #closure))
+ ::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::MemoizedClosureThunk::new(#env, #closure))
}}.into()
}
resultdiffbeforeafterboth--- a/result
+++ /dev/null
@@ -1 +0,0 @@
-/nix/store/nd6v7jksg1dqhpx4x4vqgy5ry1nkb9lk-jrsonnet-current
\ No newline at end of file
xtask/src/sourcegen/mod.rsdiffbeforeafterboth--- a/xtask/src/sourcegen/mod.rs
+++ b/xtask/src/sourcegen/mod.rs
@@ -203,49 +203,57 @@
});
let mut type_positions: HashMap<String, usize> = HashMap::new();
- let field_positions: Vec<_> = node.fields.iter().map(|field| {
- let ty_str = field.ty().to_string();
- let pos = *type_positions.get(&ty_str).unwrap_or(&0);
- type_positions.insert(ty_str, pos + 1);
- pos
- }).collect();
+ let field_positions: Vec<_> = node
+ .fields
+ .iter()
+ .map(|field| {
+ let ty_str = field.ty().to_string();
+ let pos = *type_positions.get(&ty_str).unwrap_or(&0);
+ type_positions.insert(ty_str, pos + 1);
+ pos
+ })
+ .collect();
- let methods = node.fields.iter().zip(field_positions.iter()).map(|(field, &pos)| {
- let method_name = field.method_name(kinds);
- let ty = field.ty();
+ let methods = node
+ .fields
+ .iter()
+ .zip(field_positions.iter())
+ .map(|(field, &pos)| {
+ let method_name = field.method_name(kinds);
+ let ty = field.ty();
- if field.is_many() {
- quote! {
- pub fn #method_name(&self) -> AstChildren<#ty> {
- support::children(&self.syntax)
+ if field.is_many() {
+ quote! {
+ pub fn #method_name(&self) -> AstChildren<#ty> {
+ support::children(&self.syntax)
+ }
}
- }
- } else if let Some(token_kind) = field.token_kind(kinds) {
- quote! {
- pub fn #method_name(&self) -> Option<#ty> {
- support::token(&self.syntax, #token_kind)
+ } else if let Some(token_kind) = field.token_kind(kinds) {
+ quote! {
+ pub fn #method_name(&self) -> Option<#ty> {
+ support::token(&self.syntax, #token_kind)
+ }
}
- }
- } else if field.is_token_enum(grammar) {
- quote! {
- pub fn #method_name(&self) -> Option<#ty> {
- support::token_child(&self.syntax)
+ } else if field.is_token_enum(grammar) {
+ quote! {
+ pub fn #method_name(&self) -> Option<#ty> {
+ support::token_child(&self.syntax)
+ }
}
- }
- } else if pos == 0 {
- quote! {
- pub fn #method_name(&self) -> Option<#ty> {
- support::children(&self.syntax).next()
+ } else if pos == 0 {
+ quote! {
+ pub fn #method_name(&self) -> Option<#ty> {
+ support::children(&self.syntax).next()
+ }
}
- }
- } else {
- quote! {
- pub fn #method_name(&self) -> Option<#ty> {
- support::children(&self.syntax).nth(#pos)
+ } else {
+ quote! {
+ pub fn #method_name(&self) -> Option<#ty> {
+ support::children(&self.syntax).nth(#pos)
+ }
}
}
- }
- });
+ });
(
quote! {
#[pretty_doc_comment_placeholder_workaround]