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}363738#[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 70 71 72 73 74 75 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}212213214#[allow(clippy::module_name_repetitions)]215pub enum IndexableVal {216 217 Str(IStr),218 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 229 230 231 232 233 234 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 287 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 330 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 355 #[allow(clippy::unconditional_recursion)]356 fn eq(&self, other: &Self) -> bool {357 let a = self.clone().into_flat();358 let b = other.clone().into_flat();359 a == b360 }361}362impl Eq for StrValue {}363impl PartialOrd for StrValue {364 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {365 Some(self.cmp(other))366 }367}368impl Ord for StrValue {369 fn cmp(&self, other: &Self) -> std::cmp::Ordering {370 let a = self.clone().into_flat();371 let b = other.clone().into_flat();372 a.cmp(&b)373 }374}375376377#[derive(Debug, Clone, Trace, Default)]378pub enum Val {379 380 Bool(bool),381 382 #[default]383 Null,384 385 Str(StrValue),386 387 388 389 Num(f64),390 391 #[cfg(feature = "exp-bigint")]392 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),393 394 Arr(ArrValue),395 396 Obj(ObjValue),397 398 Func(FuncVal),399}400401#[cfg(target_pointer_width = "64")]402static_assertions::assert_eq_size!(Val, [u8; 24]);403404impl From<IndexableVal> for Val {405 fn from(v: IndexableVal) -> Self {406 match v {407 IndexableVal::Str(s) => Self::string(s),408 IndexableVal::Arr(a) => Self::Arr(a),409 }410 }411}412413impl Val {414 pub const fn as_bool(&self) -> Option<bool> {415 match self {416 Self::Bool(v) => Some(*v),417 _ => None,418 }419 }420 pub const fn as_null(&self) -> Option<()> {421 match self {422 Self::Null => Some(()),423 _ => None,424 }425 }426 pub fn as_str(&self) -> Option<IStr> {427 match self {428 Self::Str(s) => Some(s.clone().into_flat()),429 _ => None,430 }431 }432 pub const fn as_num(&self) -> Option<f64> {433 match self {434 Self::Num(n) => Some(*n),435 _ => None,436 }437 }438 pub fn as_arr(&self) -> Option<ArrValue> {439 match self {440 Self::Arr(a) => Some(a.clone()),441 _ => None,442 }443 }444 pub fn as_obj(&self) -> Option<ObjValue> {445 match self {446 Self::Obj(o) => Some(o.clone()),447 _ => None,448 }449 }450 pub fn as_func(&self) -> Option<FuncVal> {451 match self {452 Self::Func(f) => Some(f.clone()),453 _ => None,454 }455 }456457 458 459 pub fn new_checked_num(num: f64) -> Result<Self> {460 if num.is_finite() {461 Ok(Self::Num(num))462 } else {463 bail!("overflow")464 }465 }466467 pub const fn value_type(&self) -> ValType {468 match self {469 Self::Str(..) => ValType::Str,470 Self::Num(..) => ValType::Num,471 #[cfg(feature = "exp-bigint")]472 Self::BigInt(..) => ValType::BigInt,473 Self::Arr(..) => ValType::Arr,474 Self::Obj(..) => ValType::Obj,475 Self::Bool(_) => ValType::Bool,476 Self::Null => ValType::Null,477 Self::Func(..) => ValType::Func,478 }479 }480481 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {482 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {483 manifest.manifest(val.clone())484 }485 manifest_dyn(self, &format)486 }487488 pub fn to_string(&self) -> Result<IStr> {489 Ok(match self {490 Self::Bool(true) => "true".into(),491 Self::Bool(false) => "false".into(),492 Self::Null => "null".into(),493 Self::Str(s) => s.clone().into_flat(),494 _ => self.manifest(ToStringFormat).map(IStr::from)?,495 })496 }497498 pub fn into_indexable(self) -> Result<IndexableVal> {499 Ok(match self {500 Val::Str(s) => IndexableVal::Str(s.into_flat()),501 Val::Arr(arr) => IndexableVal::Arr(arr),502 _ => bail!(ValueIsNotIndexable(self.value_type())),503 })504 }505506 pub fn function(function: impl Into<FuncVal>) -> Self {507 Self::Func(function.into())508 }509 pub fn string(string: impl Into<StrValue>) -> Self {510 Self::Str(string.into())511 }512}513514impl From<IStr> for Val {515 fn from(value: IStr) -> Self {516 Self::string(value)517 }518}519impl From<String> for Val {520 fn from(value: String) -> Self {521 Self::string(value)522 }523}524impl From<&str> for Val {525 fn from(value: &str) -> Self {526 Self::string(value)527 }528}529impl From<ObjValue> for Val {530 fn from(value: ObjValue) -> Self {531 Self::Obj(value)532 }533}534535const fn is_function_like(val: &Val) -> bool {536 matches!(val, Val::Func(_))537}538539540pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {541 Ok(match (val_a, val_b) {542 (Val::Bool(a), Val::Bool(b)) => a == b,543 (Val::Null, Val::Null) => true,544 (Val::Str(a), Val::Str(b)) => a == b,545 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,546 #[cfg(feature = "exp-bigint")]547 (Val::BigInt(a), Val::BigInt(b)) => a == b,548 (Val::Arr(_), Val::Arr(_)) => {549 bail!("primitiveEquals operates on primitive types, got array")550 }551 (Val::Obj(_), Val::Obj(_)) => {552 bail!("primitiveEquals operates on primitive types, got object")553 }554 (a, b) if is_function_like(a) && is_function_like(b) => {555 bail!("cannot test equality of functions")556 }557 (_, _) => false,558 })559}560561562pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {563 if val_a.value_type() != val_b.value_type() {564 return Ok(false);565 }566 match (val_a, val_b) {567 (Val::Arr(a), Val::Arr(b)) => {568 if ArrValue::ptr_eq(a, b) {569 return Ok(true);570 }571 if a.len() != b.len() {572 return Ok(false);573 }574 for (a, b) in a.iter().zip(b.iter()) {575 if !equals(&a?, &b?)? {576 return Ok(false);577 }578 }579 Ok(true)580 }581 (Val::Obj(a), Val::Obj(b)) => {582 if ObjValue::ptr_eq(a, b) {583 return Ok(true);584 }585 let fields = a.fields(586 #[cfg(feature = "exp-preserve-order")]587 false,588 );589 if fields590 != b.fields(591 #[cfg(feature = "exp-preserve-order")]592 false,593 ) {594 return Ok(false);595 }596 for field in fields {597 if !equals(598 &a.get(field.clone())?.expect("field exists"),599 &b.get(field)?.expect("field exists"),600 )? {601 return Ok(false);602 }603 }604 Ok(true)605 }606 (a, b) => Ok(primitive_equals(a, b)?),607 }608}