1use 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}335336337#[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 646 647 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}