1use std::{any::Any, cell::RefCell, fmt::Debug, iter, mem::replace};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_parser::LocExpr;67use super::ArrValue;8use crate::{9 error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, typed::Typed,10 Context, Error, ObjValue, Result, Thunk, Val,11};1213pub trait ArrayLike: Any + Trace + Debug {14 fn len(&self) -> usize;15 fn is_empty(&self) -> bool {16 self.len() == 017 }18 fn get(&self, index: usize) -> Result<Option<Val>>;19 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>>;20 fn get_cheap(&self, index: usize) -> Option<Val>;2122 fn is_cheap(&self) -> bool;23}2425#[derive(Debug, Trace)]26pub struct SliceArray {27 pub(crate) inner: ArrValue,28 pub(crate) from: u32,29 pub(crate) to: u32,30 pub(crate) step: u32,31}3233impl SliceArray {34 fn iter(&self) -> impl Iterator<Item = Result<Val>> + '_ {35 self.inner36 .iter()37 .skip(self.from as usize)38 .take((self.to - self.from) as usize)39 .step_by(self.step as usize)40 }4142 fn iter_lazy(&self) -> impl Iterator<Item = Thunk<Val>> + '_ {43 self.inner44 .iter_lazy()45 .skip(self.from as usize)46 .take((self.to - self.from) as usize)47 .step_by(self.step as usize)48 }4950 fn iter_cheap(&self) -> Option<impl crate::arr::ArrayLikeIter<Val> + '_> {51 Some(52 self.inner53 .iter_cheap()?54 .skip(self.from as usize)55 .take((self.to - self.from) as usize)56 .step_by(self.step as usize),57 )58 }59}60impl ArrayLike for SliceArray {61 fn len(&self) -> usize {62 iter::repeat(())63 .take((self.to - self.from) as usize)64 .step_by(self.step as usize)65 .count()66 }6768 fn get(&self, index: usize) -> Result<Option<Val>> {69 self.iter().nth(index).transpose()70 }7172 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {73 self.iter_lazy().nth(index)74 }7576 fn get_cheap(&self, index: usize) -> Option<Val> {77 self.iter_cheap()?.nth(index)78 }79 fn is_cheap(&self) -> bool {80 self.inner.is_cheap()81 }82}8384#[derive(Trace, Debug)]85pub struct CharArray(pub Vec<char>);86impl ArrayLike for CharArray {87 fn len(&self) -> usize {88 self.0.len()89 }9091 fn get(&self, index: usize) -> Result<Option<Val>> {92 Ok(self.get_cheap(index))93 }9495 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {96 self.get_cheap(index).map(Thunk::evaluated)97 }9899 fn get_cheap(&self, index: usize) -> Option<Val> {100 self.0.get(index).map(|v| Val::string(*v))101 }102 fn is_cheap(&self) -> bool {103 true104 }105}106107#[derive(Trace, Debug)]108pub struct BytesArray(pub IBytes);109impl ArrayLike for BytesArray {110 fn len(&self) -> usize {111 self.0.len()112 }113114 fn get(&self, index: usize) -> Result<Option<Val>> {115 Ok(self.get_cheap(index))116 }117118 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {119 self.get_cheap(index).map(Thunk::evaluated)120 }121122 fn get_cheap(&self, index: usize) -> Option<Val> {123 self.0.get(index).map(|v| Val::Num((*v).into()))124 }125 fn is_cheap(&self) -> bool {126 true127 }128}129130#[derive(Debug, Trace, Clone)]131enum ArrayThunk<T: 'static + Trace> {132 Computed(Val),133 Errored(Error),134 Waiting(T),135 Pending,136}137138#[derive(Debug, Trace, Clone)]139pub struct ExprArray {140 ctx: Context,141 cached: Cc<RefCell<Vec<ArrayThunk<LocExpr>>>>,142}143impl ExprArray {144 pub fn new(ctx: Context, items: impl IntoIterator<Item = LocExpr>) -> Self {145 Self {146 ctx,147 cached: Cc::new(RefCell::new(148 items.into_iter().map(ArrayThunk::Waiting).collect(),149 )),150 }151 }152}153impl ArrayLike for ExprArray {154 fn len(&self) -> usize {155 self.cached.borrow().len()156 }157 fn get(&self, index: usize) -> Result<Option<Val>> {158 if index >= self.len() {159 return Ok(None);160 }161 match &self.cached.borrow()[index] {162 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),163 ArrayThunk::Errored(e) => return Err(e.clone()),164 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),165 ArrayThunk::Waiting(..) => {}166 };167168 let ArrayThunk::Waiting(expr) =169 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)170 else {171 unreachable!()172 };173174 let new_value = match evaluate(self.ctx.clone(), &expr) {175 Ok(v) => v,176 Err(e) => {177 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());178 return Err(e);179 }180 };181 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());182 Ok(Some(new_value))183 }184 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {185 if index >= self.len() {186 return None;187 }188 match &self.cached.borrow()[index] {189 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),190 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),191 ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}192 };193194 let arr_thunk = self.clone();195 Some(Thunk!(move || {196 arr_thunk.get(index).transpose().expect("index checked")197 }))198 }199 fn get_cheap(&self, _index: usize) -> Option<Val> {200 None201 }202 fn is_cheap(&self) -> bool {203 false204 }205}206207#[derive(Trace, Debug)]208pub struct ExtendedArray {209 pub a: ArrValue,210 pub b: ArrValue,211 split: usize,212 len: usize,213}214impl ExtendedArray {215 pub fn new(a: ArrValue, b: ArrValue) -> Self {216 let a_len = a.len();217 let b_len = b.len();218 Self {219 a,220 b,221 split: a_len,222 len: a_len.checked_add(b_len).expect("too large array value"),223 }224 }225}226227struct WithExactSize<I>(I, usize);228impl<I, T> Iterator for WithExactSize<I>229where230 I: Iterator<Item = T>,231{232 type Item = T;233234 fn next(&mut self) -> Option<Self::Item> {235 self.0.next()236 }237 fn nth(&mut self, n: usize) -> Option<Self::Item> {238 self.0.nth(n)239 }240 fn size_hint(&self) -> (usize, Option<usize>) {241 (self.1, Some(self.1))242 }243}244impl<I> DoubleEndedIterator for WithExactSize<I>245where246 I: DoubleEndedIterator,247{248 fn next_back(&mut self) -> Option<Self::Item> {249 self.0.next_back()250 }251 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {252 self.0.nth_back(n)253 }254}255impl<I> ExactSizeIterator for WithExactSize<I>256where257 I: Iterator,258{259 fn len(&self) -> usize {260 self.1261 }262}263impl ArrayLike for ExtendedArray {264 fn get(&self, index: usize) -> Result<Option<Val>> {265 if self.split > index {266 self.a.get(index)267 } else {268 self.b.get(index - self.split)269 }270 }271 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {272 if self.split > index {273 self.a.get_lazy(index)274 } else {275 self.b.get_lazy(index - self.split)276 }277 }278279 fn len(&self) -> usize {280 self.len281 }282283 fn get_cheap(&self, index: usize) -> Option<Val> {284 if self.split > index {285 self.a.get_cheap(index)286 } else {287 self.b.get_cheap(index - self.split)288 }289 }290 fn is_cheap(&self) -> bool {291 self.a.is_cheap() && self.b.is_cheap()292 }293}294295#[derive(Trace, Debug)]296pub struct LazyArray(pub Vec<Thunk<Val>>);297impl ArrayLike for LazyArray {298 fn len(&self) -> usize {299 self.0.len()300 }301 fn get(&self, index: usize) -> Result<Option<Val>> {302 let Some(v) = self.0.get(index) else {303 return Ok(None);304 };305 v.evaluate().map(Some)306 }307 fn get_cheap(&self, _index: usize) -> Option<Val> {308 None309 }310 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {311 self.0.get(index).cloned()312 }313 fn is_cheap(&self) -> bool {314 false315 }316}317318#[derive(Trace, Debug)]319pub struct EagerArray(pub Vec<Val>);320impl ArrayLike for EagerArray {321 fn len(&self) -> usize {322 self.0.len()323 }324325 fn get(&self, index: usize) -> Result<Option<Val>> {326 Ok(self.0.get(index).cloned())327 }328329 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {330 self.0.get(index).cloned().map(Thunk::evaluated)331 }332333 fn get_cheap(&self, index: usize) -> Option<Val> {334 self.0.get(index).cloned()335 }336 fn is_cheap(&self) -> bool {337 true338 }339}340341342#[derive(Debug, Trace, PartialEq, Eq)]343pub struct RangeArray {344 start: i32,345 end: i32,346}347impl RangeArray {348 pub fn empty() -> Self {349 Self::new_exclusive(0, 0)350 }351 pub fn new_exclusive(start: i32, end: i32) -> Self {352 end.checked_sub(1)353 .map_or_else(Self::empty, |end| Self { start, end })354 }355 pub fn new_inclusive(start: i32, end: i32) -> Self {356 Self { start, end }357 }358 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {359 WithExactSize(360 self.start..=self.end,361 (self.end as usize)362 .wrapping_sub(self.start as usize)363 .wrapping_add(1),364 )365 }366}367368impl ArrayLike for RangeArray {369 fn len(&self) -> usize {370 self.range().len()371 }372 fn is_empty(&self) -> bool {373 self.range().len() == 0374 }375376 fn get(&self, index: usize) -> Result<Option<Val>> {377 Ok(self.get_cheap(index))378 }379380 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {381 self.get_cheap(index).map(Thunk::evaluated)382 }383384 fn get_cheap(&self, index: usize) -> Option<Val> {385 self.range().nth(index).map(|i| Val::Num(i.into()))386 }387 fn is_cheap(&self) -> bool {388 true389 }390}391392#[derive(Debug, Trace)]393pub struct ReverseArray(pub ArrValue);394impl ArrayLike for ReverseArray {395 fn len(&self) -> usize {396 self.0.len()397 }398399 fn get(&self, index: usize) -> Result<Option<Val>> {400 self.0.get(self.0.len() - index - 1)401 }402403 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {404 self.0.get_lazy(self.0.len() - index - 1)405 }406407 fn get_cheap(&self, index: usize) -> Option<Val> {408 self.0.get_cheap(self.0.len() - index - 1)409 }410 fn is_cheap(&self) -> bool {411 self.0.is_cheap()412 }413}414415#[derive(Trace, Debug, Clone)]416pub struct MappedArray<const WITH_INDEX: bool> {417 inner: ArrValue,418 cached: Cc<RefCell<Vec<ArrayThunk<()>>>>,419 mapper: FuncVal,420}421impl<const WITH_INDEX: bool> MappedArray<WITH_INDEX> {422 pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {423 let len = inner.len();424 Self {425 inner,426 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting(()); len])),427 mapper,428 }429 }430 fn evaluate(&self, index: usize, value: Val) -> Result<Val> {431 if WITH_INDEX {432 self.mapper.evaluate_simple(&(index, value), false)433 } else {434 self.mapper.evaluate_simple(&(value,), false)435 }436 }437}438impl<const WITH_INDEX: bool> ArrayLike for MappedArray<WITH_INDEX> {439 fn len(&self) -> usize {440 self.cached.borrow().len()441 }442443 fn get(&self, index: usize) -> Result<Option<Val>> {444 if index >= self.len() {445 return Ok(None);446 }447 match &self.cached.borrow()[index] {448 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),449 ArrayThunk::Errored(e) => return Err(e.clone()),450 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),451 ArrayThunk::Waiting(..) => {}452 };453454 let ArrayThunk::Waiting(()) =455 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)456 else {457 unreachable!()458 };459460 let val = self461 .inner462 .get(index)463 .transpose()464 .expect("index checked")465 .and_then(|r| self.evaluate(index, r));466467 let new_value = match val {468 Ok(v) => v,469 Err(e) => {470 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());471 return Err(e);472 }473 };474 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());475 Ok(Some(new_value))476 }477 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {478 if index >= self.len() {479 return None;480 }481 match &self.cached.borrow()[index] {482 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),483 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),484 ArrayThunk::Waiting(()) | ArrayThunk::Pending => {}485 };486487 let arr_thunk = self.clone();488 Some(Thunk!(move || {489 arr_thunk.get(index).transpose().expect("index checked")490 }))491 }492493 fn get_cheap(&self, _index: usize) -> Option<Val> {494 None495 }496 fn is_cheap(&self) -> bool {497 false498 }499}500501#[derive(Trace, Debug)]502pub struct RepeatedArray {503 data: ArrValue,504 repeats: usize,505 total_len: usize,506}507impl RepeatedArray {508 pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {509 let total_len = data.len().checked_mul(repeats)?;510 Some(Self {511 data,512 repeats,513 total_len,514 })515 }516}517518impl ArrayLike for RepeatedArray {519 fn len(&self) -> usize {520 self.total_len521 }522523 fn get(&self, index: usize) -> Result<Option<Val>> {524 if index > self.total_len {525 return Ok(None);526 }527 self.data.get(index % self.data.len())528 }529530 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {531 if index > self.total_len {532 return None;533 }534 self.data.get_lazy(index % self.data.len())535 }536537 fn get_cheap(&self, index: usize) -> Option<Val> {538 if index > self.total_len {539 return None;540 }541 self.data.get_cheap(index % self.data.len())542 }543 fn is_cheap(&self) -> bool {544 self.data.is_cheap()545 }546}547548#[derive(Trace, Debug)]549pub struct PickObjectValues {550 obj: ObjValue,551 keys: Vec<IStr>,552}553554impl PickObjectValues {555 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {556 Self { obj, keys }557 }558}559560impl ArrayLike for PickObjectValues {561 fn len(&self) -> usize {562 self.keys.len()563 }564565 fn get(&self, index: usize) -> Result<Option<Val>> {566 let Some(key) = self.keys.get(index) else {567 return Ok(None);568 };569 Ok(Some(self.obj.get_or_bail(key.clone())?))570 }571572 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {573 let key = self.keys.get(index)?;574 Some(self.obj.get_lazy_or_bail(key.clone()))575 }576577 fn get_cheap(&self, _index: usize) -> Option<Val> {578 None579 }580581 fn is_cheap(&self) -> bool {582 false583 }584}585586#[derive(Trace, Debug)]587pub struct PickObjectKeyValues {588 obj: ObjValue,589 keys: Vec<IStr>,590}591592impl PickObjectKeyValues {593 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {594 Self { obj, keys }595 }596}597598#[derive(Typed)]599pub struct KeyValue {600 key: IStr,601 value: Thunk<Val>,602}603604impl ArrayLike for PickObjectKeyValues {605 fn len(&self) -> usize {606 self.keys.len()607 }608609 fn get(&self, index: usize) -> Result<Option<Val>> {610 let Some(key) = self.keys.get(index) else {611 return Ok(None);612 };613 Ok(Some(614 KeyValue::into_untyped(KeyValue {615 key: key.clone(),616 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),617 })618 .expect("convertible"),619 ))620 }621622 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {623 let key = self.keys.get(index)?;624 625 626 Some(Thunk::evaluated(627 KeyValue::into_untyped(KeyValue {628 key: key.clone(),629 value: self.obj.get_lazy_or_bail(key.clone()),630 })631 .expect("convertible"),632 ))633 }634635 fn get_cheap(&self, _index: usize) -> Option<Val> {636 None637 }638639 fn is_cheap(&self) -> bool {640 false641 }642}