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 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {354 WithExactSize(355 self.start..=self.end,356 (self.end as usize)357 .wrapping_sub(self.start as usize)358 .wrapping_add(1),359 )360 }361}362363impl ArrayLike for RangeArray {364 fn len(&self) -> usize {365 self.range().len()366 }367 fn is_empty(&self) -> bool {368 self.range().len() == 0369 }370371 fn get(&self, index: usize) -> Result<Option<Val>> {372 Ok(self.get_cheap(index))373 }374375 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {376 self.get_cheap(index).map(Thunk::evaluated)377 }378379 fn get_cheap(&self, index: usize) -> Option<Val> {380 self.range().nth(index).map(|i| Val::Num(i.into()))381 }382 fn is_cheap(&self) -> bool {383 true384 }385}386387#[derive(Debug, Trace)]388pub struct ReverseArray(pub ArrValue);389impl ArrayLike for ReverseArray {390 fn len(&self) -> usize {391 self.0.len()392 }393394 fn get(&self, index: usize) -> Result<Option<Val>> {395 self.0.get(self.0.len() - index - 1)396 }397398 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {399 self.0.get_lazy(self.0.len() - index - 1)400 }401402 fn get_cheap(&self, index: usize) -> Option<Val> {403 self.0.get_cheap(self.0.len() - index - 1)404 }405 fn is_cheap(&self) -> bool {406 self.0.is_cheap()407 }408}409410#[derive(Trace, Clone, Debug)]411pub enum ArrayMapper {412 Plain(NativeFn!((Val) -> Val)),413 WithIndex(NativeFn!((u32, Val) -> Val)),414}415416#[derive(Trace, Debug, Clone)]417pub struct MappedArray {418 inner: ArrValue,419 cached: Cc<RefCell<Vec<ArrayThunk>>>,420 mapper: ArrayMapper,421}422impl MappedArray {423 pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {424 let len = inner.len();425 Self {426 inner,427 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len])),428 mapper,429 }430 }431 fn evaluate(&self, index: usize, value: Val) -> Result<Val> {432 match &self.mapper {433 ArrayMapper::Plain(f) => f.call(value),434 ArrayMapper::WithIndex(f) => f.call(index as u32, value),435 }436 }437}438impl ArrayLike for MappedArray {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 #[derive(Trace)]479 struct MappedArrayThunk {480 arr: MappedArray,481 index: usize,482 }483 impl ThunkValue for MappedArrayThunk {484 type Output = Val;485486 fn get(&self) -> Result<Self::Output> {487 self.arr.get(self.index).transpose().expect("index checked")488 }489 }490491 if index >= self.len() {492 return None;493 }494 match &self.cached.borrow()[index] {495 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),496 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),497 ArrayThunk::Waiting | ArrayThunk::Pending => {}498 }499500 Some(Thunk::new(MappedArrayThunk {501 arr: self.clone(),502 index,503 }))504 }505506 fn get_cheap(&self, _index: usize) -> Option<Val> {507 None508 }509 fn is_cheap(&self) -> bool {510 false511 }512}513514#[derive(Trace, Debug)]515pub struct RepeatedArray {516 data: ArrValue,517 repeats: usize,518 total_len: usize,519}520impl RepeatedArray {521 pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {522 let total_len = data.len().checked_mul(repeats)?;523 Some(Self {524 data,525 repeats,526 total_len,527 })528 }529}530531impl ArrayLike for RepeatedArray {532 fn len(&self) -> usize {533 self.total_len534 }535536 fn get(&self, index: usize) -> Result<Option<Val>> {537 if index > self.total_len {538 return Ok(None);539 }540 self.data.get(index % self.data.len())541 }542543 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {544 if index > self.total_len {545 return None;546 }547 self.data.get_lazy(index % self.data.len())548 }549550 fn get_cheap(&self, index: usize) -> Option<Val> {551 if index > self.total_len {552 return None;553 }554 self.data.get_cheap(index % self.data.len())555 }556 fn is_cheap(&self) -> bool {557 self.data.is_cheap()558 }559}560561#[derive(Trace, Debug)]562pub struct PickObjectValues {563 obj: ObjValue,564 keys: Vec<IStr>,565}566567impl PickObjectValues {568 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {569 Self { obj, keys }570 }571}572573impl ArrayLike for PickObjectValues {574 fn len(&self) -> usize {575 self.keys.len()576 }577578 fn get(&self, index: usize) -> Result<Option<Val>> {579 let Some(key) = self.keys.get(index) else {580 return Ok(None);581 };582 Ok(Some(self.obj.get_or_bail(key.clone())?))583 }584585 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {586 let key = self.keys.get(index)?;587 Some(self.obj.get_lazy_or_bail(key.clone()))588 }589590 fn get_cheap(&self, _index: usize) -> Option<Val> {591 None592 }593594 fn is_cheap(&self) -> bool {595 false596 }597}598599#[derive(Trace, Debug)]600pub struct PickObjectKeyValues {601 obj: ObjValue,602 keys: Vec<IStr>,603}604605impl PickObjectKeyValues {606 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {607 Self { obj, keys }608 }609}610611#[derive(Typed, IntoUntyped)]612pub struct KeyValue {613 key: IStr,614 value: Thunk<Val>,615}616617impl ArrayLike for PickObjectKeyValues {618 fn len(&self) -> usize {619 self.keys.len()620 }621622 fn get(&self, index: usize) -> Result<Option<Val>> {623 let Some(key) = self.keys.get(index) else {624 return Ok(None);625 };626 Ok(Some(627 KeyValue::into_untyped(KeyValue {628 key: key.clone(),629 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),630 })631 .expect("convertible"),632 ))633 }634635 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {636 let key = self.keys.get(index)?;637 638 639 Some(Thunk::evaluated(640 KeyValue::into_untyped(KeyValue {641 key: key.clone(),642 value: self.obj.get_lazy_or_bail(key.clone()),643 })644 .expect("convertible"),645 ))646 }647648 fn get_cheap(&self, _index: usize) -> Option<Val> {649 None650 }651652 fn is_cheap(&self) -> bool {653 false654 }655}