difftreelog
feat array unification
in: master
11 files changed
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -50,7 +50,7 @@
/// Assign elements with [`jsonnet_json_array_append`].
#[no_mangle]
pub extern "C" fn jsonnet_json_make_array(_vm: &VM) -> *mut Val {
- Box::into_raw(Box::new(Val::Arr(ArrValue::eager(Vec::new()))))
+ Box::into_raw(Box::new(Val::arr(())))
}
/// Make a `JsonnetJsonValue` representing an object.
bindings/jsonnet/src/val_modify.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -24,7 +24,7 @@
}
new.push(Thunk::evaluated(val.clone()));
- *arr = Val::Arr(ArrValue::lazy(new));
+ *arr = Val::arr(new);
}
_ => panic!("should receive array"),
}
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -6,7 +6,6 @@
};
use jrsonnet_gcmodule::{Cc, cc_dyn};
-use jrsonnet_interner::IBytes;
use jrsonnet_ir::Expr;
use crate::{Context, Result, Thunk, Val, function::NativeFn, typed::IntoUntyped};
@@ -35,28 +34,17 @@
impl ArrValue {
pub fn empty() -> Self {
- Self::new(RangeArray::empty())
+ Self::new(())
}
pub fn expr(ctx: Context, exprs: Rc<Vec<Expr>>) -> Self {
Self::new(ExprArray::new(ctx, exprs))
- }
-
- pub fn lazy(thunks: Vec<Thunk<Val>>) -> Self {
- Self::new(LazyArray(thunks))
}
- pub fn eager(values: Vec<Val>) -> Self {
- Self::new(EagerArray(values))
- }
-
pub fn repeated(data: Self, repeats: usize) -> Option<Self> {
Some(Self::new(RepeatedArray::new(data, repeats)?))
}
- pub fn bytes(bytes: IBytes) -> Self {
- Self::new(BytesArray(bytes))
- }
pub fn chars(chars: impl Iterator<Item = char>) -> Self {
Self::new(CharArray(chars.collect()))
}
@@ -83,7 +71,7 @@
out.push(i);
}
}
- return Ok(Self::eager(out));
+ return Ok(Self::new(out));
};
let mut out = Vec::new();
@@ -92,29 +80,16 @@
out.push(i);
}
}
- Ok(Self::lazy(out))
+ Ok(Self::new(out))
}
pub fn extended(a: Self, b: Self) -> Self {
- // TODO: benchmark for an optimal value, currently just a arbitrary choice
- const ARR_EXTEND_THRESHOLD: usize = 1000;
-
if a.is_empty() {
b
} else if b.is_empty() {
a
- } else if a.len() + b.len() > ARR_EXTEND_THRESHOLD {
+ } else {
Self::new(ExtendedArray::new(a, b))
- } else if let (Some(a), Some(b)) = (a.iter_cheap(), b.iter_cheap()) {
- let mut out = Vec::with_capacity(a.len() + b.len());
- out.extend(a);
- out.extend(b);
- Self::eager(out)
- } else {
- let mut out = Vec::with_capacity(a.len() + b.len());
- out.extend(a.iter_lazy());
- out.extend(b.iter_lazy());
- Self::lazy(out)
}
}
@@ -165,19 +140,15 @@
self.0.is_empty()
}
+ pub fn is_cheap(&self) -> bool {
+ self.0.is_cheap()
+ }
+
/// Get array element by index, evaluating it, if it is lazy.
///
/// Returns `None` on out-of-bounds condition.
pub fn get(&self, index: usize) -> Result<Option<Val>> {
self.0.get(index)
- }
-
- /// Returns None if get is either non cheap, or out of bounds
- /// Note that non-cheap access includes errorable values
- ///
- /// Prefer it to `get_lazy`, but use `get` when you can.
- fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0.get_cheap(index)
}
/// Get array element by index, without evaluation.
@@ -196,15 +167,6 @@
(0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))
}
- /// Prefer it over `iter_lazy`, but do not use it where `iter` will do.
- pub fn iter_cheap(&self) -> Option<impl ArrayLikeIter<Val> + '_> {
- if self.is_cheap() {
- Some((0..self.len()).map(|i| self.get_cheap(i).expect("length and is_cheap checked")))
- } else {
- None
- }
- }
-
/// Return a reversed view on current array.
#[must_use]
pub fn reversed(self) -> Self {
@@ -213,50 +175,25 @@
pub fn ptr_eq(a: &Self, b: &Self) -> bool {
Cc::ptr_eq(&a.0, &b.0)
- }
-
- /// Is this vec supports `.get_cheap()?`
- pub fn is_cheap(&self) -> bool {
- self.0.is_cheap()
}
pub fn as_any(&self) -> &dyn Any {
&self.0
}
}
-impl From<Vec<Val>> for ArrValue {
- fn from(value: Vec<Val>) -> Self {
- Self::eager(value)
- }
-}
-impl From<Vec<Thunk<Val>>> for ArrValue {
- fn from(value: Vec<Thunk<Val>>) -> Self {
- Self::lazy(value)
- }
-}
-impl FromIterator<Val> for ArrValue {
- fn from_iter<T: IntoIterator<Item = Val>>(iter: T) -> Self {
- Self::eager(iter.into_iter().collect())
+impl<T> From<T> for ArrValue
+where
+ T: ArrayLike,
+{
+ fn from(value: T) -> Self {
+ Self::new(value)
}
}
-impl ArrayLike for ArrValue {
- fn len(&self) -> usize {
- self.0.len()
- }
-
- fn get(&self, index: usize) -> Result<Option<Val>> {
- self.0.get(index)
- }
-
- fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- self.0.get_lazy(index)
- }
-
- fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0.get_cheap(index)
- }
-
- fn is_cheap(&self) -> bool {
- self.0.is_cheap()
+impl<I> FromIterator<I> for ArrValue
+where
+ Vec<I>: ArrayLike,
+{
+ fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
+ Self::new(iter.into_iter().collect::<Vec<_>>())
}
}
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth1use std::{any::Any, cell::RefCell, fmt::Debug, mem::replace, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_ir::Expr;67use super::ArrValue;8use crate::{9 Context, Error, ObjValue, Result, Thunk, Val,10 error::ErrorKind::InfiniteRecursionDetected,11 evaluate,12 function::NativeFn,13 typed::{IntoUntyped, Typed},14 val::ThunkValue,15};1617pub trait ArrayLike: Any + Trace + Debug {18 fn len(&self) -> usize;19 fn is_empty(&self) -> bool {20 self.len() == 021 }22 fn get(&self, index: usize) -> Result<Option<Val>>;23 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;24 fn get_cheap(&self, index: usize) -> Option<Val>;2526 fn is_cheap(&self) -> bool;27}2829#[derive(Debug, Trace)]30pub struct SliceArray {31 pub(crate) inner: ArrValue,32 pub(crate) from: u32,33 pub(crate) to: u32,34 pub(crate) step: u32,35}3637impl SliceArray {38 fn map_idx(&self, index: usize) -> usize {39 self.from as usize + self.step as usize * index40 }41}42impl ArrayLike for SliceArray {43 fn len(&self) -> usize {44 (self.to - self.from).div_ceil(self.step) as usize45 }4647 fn get(&self, index: usize) -> Result<Option<Val>> {48 self.inner.get(self.map_idx(index))49 }5051 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {52 self.inner.get_lazy(self.map_idx(index))53 }5455 fn get_cheap(&self, index: usize) -> Option<Val> {56 self.inner.get_cheap(self.map_idx(index))57 }58 fn is_cheap(&self) -> bool {59 self.inner.is_cheap()60 }61}6263#[derive(Trace, Debug)]64pub struct CharArray(pub Vec<char>);65impl ArrayLike for CharArray {66 fn len(&self) -> usize {67 self.0.len()68 }6970 fn get(&self, index: usize) -> Result<Option<Val>> {71 Ok(self.get_cheap(index))72 }7374 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {75 self.get_cheap(index).map(Thunk::evaluated)76 }7778 fn get_cheap(&self, index: usize) -> Option<Val> {79 self.0.get(index).map(|v| Val::string(*v))80 }81 fn is_cheap(&self) -> bool {82 true83 }84}8586#[derive(Trace, Debug)]87pub struct BytesArray(pub IBytes);88impl ArrayLike for BytesArray {89 fn len(&self) -> usize {90 self.0.len()91 }9293 fn get(&self, index: usize) -> Result<Option<Val>> {94 Ok(self.get_cheap(index))95 }9697 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {98 self.get_cheap(index).map(Thunk::evaluated)99 }100101 fn get_cheap(&self, index: usize) -> Option<Val> {102 self.0.get(index).map(|v| Val::Num((*v).into()))103 }104 fn is_cheap(&self) -> bool {105 true106 }107}108109#[derive(Debug, Trace, Clone)]110enum ArrayThunk {111 Computed(Val),112 Errored(Error),113 Waiting,114 Pending,115}116117#[derive(Debug, Trace, Clone)]118pub struct ExprArray {119 ctx: Context,120 src: Rc<Vec<Expr>>,121 cached: Cc<RefCell<Vec<ArrayThunk>>>,122}123impl ExprArray {124 pub fn new(ctx: Context, src: Rc<Vec<Expr>>) -> Self {125 Self {126 ctx,127 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),128 src,129 }130 }131}132impl ArrayLike for ExprArray {133 fn len(&self) -> usize {134 self.cached.borrow().len()135 }136 fn get(&self, index: usize) -> Result<Option<Val>> {137 if index >= self.len() {138 return Ok(None);139 }140 match &self.cached.borrow()[index] {141 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),142 ArrayThunk::Errored(e) => return Err(e.clone()),143 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),144 ArrayThunk::Waiting => {}145 }146147 let ArrayThunk::Waiting =148 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)149 else {150 unreachable!()151 };152153 let new_value = match evaluate(self.ctx.clone(), &self.src[index]) {154 Ok(v) => v,155 Err(e) => {156 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());157 return Err(e);158 }159 };160 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());161 Ok(Some(new_value))162 }163 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {164 #[derive(Trace)]165 struct ExprArrThunk {166 expr: ExprArray,167 index: usize,168 }169 impl ThunkValue for ExprArrThunk {170 type Output = Val;171172 fn get(&self) -> Result<Self::Output> {173 self.expr174 .get(self.index)175 .transpose()176 .expect("index checked")177 }178 }179180 if index >= self.len() {181 return None;182 }183 match &self.cached.borrow()[index] {184 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),185 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),186 ArrayThunk::Waiting | ArrayThunk::Pending => {}187 }188189 Some(Thunk::new(ExprArrThunk {190 expr: self.clone(),191 index,192 }))193 }194 fn get_cheap(&self, _index: usize) -> Option<Val> {195 None196 }197 fn is_cheap(&self) -> bool {198 false199 }200}201202#[derive(Trace, Debug)]203pub struct ExtendedArray {204 pub a: ArrValue,205 pub b: ArrValue,206 split: usize,207 len: usize,208}209impl ExtendedArray {210 pub fn new(a: ArrValue, b: ArrValue) -> Self {211 let a_len = a.len();212 let b_len = b.len();213 Self {214 a,215 b,216 split: a_len,217 len: a_len.checked_add(b_len).expect("too large array value"),218 }219 }220}221222struct WithExactSize<I>(I, usize);223impl<I, T> Iterator for WithExactSize<I>224where225 I: Iterator<Item = T>,226{227 type Item = T;228229 fn next(&mut self) -> Option<Self::Item> {230 self.0.next()231 }232 fn nth(&mut self, n: usize) -> Option<Self::Item> {233 self.0.nth(n)234 }235 fn size_hint(&self) -> (usize, Option<usize>) {236 (self.1, Some(self.1))237 }238}239impl<I> DoubleEndedIterator for WithExactSize<I>240where241 I: DoubleEndedIterator,242{243 fn next_back(&mut self) -> Option<Self::Item> {244 self.0.next_back()245 }246 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {247 self.0.nth_back(n)248 }249}250impl<I> ExactSizeIterator for WithExactSize<I>251where252 I: Iterator,253{254 fn len(&self) -> usize {255 self.1256 }257}258impl ArrayLike for ExtendedArray {259 fn get(&self, index: usize) -> Result<Option<Val>> {260 if self.split > index {261 self.a.get(index)262 } else {263 self.b.get(index - self.split)264 }265 }266 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {267 if self.split > index {268 self.a.get_lazy(index)269 } else {270 self.b.get_lazy(index - self.split)271 }272 }273274 fn len(&self) -> usize {275 self.len276 }277278 fn get_cheap(&self, index: usize) -> Option<Val> {279 if self.split > index {280 self.a.get_cheap(index)281 } else {282 self.b.get_cheap(index - self.split)283 }284 }285 fn is_cheap(&self) -> bool {286 self.a.is_cheap() && self.b.is_cheap()287 }288}289290#[derive(Trace, Debug)]291pub struct LazyArray(pub Vec<Thunk<Val>>);292impl ArrayLike for LazyArray {293 fn len(&self) -> usize {294 self.0.len()295 }296 fn get(&self, index: usize) -> Result<Option<Val>> {297 let Some(v) = self.0.get(index) else {298 return Ok(None);299 };300 v.evaluate().map(Some)301 }302 fn get_cheap(&self, _index: usize) -> Option<Val> {303 None304 }305 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {306 self.0.get(index).cloned()307 }308 fn is_cheap(&self) -> bool {309 false310 }311}312313#[derive(Trace, Debug)]314pub struct EagerArray(pub Vec<Val>);315impl ArrayLike for EagerArray {316 fn len(&self) -> usize {317 self.0.len()318 }319320 fn get(&self, index: usize) -> Result<Option<Val>> {321 Ok(self.0.get(index).cloned())322 }323324 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {325 self.0.get(index).cloned().map(Thunk::evaluated)326 }327328 fn get_cheap(&self, index: usize) -> Option<Val> {329 self.0.get(index).cloned()330 }331 fn is_cheap(&self) -> bool {332 true333 }334}335336/// Inclusive range type337#[derive(Debug, Trace, PartialEq, Eq)]338pub struct RangeArray {339 start: i32,340 end: i32,341}342impl RangeArray {343 pub fn empty() -> Self {344 Self::new_exclusive(0, 0)345 }346 pub fn new_exclusive(start: i32, end: i32) -> Self {347 end.checked_sub(1)348 .map_or_else(Self::empty, |end| Self { start, end })349 }350 pub fn new_inclusive(start: i32, end: i32) -> Self {351 Self { start, end }352 }353 #[expect(354 clippy::cast_sign_loss,355 reason = "the math is valid with wrapping, sign loss works as intended"356 )]357 fn size(&self) -> usize {358 (self.end as usize)359 .wrapping_sub(self.start as usize)360 .wrapping_add(1)361 }362 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {363 WithExactSize(self.start..=self.end, self.size())364 }365}366367impl ArrayLike for RangeArray {368 fn len(&self) -> usize {369 self.size()370 }371 fn is_empty(&self) -> bool {372 self.size() == 0373 }374375 fn get(&self, index: usize) -> Result<Option<Val>> {376 Ok(self.get_cheap(index))377 }378379 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {380 self.get_cheap(index).map(Thunk::evaluated)381 }382383 fn get_cheap(&self, index: usize) -> Option<Val> {384 self.range().nth(index).map(|i| Val::Num(i.into()))385 }386 fn is_cheap(&self) -> bool {387 true388 }389}390391#[derive(Debug, Trace)]392pub struct ReverseArray(pub ArrValue);393impl ArrayLike for ReverseArray {394 fn len(&self) -> usize {395 self.0.len()396 }397398 fn get(&self, index: usize) -> Result<Option<Val>> {399 self.0.get(self.0.len() - index - 1)400 }401402 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {403 self.0.get_lazy(self.0.len() - index - 1)404 }405406 fn get_cheap(&self, index: usize) -> Option<Val> {407 self.0.get_cheap(self.0.len() - index - 1)408 }409 fn is_cheap(&self) -> bool {410 self.0.is_cheap()411 }412}413414#[derive(Trace, Clone, Debug)]415pub enum ArrayMapper {416 Plain(NativeFn!((Val) -> Val)),417 WithIndex(NativeFn!((u32, Val) -> Val)),418}419420#[derive(Trace, Debug, Clone)]421pub struct MappedArray {422 inner: ArrValue,423 cached: Cc<RefCell<Vec<ArrayThunk>>>,424 mapper: ArrayMapper,425}426impl MappedArray {427 pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {428 let len = inner.len();429 Self {430 inner,431 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len])),432 mapper,433 }434 }435 fn evaluate(&self, index: usize, value: Val) -> Result<Val> {436 match &self.mapper {437 ArrayMapper::Plain(f) => f.call(value),438 #[expect(439 clippy::cast_possible_truncation,440 reason = "array len is limited to u31"441 )]442 ArrayMapper::WithIndex(f) => f.call(index as u32, value),443 }444 }445}446impl ArrayLike for MappedArray {447 fn len(&self) -> usize {448 self.cached.borrow().len()449 }450451 fn get(&self, index: usize) -> Result<Option<Val>> {452 if index >= self.len() {453 return Ok(None);454 }455 match &self.cached.borrow()[index] {456 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),457 ArrayThunk::Errored(e) => return Err(e.clone()),458 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),459 ArrayThunk::Waiting => {}460 }461462 let ArrayThunk::Waiting =463 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)464 else {465 unreachable!()466 };467468 let val = self469 .inner470 .get(index)471 .transpose()472 .expect("index checked")473 .and_then(|r| self.evaluate(index, r));474475 let new_value = match val {476 Ok(v) => v,477 Err(e) => {478 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());479 return Err(e);480 }481 };482 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());483 Ok(Some(new_value))484 }485 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {486 #[derive(Trace)]487 struct MappedArrayThunk {488 arr: MappedArray,489 index: usize,490 }491 impl ThunkValue for MappedArrayThunk {492 type Output = Val;493494 fn get(&self) -> Result<Self::Output> {495 self.arr.get(self.index).transpose().expect("index checked")496 }497 }498499 if index >= self.len() {500 return None;501 }502 match &self.cached.borrow()[index] {503 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),504 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),505 ArrayThunk::Waiting | ArrayThunk::Pending => {}506 }507508 Some(Thunk::new(MappedArrayThunk {509 arr: self.clone(),510 index,511 }))512 }513514 fn get_cheap(&self, _index: usize) -> Option<Val> {515 None516 }517 fn is_cheap(&self) -> bool {518 false519 }520}521522#[derive(Trace, Debug)]523pub struct RepeatedArray {524 data: ArrValue,525 repeats: usize,526 total_len: usize,527}528impl RepeatedArray {529 pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {530 let total_len = data.len().checked_mul(repeats)?;531 Some(Self {532 data,533 repeats,534 total_len,535 })536 }537}538539impl ArrayLike for RepeatedArray {540 fn len(&self) -> usize {541 self.total_len542 }543544 fn get(&self, index: usize) -> Result<Option<Val>> {545 if index > self.total_len {546 return Ok(None);547 }548 self.data.get(index % self.data.len())549 }550551 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {552 if index > self.total_len {553 return None;554 }555 self.data.get_lazy(index % self.data.len())556 }557558 fn get_cheap(&self, index: usize) -> Option<Val> {559 if index > self.total_len {560 return None;561 }562 self.data.get_cheap(index % self.data.len())563 }564 fn is_cheap(&self) -> bool {565 self.data.is_cheap()566 }567}568569#[derive(Trace, Debug)]570pub struct PickObjectValues {571 obj: ObjValue,572 keys: Vec<IStr>,573}574575impl PickObjectValues {576 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {577 Self { obj, keys }578 }579}580581impl ArrayLike for PickObjectValues {582 fn len(&self) -> usize {583 self.keys.len()584 }585586 fn get(&self, index: usize) -> Result<Option<Val>> {587 let Some(key) = self.keys.get(index) else {588 return Ok(None);589 };590 Ok(Some(self.obj.get_or_bail(key.clone())?))591 }592593 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {594 let key = self.keys.get(index)?;595 Some(self.obj.get_lazy_or_bail(key.clone()))596 }597598 fn get_cheap(&self, _index: usize) -> Option<Val> {599 None600 }601602 fn is_cheap(&self) -> bool {603 false604 }605}606607#[derive(Trace, Debug)]608pub struct PickObjectKeyValues {609 obj: ObjValue,610 keys: Vec<IStr>,611}612613impl PickObjectKeyValues {614 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {615 Self { obj, keys }616 }617}618619#[derive(Typed, IntoUntyped)]620pub struct KeyValue {621 key: IStr,622 value: Thunk<Val>,623}624625impl ArrayLike for PickObjectKeyValues {626 fn len(&self) -> usize {627 self.keys.len()628 }629630 fn get(&self, index: usize) -> Result<Option<Val>> {631 let Some(key) = self.keys.get(index) else {632 return Ok(None);633 };634 Ok(Some(635 KeyValue::into_untyped(KeyValue {636 key: key.clone(),637 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),638 })639 .expect("convertible"),640 ))641 }642643 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {644 let key = self.keys.get(index)?;645 // Nothing can fail in the key part, yet value is still646 // lazy-evaluated647 Some(Thunk::evaluated(648 KeyValue::into_untyped(KeyValue {649 key: key.clone(),650 value: self.obj.get_lazy_or_bail(key.clone()),651 })652 .expect("convertible"),653 ))654 }655656 fn get_cheap(&self, _index: usize) -> Option<Val> {657 None658 }659660 fn is_cheap(&self) -> bool {661 false662 }663}1use std::{2 any::Any,3 cell::RefCell,4 fmt::{self, Debug},5 mem::replace,6 rc::Rc,7};89use jrsonnet_gcmodule::{Cc, Trace};10use jrsonnet_interner::{IBytes, IStr};11use jrsonnet_ir::Expr;1213use super::ArrValue;14use crate::{15 Context, Error, ObjValue, Result, Thunk, Val,16 error::ErrorKind::InfiniteRecursionDetected,17 evaluate,18 function::NativeFn,19 typed::{IntoUntyped, Typed},20 val::ThunkValue,21};2223pub trait ArrayLike: Any + Trace + Debug {24 fn len(&self) -> usize;25 fn is_empty(&self) -> bool {26 self.len() == 027 }28 fn get(&self, index: usize) -> Result<Option<Val>>;29 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;3031 fn is_cheap(&self) -> bool {32 false33 }34}35trait ArrayCheap {36 fn get(&self, index: usize) -> Option<Val>;37 fn len(&self) -> usize;38}39impl<T> ArrayLike for T40where41 T: Any + Trace + Debug + ArrayCheap,42{43 fn len(&self) -> usize {44 <T as ArrayCheap>::len(self)45 }4647 fn get(&self, index: usize) -> Result<Option<Val>> {48 Ok(<T as ArrayCheap>::get(self, index))49 }5051 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {52 <T as ArrayCheap>::get(self, index).map(Thunk::evaluated)53 }5455 fn is_cheap(&self) -> bool {56 true57 }58}5960impl ArrayCheap for () {61 fn len(&self) -> usize {62 063 }64 fn get(&self, _index: usize) -> Option<Val> {65 None66 }67}6869#[derive(Debug, Trace)]70pub struct SliceArray {71 pub(crate) inner: ArrValue,72 pub(crate) from: u32,73 pub(crate) to: u32,74 pub(crate) step: u32,75}7677impl SliceArray {78 fn map_idx(&self, index: usize) -> usize {79 self.from as usize + self.step as usize * index80 }81}82impl ArrayLike for SliceArray {83 fn len(&self) -> usize {84 (self.to - self.from).div_ceil(self.step) as usize85 }8687 fn get(&self, index: usize) -> Result<Option<Val>> {88 self.inner.get(self.map_idx(index))89 }9091 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {92 self.inner.get_lazy(self.map_idx(index))93 }9495 fn is_cheap(&self) -> bool {96 self.inner.is_cheap()97 }98}99100#[derive(Trace, Debug)]101pub struct CharArray(pub Vec<char>);102impl ArrayCheap for CharArray {103 fn len(&self) -> usize {104 self.0.as_slice().len()105 }106 fn get(&self, index: usize) -> Option<Val> {107 self.0.as_slice().get(index).map(|v| Val::string(*v))108 }109}110111impl ArrayCheap for IBytes {112 fn len(&self) -> usize {113 self.as_slice().len()114 }115 fn get(&self, index: usize) -> Option<Val> {116 self.as_slice().get(index).map(|v| Val::Num((*v).into()))117 }118}119120#[derive(Debug, Trace, Clone)]121enum ArrayThunk {122 Computed(Val),123 Errored(Error),124 Waiting,125 Pending,126}127128#[derive(Debug, Trace, Clone)]129pub struct ExprArray {130 ctx: Context,131 src: Rc<Vec<Expr>>,132 cached: Cc<RefCell<Vec<ArrayThunk>>>,133}134impl ExprArray {135 pub fn new(ctx: Context, src: Rc<Vec<Expr>>) -> Self {136 Self {137 ctx,138 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),139 src,140 }141 }142}143impl ArrayLike for ExprArray {144 fn len(&self) -> usize {145 self.cached.borrow().len()146 }147 fn get(&self, index: usize) -> Result<Option<Val>> {148 if index >= self.len() {149 return Ok(None);150 }151 match &self.cached.borrow()[index] {152 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),153 ArrayThunk::Errored(e) => return Err(e.clone()),154 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),155 ArrayThunk::Waiting => {}156 }157158 let ArrayThunk::Waiting =159 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)160 else {161 unreachable!()162 };163164 let new_value = match evaluate(self.ctx.clone(), &self.src[index]) {165 Ok(v) => v,166 Err(e) => {167 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());168 return Err(e);169 }170 };171 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());172 Ok(Some(new_value))173 }174 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {175 #[derive(Trace)]176 struct ExprArrThunk {177 expr: ExprArray,178 index: usize,179 }180 impl ThunkValue for ExprArrThunk {181 type Output = Val;182183 fn get(&self) -> Result<Self::Output> {184 self.expr185 .get(self.index)186 .transpose()187 .expect("index checked")188 }189 }190191 if index >= self.len() {192 return None;193 }194 match &self.cached.borrow()[index] {195 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),196 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),197 ArrayThunk::Waiting | ArrayThunk::Pending => {}198 }199200 Some(Thunk::new(ExprArrThunk {201 expr: self.clone(),202 index,203 }))204 }205 fn is_cheap(&self) -> bool {206 false207 }208}209210#[derive(Trace, Debug)]211pub struct ExtendedArray {212 pub a: ArrValue,213 pub b: ArrValue,214 split: usize,215 len: usize,216}217impl ExtendedArray {218 pub fn new(a: ArrValue, b: ArrValue) -> Self {219 let a_len = a.len();220 let b_len = b.len();221 Self {222 a,223 b,224 split: a_len,225 len: a_len.checked_add(b_len).expect("too large array value"),226 }227 }228}229230struct WithExactSize<I>(I, usize);231impl<I, T> Iterator for WithExactSize<I>232where233 I: Iterator<Item = T>,234{235 type Item = T;236237 fn next(&mut self) -> Option<Self::Item> {238 self.0.next()239 }240 fn nth(&mut self, n: usize) -> Option<Self::Item> {241 self.0.nth(n)242 }243 fn size_hint(&self) -> (usize, Option<usize>) {244 (self.1, Some(self.1))245 }246}247impl<I> DoubleEndedIterator for WithExactSize<I>248where249 I: DoubleEndedIterator,250{251 fn next_back(&mut self) -> Option<Self::Item> {252 self.0.next_back()253 }254 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {255 self.0.nth_back(n)256 }257}258impl<I> ExactSizeIterator for WithExactSize<I>259where260 I: Iterator,261{262 fn len(&self) -> usize {263 self.1264 }265}266impl ArrayLike for ExtendedArray {267 fn get(&self, index: usize) -> Result<Option<Val>> {268 if self.split > index {269 self.a.get(index)270 } else {271 self.b.get(index - self.split)272 }273 }274 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {275 if self.split > index {276 self.a.get_lazy(index)277 } else {278 self.b.get_lazy(index - self.split)279 }280 }281282 fn len(&self) -> usize {283 self.len284 }285286 fn is_cheap(&self) -> bool {287 self.a.is_cheap() && self.b.is_cheap()288 }289}290291impl<T> ArrayLike for Vec<T>292where293 T: IntoUntyped + Trace + fmt::Debug,294 for<'a> &'a T: IntoUntyped,295{296 fn len(&self) -> usize {297 self.as_slice().len()298 }299300 fn get(&self, index: usize) -> Result<Option<Val>> {301 let Some(elem) = self.as_slice().get(index) else {302 return Ok(None);303 };304 IntoUntyped::into_untyped(elem).map(Some)305 }306307 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {308 let elem = self.as_slice().get(index)?;309 Some(IntoUntyped::into_lazy_untyped(elem))310 }311312 fn is_cheap(&self) -> bool {313 !T::provides_lazy()314 }315}316317/// Inclusive range type318#[derive(Debug, Trace, PartialEq, Eq)]319pub struct RangeArray {320 start: i32,321 end: i32,322}323impl RangeArray {324 pub fn empty() -> Self {325 Self::new_exclusive(0, 0)326 }327 pub fn new_exclusive(start: i32, end: i32) -> Self {328 end.checked_sub(1)329 .map_or_else(Self::empty, |end| Self { start, end })330 }331 pub fn new_inclusive(start: i32, end: i32) -> Self {332 Self { start, end }333 }334 #[expect(335 clippy::cast_sign_loss,336 reason = "the math is valid with wrapping, sign loss works as intended"337 )]338 fn size(&self) -> usize {339 (self.end as usize)340 .wrapping_sub(self.start as usize)341 .wrapping_add(1)342 }343 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {344 WithExactSize(self.start..=self.end, self.size())345 }346}347impl ArrayCheap for RangeArray {348 fn get(&self, index: usize) -> Option<Val> {349 self.range().nth(index).map(|i| Val::Num(i.into()))350 }351 fn len(&self) -> usize {352 self.size()353 }354}355356#[derive(Debug, Trace)]357pub struct ReverseArray(pub ArrValue);358impl ArrayLike for ReverseArray {359 fn len(&self) -> usize {360 self.0.len()361 }362363 fn get(&self, index: usize) -> Result<Option<Val>> {364 self.0.get(self.0.len() - index - 1)365 }366367 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {368 self.0.get_lazy(self.0.len() - index - 1)369 }370371 fn is_cheap(&self) -> bool {372 self.0.is_cheap()373 }374}375376#[derive(Trace, Clone, Debug)]377pub enum ArrayMapper {378 Plain(NativeFn!((Val) -> Val)),379 WithIndex(NativeFn!((u32, Val) -> Val)),380}381382#[derive(Trace, Debug, Clone)]383pub struct MappedArray {384 inner: ArrValue,385 cached: Cc<RefCell<Vec<ArrayThunk>>>,386 mapper: ArrayMapper,387}388impl MappedArray {389 pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {390 let len = inner.len();391 Self {392 inner,393 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len])),394 mapper,395 }396 }397 fn evaluate(&self, index: usize, value: Val) -> Result<Val> {398 match &self.mapper {399 ArrayMapper::Plain(f) => f.call(value),400 #[expect(401 clippy::cast_possible_truncation,402 reason = "array len is limited to u31"403 )]404 ArrayMapper::WithIndex(f) => f.call(index as u32, value),405 }406 }407}408impl ArrayLike for MappedArray {409 fn len(&self) -> usize {410 self.cached.borrow().len()411 }412413 fn get(&self, index: usize) -> Result<Option<Val>> {414 if index >= self.len() {415 return Ok(None);416 }417 match &self.cached.borrow()[index] {418 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),419 ArrayThunk::Errored(e) => return Err(e.clone()),420 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),421 ArrayThunk::Waiting => {}422 }423424 let ArrayThunk::Waiting =425 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)426 else {427 unreachable!()428 };429430 let val = self431 .inner432 .get(index)433 .transpose()434 .expect("index checked")435 .and_then(|r| self.evaluate(index, r));436437 let new_value = match val {438 Ok(v) => v,439 Err(e) => {440 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());441 return Err(e);442 }443 };444 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());445 Ok(Some(new_value))446 }447 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {448 #[derive(Trace)]449 struct MappedArrayThunk {450 arr: MappedArray,451 index: usize,452 }453 impl ThunkValue for MappedArrayThunk {454 type Output = Val;455456 fn get(&self) -> Result<Self::Output> {457 self.arr.get(self.index).transpose().expect("index checked")458 }459 }460461 if index >= self.len() {462 return None;463 }464 match &self.cached.borrow()[index] {465 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),466 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),467 ArrayThunk::Waiting | ArrayThunk::Pending => {}468 }469470 Some(Thunk::new(MappedArrayThunk {471 arr: self.clone(),472 index,473 }))474 }475}476477#[derive(Trace, Debug)]478pub struct RepeatedArray {479 data: ArrValue,480 repeats: usize,481 total_len: usize,482}483impl RepeatedArray {484 pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {485 let total_len = data.len().checked_mul(repeats)?;486 Some(Self {487 data,488 repeats,489 total_len,490 })491 }492 fn map_idx(&self, index: usize) -> Option<usize> {493 if index > self.total_len {494 return None;495 }496 Some(index % self.data.len())497 }498}499500impl ArrayLike for RepeatedArray {501 fn len(&self) -> usize {502 self.total_len503 }504505 fn get(&self, index: usize) -> Result<Option<Val>> {506 let Some(idx) = self.map_idx(index) else {507 return Ok(None);508 };509 self.data.get(idx)510 }511512 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {513 let idx = self.map_idx(index)?;514 self.data.get_lazy(idx)515 }516517 fn is_cheap(&self) -> bool {518 self.data.is_cheap()519 }520}521522#[derive(Trace, Debug)]523pub struct PickObjectValues {524 obj: ObjValue,525 keys: Vec<IStr>,526}527528impl PickObjectValues {529 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {530 Self { obj, keys }531 }532}533534impl ArrayLike for PickObjectValues {535 fn len(&self) -> usize {536 self.keys.len()537 }538539 fn get(&self, index: usize) -> Result<Option<Val>> {540 let Some(key) = self.keys.as_slice().get(index) else {541 return Ok(None);542 };543 Ok(Some(self.obj.get_or_bail(key.clone())?))544 }545546 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {547 let key = self.keys.as_slice().get(index)?;548 Some(self.obj.get_lazy_or_bail(key.clone()))549 }550551 fn is_cheap(&self) -> bool {552 false553 }554}555556#[derive(Trace, Debug)]557pub struct PickObjectKeyValues {558 obj: ObjValue,559 keys: Vec<IStr>,560}561562impl PickObjectKeyValues {563 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {564 Self { obj, keys }565 }566}567568#[derive(Typed, IntoUntyped)]569pub struct KeyValue {570 key: IStr,571 value: Thunk<Val>,572}573574impl ArrayLike for PickObjectKeyValues {575 fn len(&self) -> usize {576 self.keys.len()577 }578579 fn get(&self, index: usize) -> Result<Option<Val>> {580 let Some(key) = self.keys.as_slice().get(index) else {581 return Ok(None);582 };583 Ok(Some(584 KeyValue::into_untyped(KeyValue {585 key: key.clone(),586 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),587 })588 .expect("convertible"),589 ))590 }591592 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {593 let key = self.keys.as_slice().get(index)?;594 // Nothing can fail in the key part, yet value is still595 // lazy-evaluated596 Some(Thunk::evaluated(597 KeyValue::into_untyped(KeyValue {598 key: key.clone(),599 value: self.obj.get_lazy_or_bail(key.clone()),600 })601 .expect("convertible"),602 ))603 }604605 fn is_cheap(&self) -> bool {606 false607 }608}crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -70,12 +70,12 @@
if n.iter().any(|e| !is_trivial(e)) {
return None;
}
- Val::Arr(ArrValue::eager(
+ Val::Arr(
n.iter()
.map(evaluate_trivial)
.map(|e| e.expect("checked trivial"))
.collect(),
- ))
+ )
}
_ => return None,
})
@@ -145,12 +145,12 @@
let fctx = Pending::new();
let mut new_bindings = FxHashMap::with_capacity(into.binds_len());
let obj = obj.clone();
- let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![
+ let value = Thunk::evaluated(Val::arr(vec![
Thunk::evaluated(Val::string(field.clone())),
- Thunk!(move || obj.get(field).transpose().expect(
+ obj.get_lazy(field).transpose().expect(
"field exists, as field name was obtained from object.fields()",
- )),
- ])));
+ ),
+ ]));
destruct(into, value, fctx.clone(), &mut new_bindings)?;
let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);
@@ -528,7 +528,7 @@
#[cfg(feature = "exp-null-coaelse")]
None if part.null_coaelse => return Ok(Val::Null),
None => {
- let suggestions = suggest_object_fields(&v, key.clone().into_flat());
+ let suggestions = suggest_object_fields(&v, key.into_flat());
return Err(Error::from(NoSuchField(
key.clone().into_flat(),
@@ -628,7 +628,7 @@
}
Arr(items) => {
if items.is_empty() {
- Val::Arr(ArrValue::empty())
+ Val::arr(())
} else {
Val::Arr(ArrValue::expr(ctx, items.clone()))
}
@@ -640,7 +640,7 @@
out.push(Thunk!(move || evaluate(ctx, &expr)));
Ok(())
})?;
- Val::Arr(ArrValue::lazy(out))
+ Val::arr(out)
}
Obj(body) => Val::Obj(evaluate_object(None, ctx, body)?),
ObjExtend(a, b) => {
@@ -718,9 +718,7 @@
|| s.import_resolved(resolved_path),
)?,
ImportKind::Str => Val::string(s.import_resolved_str(resolved_path)?),
- ImportKind::Bin => {
- Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?))
- }
+ ImportKind::Bin => Val::arr(s.import_resolved_bin(resolved_path)?),
}) as Result<Val>
})?
}
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,6 +1,6 @@
use std::borrow::Cow;
-use jrsonnet_interner::IStr;
+use jrsonnet_interner::{IBytes, IStr};
use serde::{
Deserialize, Serialize, Serializer,
de::{self, Visitor},
@@ -11,8 +11,8 @@
};
use crate::{
- Error as JrError, ObjValue, ObjValueBuilder, Result, Val, arr::ArrValue, in_description_frame,
- runtime_error, val::NumValue,
+ Error as JrError, ObjValue, ObjValueBuilder, Result, Val, in_description_frame, runtime_error,
+ val::NumValue,
};
impl<'de> Deserialize<'de> for Val {
@@ -90,7 +90,7 @@
where
E: de::Error,
{
- Ok(Val::Arr(ArrValue::bytes(v.into())))
+ Ok(Val::arr(IBytes::from(v)))
}
fn visit_none<E>(self) -> Result<Self::Value, E>
@@ -130,7 +130,7 @@
out.push(val);
}
- Ok(Val::Arr(ArrValue::eager(out)))
+ Ok(Val::arr(out))
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
@@ -270,7 +270,7 @@
}
fn end(self) -> Result<Val> {
- let inner = Val::Arr(ArrValue::eager(self.data));
+ let inner = Val::arr(self.data);
if let Some(variant) = self.variant {
let mut out = ObjValue::builder_with_capacity(1);
out.field(variant).value(inner);
@@ -509,7 +509,7 @@
}
fn serialize_bytes(self, v: &[u8]) -> Result<Val> {
- Ok(Val::Arr(ArrValue::bytes(v.into())))
+ Ok(Val::arr(IBytes::from(v)))
}
fn serialize_none(self) -> Result<Val> {
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -6,7 +6,7 @@
use crate::{
ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
- arr::{ArrValue, BytesArray},
+ arr::ArrValue,
bail,
function::FuncVal,
typed::CheckType,
@@ -83,6 +83,12 @@
pub trait Typed: Sized {
const TYPE: &'static ComplexValType;
}
+impl<T> Typed for &T
+where
+ T: Typed,
+{
+ const TYPE: &'static ComplexValType = <&T as Typed>::TYPE;
+}
pub trait IntoUntyped: Typed {
// Whatever caller should use `into_lazy_untyped` instead of `into_untyped`
fn provides_lazy() -> bool {
@@ -93,6 +99,7 @@
Thunk::from(Self::into_untyped(typed))
}
}
+
pub trait IntoUntypedResult: Typed {
/// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result
/// This method returns identity in impl Typed for Result, and should not be overriden
@@ -157,6 +164,26 @@
inner.map(<ThunkIntoUntyped<T>>::default())
}
}
+impl<T> IntoUntyped for &Thunk<T>
+where
+ T: IntoUntyped + Trace + Clone,
+{
+ fn into_untyped(typed: Self) -> Result<Val> {
+ T::into_untyped(typed.evaluate()?)
+ }
+ fn provides_lazy() -> bool {
+ true
+ }
+
+ fn into_lazy_untyped(inner: Self) -> Thunk<Val> {
+ // Avoid lazy mapping
+ let inner = match try_cast_thunk_val(inner.clone()) {
+ Ok(v) => return v,
+ Err(e) => e,
+ };
+ inner.map(<ThunkIntoUntyped<T>>::default())
+ }
+}
fn try_cast_thunk_t<T: 'static>(typed: Thunk<Val>) -> Result<Thunk<T>, Thunk<Val>> {
if TypeId::of::<T>() == TypeId::of::<Val>() {
@@ -221,6 +248,11 @@
}
}
}
+ impl IntoUntyped for &$ty {
+ fn into_untyped(value: Self) -> Result<Val> {
+ Ok(Val::Num((*value).into()))
+ }
+ }
impl IntoUntyped for $ty {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::Num(value.into()))
@@ -305,6 +337,11 @@
impl Typed for f64 {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
}
+impl IntoUntyped for &f64 {
+ fn into_untyped(value: Self) -> Result<Val> {
+ Ok(Val::try_num(*value)?)
+ }
+}
impl IntoUntyped for f64 {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::try_num(value)?)
@@ -324,7 +361,7 @@
impl Typed for PositiveF64 {
const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);
}
-impl IntoUntyped for PositiveF64 {
+impl IntoUntyped for &PositiveF64 {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::try_num(value.0)?)
}
@@ -538,6 +575,11 @@
impl Typed for Val {
const TYPE: &'static ComplexValType = &ComplexValType::Any;
}
+impl IntoUntyped for &Val {
+ fn into_untyped(typed: Self) -> Result<Val> {
+ Ok(typed.clone())
+ }
+}
impl IntoUntyped for Val {
fn into_untyped(typed: Self) -> Result<Val> {
Ok(typed)
@@ -567,9 +609,14 @@
const TYPE: &'static ComplexValType =
&ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));
}
+impl IntoUntyped for &IBytes {
+ fn into_untyped(value: Self) -> Result<Val> {
+ Ok(Val::arr(value.clone()))
+ }
+}
impl IntoUntyped for IBytes {
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Arr(ArrValue::bytes(value)))
+ Ok(Val::arr(value))
}
}
impl FromUntyped for IBytes {
@@ -578,8 +625,8 @@
<Self as Typed>::TYPE.check(&value)?;
unreachable!()
};
- if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
- return Ok(bytes.0.as_slice().into());
+ if let Some(bytes) = a.as_any().downcast_ref::<IBytes>() {
+ return Ok(bytes.clone());
}
<Self as Typed>::TYPE.check(&value)?;
// Any::downcast_ref::<ByteArray>(&a);
@@ -596,7 +643,7 @@
impl Typed for M1 {
const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));
}
-impl IntoUntyped for M1 {
+impl IntoUntyped for &M1 {
fn into_untyped(_: Self) -> Result<Val> {
Ok(Val::Num(NumValue::new(-1.0).expect("finite")))
}
@@ -728,6 +775,11 @@
impl Typed for bool {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);
}
+impl IntoUntyped for &bool {
+ fn into_untyped(value: Self) -> Result<Val> {
+ Ok(Val::Bool(*value))
+ }
+}
impl IntoUntyped for bool {
fn into_untyped(value: Self) -> Result<Val> {
Ok(Val::Bool(value))
@@ -764,19 +816,23 @@
}
}
-pub struct Null;
-impl Typed for Null {
+impl Typed for () {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);
}
-impl IntoUntyped for Null {
- fn into_untyped(_: Self) -> Result<Val> {
+impl IntoUntyped for &() {
+ fn into_untyped((): Self) -> Result<Val> {
Ok(Val::Null)
}
}
-impl FromUntyped for Null {
+impl IntoUntyped for () {
+ fn into_untyped((): Self) -> Result<Val> {
+ Ok(Val::Null)
+ }
+}
+impl FromUntyped for () {
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
- Ok(Self)
+ Ok(())
}
}
@@ -811,9 +867,9 @@
impl Typed for NumValue {
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
}
-impl IntoUntyped for NumValue {
+impl IntoUntyped for &NumValue {
fn into_untyped(typed: Self) -> Result<Val> {
- Ok(Val::Num(typed))
+ Ok(Val::Num(*typed))
}
}
impl FromUntyped for NumValue {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -137,7 +137,7 @@
impl<T> Thunk<T>
where
- T: Clone + Trace,
+ T: Trace,
{
pub fn force(&self) -> Result<()> {
self.evaluate()?;
@@ -161,7 +161,7 @@
}
impl<Input> Thunk<Input>
where
- Input: Trace + Clone,
+ Input: Trace,
{
pub fn map<M>(self, mapper: M) -> Thunk<M::Output>
where
@@ -355,7 +355,7 @@
Self::Tree(Rc::new((a, b, len)))
}
}
- pub fn into_flat(self) -> IStr {
+ pub fn into_flat(&self) -> IStr {
#[cold]
fn write_buf(s: &StrValue, out: &mut String) {
match s {
@@ -367,10 +367,10 @@
}
}
match self {
- Self::Flat(f) => f,
+ Self::Flat(f) => f.clone(),
Self::Tree(_) => {
let mut buf = String::with_capacity(self.len());
- write_buf(&self, &mut buf);
+ write_buf(self, &mut buf);
buf.into()
}
}
@@ -701,6 +701,9 @@
{
Ok(Self::Num(num.try_into()?))
}
+ pub fn arr(a: impl ArrayLike) -> Self {
+ Self::Arr(ArrValue::new(a))
+ }
}
impl From<IStr> for Val {
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -34,7 +34,7 @@
for _ in 0..*sz {
out.push(trivial.clone());
}
- Ok(ArrValue::eager(out))
+ Ok(ArrValue::new(out))
},
)
}
@@ -256,7 +256,7 @@
pub fn builtin_lines(arr: ArrValue) -> Result<IndexableVal> {
builtin_join(
IndexableVal::Str("\n".into()),
- ArrValue::extended(arr, ArrValue::eager(vec![Val::string("")])),
+ ArrValue::extended(arr, ArrValue::new(vec![Val::string("")])),
)
}
@@ -468,7 +468,7 @@
out.push(ele);
}
}
- Val::Arr(ArrValue::eager(out))
+ Val::arr(out)
}
Val::Obj(o) => {
let mut out = ObjValueBuilder::new();
crates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -29,7 +29,11 @@
#[builtin]
#[allow(non_snake_case, clippy::redundant_closure)]
-pub fn builtin_set_inter(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
+pub fn builtin_set_inter(
+ a: ArrValue,
+ b: ArrValue,
+ #[default] keyF: KeyF,
+) -> Result<Vec<Thunk<Val>>> {
let mut a = a.iter_lazy();
let mut b = b.iter_lazy();
@@ -60,12 +64,16 @@
}
}
}
- Ok(ArrValue::lazy(out))
+ Ok(out)
}
#[builtin]
#[allow(non_snake_case, clippy::redundant_closure)]
-pub fn builtin_set_diff(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
+pub fn builtin_set_diff(
+ a: ArrValue,
+ b: ArrValue,
+ #[default] keyF: KeyF,
+) -> Result<Vec<Thunk<Val>>> {
let mut a = a.iter_lazy();
let mut b = b.iter_lazy();
@@ -103,12 +111,16 @@
av = a.next();
ak = av.clone().map(keyF).transpose()?;
}
- Ok(ArrValue::lazy(out))
+ Ok(out)
}
#[builtin]
#[allow(non_snake_case, clippy::redundant_closure)]
-pub fn builtin_set_union(a: ArrValue, b: ArrValue, #[default] keyF: KeyF) -> Result<ArrValue> {
+pub fn builtin_set_union(
+ a: ArrValue,
+ b: ArrValue,
+ #[default] keyF: KeyF,
+) -> Result<Vec<Thunk<Val>>> {
let mut a = a.iter_lazy();
let mut b = b.iter_lazy();
@@ -154,5 +166,5 @@
bv = b.next();
bk = bv.clone().map(keyF).transpose()?;
}
- Ok(ArrValue::lazy(out))
+ Ok(out)
}
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -113,11 +113,11 @@
return Ok(values);
}
if key_getter.is_identity() {
- Ok(ArrValue::eager(sort_identity(
+ Ok(ArrValue::new(sort_identity(
values.iter().collect::<Result<Vec<Val>>>()?,
)?))
} else {
- Ok(ArrValue::lazy(sort_keyf(values, key_getter)?))
+ Ok(ArrValue::new(sort_keyf(values, key_getter)?))
}
}
@@ -162,11 +162,11 @@
return Ok(arr);
}
if keyF.is_identity() {
- Ok(ArrValue::eager(uniq_identity(
+ Ok(ArrValue::new(uniq_identity(
arr.iter().collect::<Result<Vec<Val>>>()?,
)?))
} else {
- Ok(ArrValue::lazy(uniq_keyf(arr, keyF)?))
+ Ok(ArrValue::new(uniq_keyf(arr, keyF)?))
}
}
@@ -180,11 +180,11 @@
let arr = arr.iter().collect::<Result<Vec<Val>>>()?;
let arr = sort_identity(arr)?;
let arr = uniq_identity(arr)?;
- Ok(ArrValue::eager(arr))
+ Ok(ArrValue::new(arr))
} else {
let arr = sort_keyf(arr, keyF.clone())?;
- let arr = uniq_keyf(ArrValue::lazy(arr), keyF)?;
- Ok(ArrValue::lazy(arr))
+ let arr = uniq_keyf(ArrValue::new(arr), keyF)?;
+ Ok(ArrValue::new(arr))
}
}