difftreelog
fix enforce Val::Num finityness at type level
in: master
13 files changed
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth1use 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 val::ThunkValue, 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(f64::from(*v)))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 #[derive(Trace)]186 struct ArrayElement {187 arr_thunk: ExprArray,188 index: usize,189 }190191 impl ThunkValue for ArrayElement {192 type Output = Val;193194 fn get(self: Box<Self>) -> Result<Self::Output> {195 self.arr_thunk196 .get(self.index)197 .transpose()198 .expect("index checked")199 }200 }201202 if index >= self.len() {203 return None;204 }205 match &self.cached.borrow()[index] {206 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),207 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),208 ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}209 };210211 Some(Thunk::new(ArrayElement {212 arr_thunk: self.clone(),213 index,214 }))215 }216 fn get_cheap(&self, _index: usize) -> Option<Val> {217 None218 }219 fn is_cheap(&self) -> bool {220 false221 }222}223224#[derive(Trace, Debug)]225pub struct ExtendedArray {226 pub a: ArrValue,227 pub b: ArrValue,228 split: usize,229 len: usize,230}231impl ExtendedArray {232 pub fn new(a: ArrValue, b: ArrValue) -> Self {233 let a_len = a.len();234 let b_len = b.len();235 Self {236 a,237 b,238 split: a_len,239 len: a_len.checked_add(b_len).expect("too large array value"),240 }241 }242}243244struct WithExactSize<I>(I, usize);245impl<I, T> Iterator for WithExactSize<I>246where247 I: Iterator<Item = T>,248{249 type Item = T;250251 fn next(&mut self) -> Option<Self::Item> {252 self.0.next()253 }254 fn nth(&mut self, n: usize) -> Option<Self::Item> {255 self.0.nth(n)256 }257 fn size_hint(&self) -> (usize, Option<usize>) {258 (self.1, Some(self.1))259 }260}261impl<I> DoubleEndedIterator for WithExactSize<I>262where263 I: DoubleEndedIterator,264{265 fn next_back(&mut self) -> Option<Self::Item> {266 self.0.next_back()267 }268 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {269 self.0.nth_back(n)270 }271}272impl<I> ExactSizeIterator for WithExactSize<I>273where274 I: Iterator,275{276 fn len(&self) -> usize {277 self.1278 }279}280impl ArrayLike for ExtendedArray {281 fn get(&self, index: usize) -> Result<Option<Val>> {282 if self.split > index {283 self.a.get(index)284 } else {285 self.b.get(index - self.split)286 }287 }288 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {289 if self.split > index {290 self.a.get_lazy(index)291 } else {292 self.b.get_lazy(index - self.split)293 }294 }295296 fn len(&self) -> usize {297 self.len298 }299300 fn get_cheap(&self, index: usize) -> Option<Val> {301 if self.split > index {302 self.a.get_cheap(index)303 } else {304 self.b.get_cheap(index - self.split)305 }306 }307 fn is_cheap(&self) -> bool {308 self.a.is_cheap() && self.b.is_cheap()309 }310}311312#[derive(Trace, Debug)]313pub struct LazyArray(pub Vec<Thunk<Val>>);314impl ArrayLike for LazyArray {315 fn len(&self) -> usize {316 self.0.len()317 }318 fn get(&self, index: usize) -> Result<Option<Val>> {319 let Some(v) = self.0.get(index) else {320 return Ok(None);321 };322 v.evaluate().map(Some)323 }324 fn get_cheap(&self, _index: usize) -> Option<Val> {325 None326 }327 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {328 self.0.get(index).cloned()329 }330 fn is_cheap(&self) -> bool {331 false332 }333}334335#[derive(Trace, Debug)]336pub struct EagerArray(pub Vec<Val>);337impl ArrayLike for EagerArray {338 fn len(&self) -> usize {339 self.0.len()340 }341342 fn get(&self, index: usize) -> Result<Option<Val>> {343 Ok(self.0.get(index).cloned())344 }345346 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {347 self.0.get(index).cloned().map(Thunk::evaluated)348 }349350 fn get_cheap(&self, index: usize) -> Option<Val> {351 self.0.get(index).cloned()352 }353 fn is_cheap(&self) -> bool {354 true355 }356}357358/// Inclusive range type359#[derive(Debug, Trace, PartialEq, Eq)]360pub struct RangeArray {361 start: i32,362 end: i32,363}364impl RangeArray {365 pub fn empty() -> Self {366 Self::new_exclusive(0, 0)367 }368 pub fn new_exclusive(start: i32, end: i32) -> Self {369 end.checked_sub(1)370 .map_or_else(Self::empty, |end| Self { start, end })371 }372 pub fn new_inclusive(start: i32, end: i32) -> Self {373 Self { start, end }374 }375 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {376 WithExactSize(377 self.start..=self.end,378 (self.end as usize)379 .wrapping_sub(self.start as usize)380 .wrapping_add(1),381 )382 }383}384385impl ArrayLike for RangeArray {386 fn len(&self) -> usize {387 self.range().len()388 }389 fn is_empty(&self) -> bool {390 self.range().len() == 0391 }392393 fn get(&self, index: usize) -> Result<Option<Val>> {394 Ok(self.get_cheap(index))395 }396397 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {398 self.get_cheap(index).map(Thunk::evaluated)399 }400401 fn get_cheap(&self, index: usize) -> Option<Val> {402 self.range().nth(index).map(|i| Val::Num(f64::from(i)))403 }404 fn is_cheap(&self) -> bool {405 true406 }407}408409#[derive(Debug, Trace)]410pub struct ReverseArray(pub ArrValue);411impl ArrayLike for ReverseArray {412 fn len(&self) -> usize {413 self.0.len()414 }415416 fn get(&self, index: usize) -> Result<Option<Val>> {417 self.0.get(self.0.len() - index - 1)418 }419420 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {421 self.0.get_lazy(self.0.len() - index - 1)422 }423424 fn get_cheap(&self, index: usize) -> Option<Val> {425 self.0.get_cheap(self.0.len() - index - 1)426 }427 fn is_cheap(&self) -> bool {428 self.0.is_cheap()429 }430}431432#[derive(Trace, Debug, Clone)]433pub struct MappedArray<const WithIndex: bool> {434 inner: ArrValue,435 cached: Cc<RefCell<Vec<ArrayThunk<()>>>>,436 mapper: FuncVal,437}438impl<const WithIndex: bool> MappedArray<WithIndex> {439 pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {440 let len = inner.len();441 Self {442 inner,443 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting(()); len])),444 mapper,445 }446 }447 fn evaluate(&self, index: usize, value: Val) -> Result<Val> {448 if WithIndex {449 self.mapper.evaluate_simple(&(index, value), false)450 } else {451 self.mapper.evaluate_simple(&(value,), false)452 }453 }454}455impl<const WithIndex: bool> ArrayLike for MappedArray<WithIndex> {456 fn len(&self) -> usize {457 self.cached.borrow().len()458 }459460 fn get(&self, index: usize) -> Result<Option<Val>> {461 if index >= self.len() {462 return Ok(None);463 }464 match &self.cached.borrow()[index] {465 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),466 ArrayThunk::Errored(e) => return Err(e.clone()),467 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),468 ArrayThunk::Waiting(..) => {}469 };470471 let ArrayThunk::Waiting(()) =472 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)473 else {474 unreachable!()475 };476477 let val = self478 .inner479 .get(index)480 .transpose()481 .expect("index checked")482 .and_then(|r| self.evaluate(index, r));483484 let new_value = match val {485 Ok(v) => v,486 Err(e) => {487 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());488 return Err(e);489 }490 };491 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());492 Ok(Some(new_value))493 }494 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {495 #[derive(Trace)]496 struct ArrayElement<const WithIndex: bool> {497 arr_thunk: MappedArray<WithIndex>,498 index: usize,499 }500501 impl<const WithIndex: bool> ThunkValue for ArrayElement<WithIndex> {502 type Output = Val;503504 fn get(self: Box<Self>) -> Result<Self::Output> {505 self.arr_thunk506 .get(self.index)507 .transpose()508 .expect("index checked")509 }510 }511512 if index >= self.len() {513 return None;514 }515 match &self.cached.borrow()[index] {516 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),517 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),518 ArrayThunk::Waiting(()) | ArrayThunk::Pending => {}519 };520521 Some(Thunk::new(ArrayElement {522 arr_thunk: self.clone(),523 index,524 }))525 }526527 fn get_cheap(&self, _index: usize) -> Option<Val> {528 None529 }530 fn is_cheap(&self) -> bool {531 false532 }533}534535#[derive(Trace, Debug)]536pub struct RepeatedArray {537 data: ArrValue,538 repeats: usize,539 total_len: usize,540}541impl RepeatedArray {542 pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {543 let total_len = data.len().checked_mul(repeats)?;544 Some(Self {545 data,546 repeats,547 total_len,548 })549 }550}551552impl ArrayLike for RepeatedArray {553 fn len(&self) -> usize {554 self.total_len555 }556557 fn get(&self, index: usize) -> Result<Option<Val>> {558 if index > self.total_len {559 return Ok(None);560 }561 self.data.get(index % self.data.len())562 }563564 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {565 if index > self.total_len {566 return None;567 }568 self.data.get_lazy(index % self.data.len())569 }570571 fn get_cheap(&self, index: usize) -> Option<Val> {572 if index > self.total_len {573 return None;574 }575 self.data.get_cheap(index % self.data.len())576 }577 fn is_cheap(&self) -> bool {578 self.data.is_cheap()579 }580}581582#[derive(Trace, Debug)]583pub struct PickObjectValues {584 obj: ObjValue,585 keys: Vec<IStr>,586}587588impl PickObjectValues {589 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {590 Self { obj, keys }591 }592}593594impl ArrayLike for PickObjectValues {595 fn len(&self) -> usize {596 self.keys.len()597 }598599 fn get(&self, index: usize) -> Result<Option<Val>> {600 let Some(key) = self.keys.get(index) else {601 return Ok(None);602 };603 Ok(Some(self.obj.get_or_bail(key.clone())?))604 }605606 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {607 let key = self.keys.get(index)?;608 Some(self.obj.get_lazy_or_bail(key.clone()))609 }610611 fn get_cheap(&self, _index: usize) -> Option<Val> {612 None613 }614615 fn is_cheap(&self) -> bool {616 false617 }618}619620#[derive(Trace, Debug)]621pub struct PickObjectKeyValues {622 obj: ObjValue,623 keys: Vec<IStr>,624}625626impl PickObjectKeyValues {627 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {628 Self { obj, keys }629 }630}631632#[derive(Typed)]633pub struct KeyValue {634 key: IStr,635 value: Thunk<Val>,636}637638impl ArrayLike for PickObjectKeyValues {639 fn len(&self) -> usize {640 self.keys.len()641 }642643 fn get(&self, index: usize) -> Result<Option<Val>> {644 let Some(key) = self.keys.get(index) else {645 return Ok(None);646 };647 Ok(Some(648 KeyValue::into_untyped(KeyValue {649 key: key.clone(),650 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),651 })652 .expect("convertible"),653 ))654 }655656 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {657 let key = self.keys.get(index)?;658 // Nothing can fail in the key part, yet value is still659 // lazy-evaluated660 Some(Thunk::evaluated(661 KeyValue::into_untyped(KeyValue {662 key: key.clone(),663 value: self.obj.get_lazy_or_bail(key.clone()),664 })665 .expect("convertible"),666 ))667 }668669 fn get_cheap(&self, _index: usize) -> Option<Val> {670 None671 }672673 fn is_cheap(&self) -> bool {674 false675 }676}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 val::ThunkValue, 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 #[derive(Trace)]186 struct ArrayElement {187 arr_thunk: ExprArray,188 index: usize,189 }190191 impl ThunkValue for ArrayElement {192 type Output = Val;193194 fn get(self: Box<Self>) -> Result<Self::Output> {195 self.arr_thunk196 .get(self.index)197 .transpose()198 .expect("index checked")199 }200 }201202 if index >= self.len() {203 return None;204 }205 match &self.cached.borrow()[index] {206 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),207 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),208 ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}209 };210211 Some(Thunk::new(ArrayElement {212 arr_thunk: self.clone(),213 index,214 }))215 }216 fn get_cheap(&self, _index: usize) -> Option<Val> {217 None218 }219 fn is_cheap(&self) -> bool {220 false221 }222}223224#[derive(Trace, Debug)]225pub struct ExtendedArray {226 pub a: ArrValue,227 pub b: ArrValue,228 split: usize,229 len: usize,230}231impl ExtendedArray {232 pub fn new(a: ArrValue, b: ArrValue) -> Self {233 let a_len = a.len();234 let b_len = b.len();235 Self {236 a,237 b,238 split: a_len,239 len: a_len.checked_add(b_len).expect("too large array value"),240 }241 }242}243244struct WithExactSize<I>(I, usize);245impl<I, T> Iterator for WithExactSize<I>246where247 I: Iterator<Item = T>,248{249 type Item = T;250251 fn next(&mut self) -> Option<Self::Item> {252 self.0.next()253 }254 fn nth(&mut self, n: usize) -> Option<Self::Item> {255 self.0.nth(n)256 }257 fn size_hint(&self) -> (usize, Option<usize>) {258 (self.1, Some(self.1))259 }260}261impl<I> DoubleEndedIterator for WithExactSize<I>262where263 I: DoubleEndedIterator,264{265 fn next_back(&mut self) -> Option<Self::Item> {266 self.0.next_back()267 }268 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {269 self.0.nth_back(n)270 }271}272impl<I> ExactSizeIterator for WithExactSize<I>273where274 I: Iterator,275{276 fn len(&self) -> usize {277 self.1278 }279}280impl ArrayLike for ExtendedArray {281 fn get(&self, index: usize) -> Result<Option<Val>> {282 if self.split > index {283 self.a.get(index)284 } else {285 self.b.get(index - self.split)286 }287 }288 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {289 if self.split > index {290 self.a.get_lazy(index)291 } else {292 self.b.get_lazy(index - self.split)293 }294 }295296 fn len(&self) -> usize {297 self.len298 }299300 fn get_cheap(&self, index: usize) -> Option<Val> {301 if self.split > index {302 self.a.get_cheap(index)303 } else {304 self.b.get_cheap(index - self.split)305 }306 }307 fn is_cheap(&self) -> bool {308 self.a.is_cheap() && self.b.is_cheap()309 }310}311312#[derive(Trace, Debug)]313pub struct LazyArray(pub Vec<Thunk<Val>>);314impl ArrayLike for LazyArray {315 fn len(&self) -> usize {316 self.0.len()317 }318 fn get(&self, index: usize) -> Result<Option<Val>> {319 let Some(v) = self.0.get(index) else {320 return Ok(None);321 };322 v.evaluate().map(Some)323 }324 fn get_cheap(&self, _index: usize) -> Option<Val> {325 None326 }327 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {328 self.0.get(index).cloned()329 }330 fn is_cheap(&self) -> bool {331 false332 }333}334335#[derive(Trace, Debug)]336pub struct EagerArray(pub Vec<Val>);337impl ArrayLike for EagerArray {338 fn len(&self) -> usize {339 self.0.len()340 }341342 fn get(&self, index: usize) -> Result<Option<Val>> {343 Ok(self.0.get(index).cloned())344 }345346 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {347 self.0.get(index).cloned().map(Thunk::evaluated)348 }349350 fn get_cheap(&self, index: usize) -> Option<Val> {351 self.0.get(index).cloned()352 }353 fn is_cheap(&self) -> bool {354 true355 }356}357358/// Inclusive range type359#[derive(Debug, Trace, PartialEq, Eq)]360pub struct RangeArray {361 start: i32,362 end: i32,363}364impl RangeArray {365 pub fn empty() -> Self {366 Self::new_exclusive(0, 0)367 }368 pub fn new_exclusive(start: i32, end: i32) -> Self {369 end.checked_sub(1)370 .map_or_else(Self::empty, |end| Self { start, end })371 }372 pub fn new_inclusive(start: i32, end: i32) -> Self {373 Self { start, end }374 }375 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {376 WithExactSize(377 self.start..=self.end,378 (self.end as usize)379 .wrapping_sub(self.start as usize)380 .wrapping_add(1),381 )382 }383}384385impl ArrayLike for RangeArray {386 fn len(&self) -> usize {387 self.range().len()388 }389 fn is_empty(&self) -> bool {390 self.range().len() == 0391 }392393 fn get(&self, index: usize) -> Result<Option<Val>> {394 Ok(self.get_cheap(index))395 }396397 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {398 self.get_cheap(index).map(Thunk::evaluated)399 }400401 fn get_cheap(&self, index: usize) -> Option<Val> {402 self.range().nth(index).map(|i| Val::Num(i.into()))403 }404 fn is_cheap(&self) -> bool {405 true406 }407}408409#[derive(Debug, Trace)]410pub struct ReverseArray(pub ArrValue);411impl ArrayLike for ReverseArray {412 fn len(&self) -> usize {413 self.0.len()414 }415416 fn get(&self, index: usize) -> Result<Option<Val>> {417 self.0.get(self.0.len() - index - 1)418 }419420 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {421 self.0.get_lazy(self.0.len() - index - 1)422 }423424 fn get_cheap(&self, index: usize) -> Option<Val> {425 self.0.get_cheap(self.0.len() - index - 1)426 }427 fn is_cheap(&self) -> bool {428 self.0.is_cheap()429 }430}431432#[derive(Trace, Debug, Clone)]433pub struct MappedArray<const WITH_INDEX: bool> {434 inner: ArrValue,435 cached: Cc<RefCell<Vec<ArrayThunk<()>>>>,436 mapper: FuncVal,437}438impl<const WITH_INDEX: bool> MappedArray<WITH_INDEX> {439 pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {440 let len = inner.len();441 Self {442 inner,443 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting(()); len])),444 mapper,445 }446 }447 fn evaluate(&self, index: usize, value: Val) -> Result<Val> {448 if WITH_INDEX {449 self.mapper.evaluate_simple(&(index, value), false)450 } else {451 self.mapper.evaluate_simple(&(value,), false)452 }453 }454}455impl<const WITH_INDEX: bool> ArrayLike for MappedArray<WITH_INDEX> {456 fn len(&self) -> usize {457 self.cached.borrow().len()458 }459460 fn get(&self, index: usize) -> Result<Option<Val>> {461 if index >= self.len() {462 return Ok(None);463 }464 match &self.cached.borrow()[index] {465 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),466 ArrayThunk::Errored(e) => return Err(e.clone()),467 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),468 ArrayThunk::Waiting(..) => {}469 };470471 let ArrayThunk::Waiting(()) =472 replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)473 else {474 unreachable!()475 };476477 let val = self478 .inner479 .get(index)480 .transpose()481 .expect("index checked")482 .and_then(|r| self.evaluate(index, r));483484 let new_value = match val {485 Ok(v) => v,486 Err(e) => {487 self.cached.borrow_mut()[index] = ArrayThunk::Errored(e.clone());488 return Err(e);489 }490 };491 self.cached.borrow_mut()[index] = ArrayThunk::Computed(new_value.clone());492 Ok(Some(new_value))493 }494 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {495 #[derive(Trace)]496 struct ArrayElement<const WITH_INDEX: bool> {497 arr_thunk: MappedArray<WITH_INDEX>,498 index: usize,499 }500501 impl<const WITH_INDEX: bool> ThunkValue for ArrayElement<WITH_INDEX> {502 type Output = Val;503504 fn get(self: Box<Self>) -> Result<Self::Output> {505 self.arr_thunk506 .get(self.index)507 .transpose()508 .expect("index checked")509 }510 }511512 if index >= self.len() {513 return None;514 }515 match &self.cached.borrow()[index] {516 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),517 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),518 ArrayThunk::Waiting(()) | ArrayThunk::Pending => {}519 };520521 Some(Thunk::new(ArrayElement {522 arr_thunk: self.clone(),523 index,524 }))525 }526527 fn get_cheap(&self, _index: usize) -> Option<Val> {528 None529 }530 fn is_cheap(&self) -> bool {531 false532 }533}534535#[derive(Trace, Debug)]536pub struct RepeatedArray {537 data: ArrValue,538 repeats: usize,539 total_len: usize,540}541impl RepeatedArray {542 pub fn new(data: ArrValue, repeats: usize) -> Option<Self> {543 let total_len = data.len().checked_mul(repeats)?;544 Some(Self {545 data,546 repeats,547 total_len,548 })549 }550}551552impl ArrayLike for RepeatedArray {553 fn len(&self) -> usize {554 self.total_len555 }556557 fn get(&self, index: usize) -> Result<Option<Val>> {558 if index > self.total_len {559 return Ok(None);560 }561 self.data.get(index % self.data.len())562 }563564 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {565 if index > self.total_len {566 return None;567 }568 self.data.get_lazy(index % self.data.len())569 }570571 fn get_cheap(&self, index: usize) -> Option<Val> {572 if index > self.total_len {573 return None;574 }575 self.data.get_cheap(index % self.data.len())576 }577 fn is_cheap(&self) -> bool {578 self.data.is_cheap()579 }580}581582#[derive(Trace, Debug)]583pub struct PickObjectValues {584 obj: ObjValue,585 keys: Vec<IStr>,586}587588impl PickObjectValues {589 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {590 Self { obj, keys }591 }592}593594impl ArrayLike for PickObjectValues {595 fn len(&self) -> usize {596 self.keys.len()597 }598599 fn get(&self, index: usize) -> Result<Option<Val>> {600 let Some(key) = self.keys.get(index) else {601 return Ok(None);602 };603 Ok(Some(self.obj.get_or_bail(key.clone())?))604 }605606 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {607 let key = self.keys.get(index)?;608 Some(self.obj.get_lazy_or_bail(key.clone()))609 }610611 fn get_cheap(&self, _index: usize) -> Option<Val> {612 None613 }614615 fn is_cheap(&self) -> bool {616 false617 }618}619620#[derive(Trace, Debug)]621pub struct PickObjectKeyValues {622 obj: ObjValue,623 keys: Vec<IStr>,624}625626impl PickObjectKeyValues {627 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {628 Self { obj, keys }629 }630}631632#[derive(Typed)]633pub struct KeyValue {634 key: IStr,635 value: Thunk<Val>,636}637638impl ArrayLike for PickObjectKeyValues {639 fn len(&self) -> usize {640 self.keys.len()641 }642643 fn get(&self, index: usize) -> Result<Option<Val>> {644 let Some(key) = self.keys.get(index) else {645 return Ok(None);646 };647 Ok(Some(648 KeyValue::into_untyped(KeyValue {649 key: key.clone(),650 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),651 })652 .expect("convertible"),653 ))654 }655656 fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {657 let key = self.keys.get(index)?;658 // Nothing can fail in the key part, yet value is still659 // lazy-evaluated660 Some(Thunk::evaluated(661 KeyValue::into_untyped(KeyValue {662 key: key.clone(),663 value: self.obj.get_lazy_or_bail(key.clone()),664 })665 .expect("convertible"),666 ))667 }668669 fn get_cheap(&self, _index: usize) -> Option<Val> {670 None671 }672673 fn is_cheap(&self) -> bool {674 false675 }676}crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -1,7 +1,5 @@
use std::{
- cmp::Ordering,
- fmt::{Debug, Display},
- path::PathBuf,
+ cmp::Ordering, convert::Infallible, fmt::{Debug, Display}, path::PathBuf
};
use jrsonnet_gcmodule::Trace;
@@ -14,6 +12,7 @@
function::{builtin::ParamDefault, CallLocation},
stdlib::format::FormatError,
typed::TypeLocError,
+ val::ConvertNumValueError,
ObjValue,
};
@@ -236,6 +235,9 @@
#[error("invalid unicode codepoint: {0}")]
InvalidUnicodeCodepointGot(u32),
+ #[error("convert num value: {0}")]
+ ConvertNumValue(#[from] ConvertNumValueError),
+
#[error("format error: {0}")]
Format(#[from] FormatError),
#[error("type error: {0}")]
@@ -259,6 +261,12 @@
}
}
+impl From<Infallible> for Error {
+ fn from(_value: Infallible) -> Self {
+ unreachable!()
+ }
+}
+
/// Single stack trace frame
#[derive(Clone, Debug, Trace)]
pub struct StackTraceElement {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -17,7 +17,7 @@
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
function::{CallLocation, FuncDesc, FuncVal},
typed::Typed,
- val::{CachedUnbound, IndexableVal, StrValue, Thunk, ThunkValue},
+ val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk, ThunkValue},
Context, Error, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
ResultExt, State, Unbound, Val,
};
@@ -37,7 +37,7 @@
}
Some(match &*expr.0 {
Expr::Str(s) => Val::string(s.clone()),
- Expr::Num(n) => Val::Num(*n),
+ Expr::Num(n) => Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values")),
Expr::Literal(LiteralType::False) => Val::Bool(false),
Expr::Literal(LiteralType::True) => Val::Bool(true),
Expr::Literal(LiteralType::Null) => Val::Null,
@@ -438,7 +438,7 @@
Literal(LiteralType::Null) => Val::Null,
Parened(e) => evaluate(ctx, e)?,
Str(v) => Val::string(v.clone()),
- Num(v) => Val::new_checked_num(*v)?,
+ Num(v) => Val::try_num(*v)?,
// I have tried to remove special behavior from super by implementing standalone-super
// expresion, but looks like this case still needs special treatment.
//
@@ -530,6 +530,7 @@
n.value_type(),
)),
(Val::Arr(v), Val::Num(n)) => {
+ let n = n.get();
if n.fract() > f64::EPSILON {
bail!(FractionalIndex)
}
@@ -553,13 +554,13 @@
.clone()
.into_flat()
.chars()
- .skip(n as usize)
+ .skip(n.get() as usize)
.take(1)
.collect::<String>()
.into();
if v.is_empty() {
let size = s.into_flat().chars().count();
- bail!(StringBoundsError(n as usize, size))
+ bail!(StringBoundsError(n.get() as usize, size))
}
StrValue::Flat(v)
}),
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -17,10 +17,10 @@
use UnaryOpType::*;
use Val::*;
Ok(match (op, b) {
- (Plus, Num(n)) => Num(*n),
- (Minus, Num(n)) => Num(-*n),
+ (Plus, Num(n)) => Val::Num(*n),
+ (Minus, Num(n)) => Val::try_num(-n.get())?,
(Not, Bool(v)) => Bool(!v),
- (BitNot, Num(n)) => Num(!(*n as i64) as f64),
+ (BitNot, Num(n)) => Val::try_num(!(n.get() as i64) as f64)?,
(op, o) => bail!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
})
}
@@ -40,7 +40,7 @@
(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
(Arr(a), Arr(b)) => Val::Arr(ArrValue::extended(a.clone(), b.clone())),
- (Num(v1), Num(v2)) => Val::new_checked_num(v1 + v2)?,
+ (Num(v1), Num(v2)) => Val::try_num(v1.get() + v2.get())?,
#[cfg(feature = "exp-bigint")]
(BigInt(a), BigInt(b)) => BigInt(Box::new(&**a + &**b)),
_ => bail!(BinaryOperatorDoesNotOperateOnValues(
@@ -55,10 +55,10 @@
use Val::*;
match (a, b) {
(Num(a), Num(b)) => {
- if *b == 0.0 {
+ if b.get() == 0.0 {
bail!(DivisionByZero)
}
- Ok(Num(a % b))
+ Ok(Val::try_num(a.get() % b.get())?)
}
(Str(str), vals) => {
String::into_untyped(std_format(&str.clone().into_flat(), vals.clone())?)
@@ -143,39 +143,39 @@
(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone().into_flat(), true)),
(a, Mod, b) => evaluate_mod_op(a, b)?,
- (Str(v1), Mul, Num(v2)) => Val::string(v1.to_string().repeat(*v2 as usize)),
+ (Str(v1), Mul, Num(v2)) => Val::string(v1.to_string().repeat(v2.get() as usize)),
// Bool X Bool
(Bool(a), And, Bool(b)) => Bool(*a && *b),
(Bool(a), Or, Bool(b)) => Bool(*a || *b),
// Num X Num
- (Num(v1), Mul, Num(v2)) => Val::new_checked_num(v1 * v2)?,
+ (Num(v1), Mul, Num(v2)) => Val::try_num(v1.get() * v2.get())?,
(Num(v1), Div, Num(v2)) => {
- if *v2 == 0.0 {
+ if v2.get() == 0.0 {
bail!(DivisionByZero)
}
- Val::new_checked_num(v1 / v2)?
+ Val::try_num(v1.get() / v2.get())?
}
- (Num(v1), Sub, Num(v2)) => Val::new_checked_num(v1 - v2)?,
+ (Num(v1), Sub, Num(v2)) => Val::try_num(v1.get() - v2.get())?,
- (Num(v1), BitAnd, Num(v2)) => Num((*v1 as i64 & *v2 as i64) as f64),
- (Num(v1), BitOr, Num(v2)) => Num((*v1 as i64 | *v2 as i64) as f64),
- (Num(v1), BitXor, Num(v2)) => Num((*v1 as i64 ^ *v2 as i64) as f64),
+ (Num(v1), BitAnd, Num(v2)) => Val::try_num((v1.get() as i64 & v2.get() as i64) as f64)?,
+ (Num(v1), BitOr, Num(v2)) => Val::try_num((v1.get() as i64 | v2.get() as i64) as f64)?,
+ (Num(v1), BitXor, Num(v2)) => Val::try_num((v1.get() as i64 ^ v2.get() as i64) as f64)?,
(Num(v1), Lhs, Num(v2)) => {
- if *v2 < 0.0 {
+ if v2.get() < 0.0 {
bail!("shift by negative exponent")
}
- let exp = ((*v2 as i64) & 63) as u32;
- Num((*v1 as i64).wrapping_shl(exp) as f64)
+ let exp = ((v2.get() as i64) & 63) as u32;
+ Val::try_num((v1.get() as i64).wrapping_shl(exp) as f64)?
}
(Num(v1), Rhs, Num(v2)) => {
- if *v2 < 0.0 {
+ if v2.get() < 0.0 {
bail!("shift by negative exponent")
}
- let exp = ((*v2 as i64) & 63) as u32;
- Num((*v1 as i64).wrapping_shr(exp) as f64)
+ let exp = ((v2.get() as i64) & 63) as u32;
+ Val::try_num((v1.get() as i64).wrapping_shr(exp) as f64)?
}
// Bigint X Bigint
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -2,7 +2,7 @@
use jrsonnet_interner::IStr;
use serde::{
- de::Visitor,
+ de::{self, Visitor},
ser::{
Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
SerializeTupleStruct, SerializeTupleVariant,
@@ -11,7 +11,8 @@
};
use crate::{
- arr::ArrValue, runtime_error, Error as JrError, ObjValue, ObjValueBuilder, Result, State, Val,
+ arr::ArrValue, runtime_error, val::NumValue, Error as JrError, ObjValue, ObjValueBuilder,
+ Result, State, Val,
};
impl<'de> Deserialize<'de> for Val {
@@ -37,22 +38,21 @@
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
- E: serde::de::Error,
+ E: de::Error,
{
Ok(Val::Bool(v))
}
fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
where
- E: serde::de::Error,
+ E: de::Error,
{
- if !v.is_finite() {
- return Err(E::custom("only finite numbers are supported"));
- }
- Ok(Val::Num(v))
+ Ok(Val::Num(NumValue::new(v).ok_or_else(|| {
+ E::custom("only finite numbers are supported")
+ })?))
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
- E: serde::de::Error,
+ E: de::Error,
{
Ok(Val::string(v))
}
@@ -67,27 +67,27 @@
// }
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
- E: serde::de::Error,
+ E: de::Error,
{
- Ok(Val::Num(v as f64))
+ Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))
}
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
- E: serde::de::Error,
+ E: de::Error,
{
- Ok(Val::Num(v as f64))
+ Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
- E: serde::de::Error,
+ E: de::Error,
{
Ok(Val::Arr(ArrValue::bytes(v.into())))
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
- E: serde::de::Error,
+ E: de::Error,
{
Ok(Val::Null)
}
@@ -100,7 +100,7 @@
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
- E: serde::de::Error,
+ E: de::Error,
{
Ok(Val::Null)
}
@@ -114,7 +114,7 @@
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
- A: serde::de::SeqAccess<'de>,
+ A: de::SeqAccess<'de>,
{
let mut out = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);
@@ -127,7 +127,7 @@
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
- A: serde::de::MapAccess<'de>,
+ A: de::MapAccess<'de>,
{
let mut out = map
.size_hint()
@@ -159,11 +159,12 @@
Self::Null => serializer.serialize_none(),
Self::Str(s) => serializer.serialize_str(&s.clone().into_flat()),
Self::Num(n) => {
+ let n = n.get();
if n.fract() == 0.0 {
- let n = *n as i64;
+ let n = n as i64;
serializer.serialize_i64(n)
} else {
- serializer.serialize_f64(*n)
+ serializer.serialize_f64(n)
}
}
#[cfg(feature = "exp-bigint")]
@@ -449,15 +450,15 @@
}
fn serialize_i8(self, v: i8) -> Result<Val> {
- Ok(Val::Num(f64::from(v)))
+ Ok(Val::Num(v.into()))
}
fn serialize_i16(self, v: i16) -> Result<Val> {
- Ok(Val::Num(f64::from(v)))
+ Ok(Val::Num(v.into()))
}
fn serialize_i32(self, v: i32) -> Result<Val> {
- Ok(Val::Num(f64::from(v)))
+ Ok(Val::Num(v.into()))
}
fn serialize_i64(self, v: i64) -> Result<Val> {
@@ -465,15 +466,15 @@
}
fn serialize_u8(self, v: u8) -> Result<Val> {
- Ok(Val::Num(f64::from(v)))
+ Ok(Val::Num(v.into()))
}
fn serialize_u16(self, v: u16) -> Result<Val> {
- Ok(Val::Num(f64::from(v)))
+ Ok(Val::Num(v.into()))
}
fn serialize_u32(self, v: u32) -> Result<Val> {
- Ok(Val::Num(f64::from(v)))
+ Ok(Val::Num(v.into()))
}
fn serialize_u64(self, v: u64) -> Result<Val> {
@@ -481,11 +482,11 @@
}
fn serialize_f32(self, v: f32) -> Result<Val> {
- Ok(Val::Num(f64::from(v)))
+ Ok(Val::try_num(f64::from(v))?)
}
fn serialize_f64(self, v: f64) -> Result<Val> {
- Ok(Val::Num(v))
+ Ok(Val::try_num(v)?)
}
fn serialize_char(self, v: char) -> Result<Val> {
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -604,10 +604,13 @@
}
}
ConvTypeV::Char => match value.clone() {
- Val::Num(n) => tmp_out.push(
- std::char::from_u32(n as u32)
- .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
- ),
+ Val::Num(n) => {
+ let n = n.get();
+ tmp_out.push(
+ std::char::from_u32(n as u32)
+ .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
+ )
+ }
Val::Str(s) => {
let s = s.into_flat();
if s.chars().count() != 1 {
@@ -786,6 +789,7 @@
#[cfg(test)]
pub mod test_format {
use super::*;
+ use crate::val::NumValue;
#[test]
fn parse() {
@@ -799,17 +803,21 @@
);
}
+ fn num(v: f64) -> Val {
+ Val::Num(NumValue::new(v).expect("finite"))
+ }
+
#[test]
fn octals() {
- assert_eq!(format_arr("%#o", &[Val::Num(8.0)]).unwrap(), "010");
- assert_eq!(format_arr("%#4o", &[Val::Num(8.0)]).unwrap(), " 010");
- assert_eq!(format_arr("%4o", &[Val::Num(8.0)]).unwrap(), " 10");
- assert_eq!(format_arr("%04o", &[Val::Num(8.0)]).unwrap(), "0010");
- assert_eq!(format_arr("%+4o", &[Val::Num(8.0)]).unwrap(), " +10");
- assert_eq!(format_arr("%+04o", &[Val::Num(8.0)]).unwrap(), "+010");
- assert_eq!(format_arr("%-4o", &[Val::Num(8.0)]).unwrap(), "10 ");
- assert_eq!(format_arr("%+-4o", &[Val::Num(8.0)]).unwrap(), "+10 ");
- assert_eq!(format_arr("%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");
+ assert_eq!(format_arr("%#o", &[num(8.0)]).unwrap(), "010");
+ assert_eq!(format_arr("%#4o", &[num(8.0)]).unwrap(), " 010");
+ assert_eq!(format_arr("%4o", &[num(8.0)]).unwrap(), " 10");
+ assert_eq!(format_arr("%04o", &[num(8.0)]).unwrap(), "0010");
+ assert_eq!(format_arr("%+4o", &[num(8.0)]).unwrap(), " +10");
+ assert_eq!(format_arr("%+04o", &[num(8.0)]).unwrap(), "+010");
+ assert_eq!(format_arr("%-4o", &[num(8.0)]).unwrap(), "10 ");
+ assert_eq!(format_arr("%+-4o", &[num(8.0)]).unwrap(), "+10 ");
+ assert_eq!(format_arr("%+-04o", &[num(8.0)]).unwrap(), "+10 ");
}
#[test]
@@ -817,7 +825,7 @@
assert_eq!(
format_arr(
"How much error budget is left looking at our %.3f%% availability gurantees?",
- &[Val::Num(4.0)]
+ &[num(4.0)]
)
.unwrap(),
"How much error budget is left looking at our 4.000% availability gurantees?"
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -10,7 +10,7 @@
bail,
function::{native::NativeDesc, FuncDesc, FuncVal},
typed::CheckType,
- val::{IndexableVal, StrValue, ThunkMapper},
+ val::{IndexableVal, NumValue, StrValue, ThunkMapper},
ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
};
@@ -120,7 +120,8 @@
}
}
-const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;
+pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;
+pub const MIN_SAFE_INTEGER: f64 = -MAX_SAFE_INTEGER;
macro_rules! impl_int {
($($ty:ty)*) => {$(
@@ -131,6 +132,7 @@
<Self as Typed>::TYPE.check(&value)?;
match value {
Val::Num(n) => {
+ let n = n.get();
#[allow(clippy::float_cmp)]
if n.trunc() != n {
bail!(
@@ -143,9 +145,8 @@
_ => unreachable!(),
}
}
- #[allow(clippy::cast_lossless)]
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Num(value as f64))
+ Ok(Val::Num(value.into()))
}
}
)*};
@@ -187,6 +188,7 @@
<Self as Typed>::TYPE.check(&value)?;
match value {
Val::Num(n) => {
+ let n = n.get();
#[allow(clippy::float_cmp)]
if n.trunc() != n {
bail!(
@@ -202,7 +204,7 @@
#[allow(clippy::cast_lossless)]
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Num(value.0 as f64))
+ Ok(Val::try_num(value.0)?)
}
}
)*};
@@ -220,13 +222,13 @@
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Num(value))
+ Ok(Val::try_num(value)?)
}
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
- Val::Num(n) => Ok(n),
+ Val::Num(n) => Ok(n.get()),
_ => unreachable!(),
}
}
@@ -237,13 +239,13 @@
const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Num(value.0))
+ Ok(Val::try_num(value.0)?)
}
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
- Val::Num(n) => Ok(Self(n)),
+ Val::Num(n) => Ok(Self(n.get())),
_ => unreachable!(),
}
}
@@ -253,16 +255,14 @@
&ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));
fn into_untyped(value: Self) -> Result<Val> {
- if value > MAX_SAFE_INTEGER as Self {
- bail!("number is too large")
- }
- Ok(Val::Num(value as f64))
+ Ok(Val::try_num(value)?)
}
fn from_untyped(value: Val) -> Result<Self> {
<Self as Typed>::TYPE.check(&value)?;
match value {
Val::Num(n) => {
+ let n = n.get();
#[allow(clippy::float_cmp)]
if n.trunc() != n {
bail!("cannot convert number with fractional part to usize")
@@ -479,7 +479,7 @@
const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));
fn into_untyped(_: Self) -> Result<Val> {
- Ok(Val::Num(-1.0))
+ Ok(Val::Num(NumValue::new(-1.0).expect("finite")))
}
fn from_untyped(value: Val) -> Result<Self> {
@@ -679,3 +679,19 @@
))
}
}
+
+impl Typed for NumValue {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
+
+ fn into_untyped(typed: Self) -> Result<Val> {
+ Ok(Val::Num(typed))
+ }
+
+ fn from_untyped(untyped: Val) -> Result<Self> {
+ Self::TYPE.check(&untyped)?;
+ match untyped {
+ Val::Num(v) => Ok(v),
+ _ => unreachable!(),
+ }
+ }
+}
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -1,6 +1,6 @@
use std::{fmt::Display, rc::Rc};
-mod conversions;
+pub(crate) mod conversions;
pub use conversions::*;
use jrsonnet_gcmodule::Trace;
pub use jrsonnet_types::{ComplexValType, ValType};
@@ -155,10 +155,11 @@
},
Self::BoundedNumber(from, to) => {
if let Val::Num(n) = value {
- if from.map(|from| from > *n).unwrap_or(false)
- || to.map(|to| to < *n).unwrap_or(false)
+ let n = n.get();
+ if from.map(|from| from > n).unwrap_or(false)
+ || to.map(|to| to < n).unwrap_or(false)
{
- return Err(TypeError::BoundsFailed(*n, *from, *to).into());
+ return Err(TypeError::BoundsFailed(n, *from, *to).into());
}
Ok(())
} else {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -1,14 +1,18 @@
use std::{
cell::RefCell,
+ cmp::Ordering,
fmt::{self, Debug, Display},
mem::replace,
num::NonZeroU32,
+ ops::Deref,
rc::Rc,
};
+use derivative::Derivative;
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
use jrsonnet_types::ValType;
+use thiserror::Error;
pub use crate::arr::{ArrValue, ArrayLike};
use crate::{
@@ -379,18 +383,127 @@
}
impl Eq for StrValue {}
impl PartialOrd for StrValue {
- fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for StrValue {
- fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ fn cmp(&self, other: &Self) -> Ordering {
let a = self.clone().into_flat();
let b = other.clone().into_flat();
a.cmp(&b)
}
}
+/// Represents jsonnet number
+/// Jsonnet numbers are finite f64, with NaNs disallowed
+#[derive(Trace, Clone, Copy, Derivative)]
+#[derivative(Debug = "transparent")]
+#[repr(transparent)]
+pub struct NumValue(f64);
+impl NumValue {
+ /// Creates a [`NumValue`], if value is finite and not NaN
+ pub fn new(v: f64) -> Option<Self> {
+ if !v.is_finite() {
+ return None;
+ }
+ Some(Self(v))
+ }
+ pub const fn get(&self) -> f64 {
+ self.0
+ }
+}
+impl PartialEq for NumValue {
+ fn eq(&self, other: &Self) -> bool {
+ self.0 == other.0
+ }
+}
+impl Eq for NumValue {}
+impl Ord for NumValue {
+ fn cmp(&self, other: &Self) -> Ordering {
+ // Can't use `total_cmp`: its behavior for `-0` and `0`
+ // is not following wanted.
+ self.0.partial_cmp(&other.0).expect("NaNs are disallowed")
+ }
+}
+impl PartialOrd for NumValue {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.cmp(other))
+ }
+}
+impl Display for NumValue {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ Display::fmt(&self.0, f)
+ }
+}
+impl Deref for NumValue {
+ type Target = f64;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+macro_rules! impl_num {
+ ($($ty:ty),+) => {$(
+ impl From<$ty> for NumValue {
+ fn from(value: $ty) -> Self {
+ Self(value.into())
+ }
+ }
+ )+};
+}
+impl_num!(i8, u8, i16, u16, i32, u32);
+
+#[derive(Clone, Copy, Debug, Error, Trace)]
+pub enum ConvertNumValueError {
+ #[error("overflow")]
+ Overflow,
+ #[error("underflow")]
+ Underflow,
+ #[error("non-finite")]
+ NonFinite,
+}
+impl From<ConvertNumValueError> for Error {
+ fn from(e: ConvertNumValueError) -> Self {
+ Self::new(e.into())
+ }
+}
+
+macro_rules! impl_try_num {
+ ($($ty:ty),+) => {$(
+ impl TryFrom<$ty> for NumValue {
+ type Error = ConvertNumValueError;
+ fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {
+ use crate::typed::conversions::{MIN_SAFE_INTEGER, MAX_SAFE_INTEGER};
+ let value = value as f64;
+ if value < MIN_SAFE_INTEGER {
+ return Err(ConvertNumValueError::Underflow)
+ } else if value > MAX_SAFE_INTEGER {
+ return Err(ConvertNumValueError::Overflow)
+ }
+ // Number is finite.
+ Ok(Self(value))
+ }
+ }
+ )+};
+}
+impl_try_num!(usize, isize, i64, u64);
+
+impl TryFrom<f64> for NumValue {
+ type Error = ConvertNumValueError;
+
+ fn try_from(value: f64) -> Result<Self, Self::Error> {
+ Self::new(value).ok_or(ConvertNumValueError::NonFinite)
+ }
+}
+impl TryFrom<f32> for NumValue {
+ type Error = ConvertNumValueError;
+
+ fn try_from(value: f32) -> Result<Self, Self::Error> {
+ Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)
+ }
+}
+
/// Represents any valid Jsonnet value.
#[derive(Debug, Clone, Trace, Default)]
pub enum Val {
@@ -404,7 +517,7 @@
/// Represents a Jsonnet number.
/// Should be finite, and not NaN
/// This restriction isn't enforced by enum, as enum field can't be marked as private
- Num(f64),
+ Num(NumValue),
/// Experimental bigint
#[cfg(feature = "exp-bigint")]
BigInt(#[trace(skip)] Box<num_bigint::BigInt>),
@@ -449,7 +562,7 @@
}
pub const fn as_num(&self) -> Option<f64> {
match self {
- Self::Num(n) => Some(*n),
+ Self::Num(n) => Some(n.get()),
_ => None,
}
}
@@ -472,16 +585,6 @@
}
}
- /// Creates `Val::Num` after checking for numeric overflow.
- /// As numbers are `f64`, we can just check for their finity.
- pub fn new_checked_num(num: f64) -> Result<Self> {
- if num.is_finite() {
- Ok(Self::Num(num))
- } else {
- bail!("overflow")
- }
- }
-
pub const fn value_type(&self) -> ValType {
match self {
Self::Str(..) => ValType::Str,
@@ -527,6 +630,15 @@
pub fn string(string: impl Into<StrValue>) -> Self {
Self::Str(string.into())
}
+ pub fn num(num: impl Into<NumValue>) -> Self {
+ Self::Num(num.into())
+ }
+ pub fn try_num<V, E>(num: V) -> Result<Self, E>
+ where
+ NumValue: TryFrom<V, Error = E>,
+ {
+ Ok(Self::Num(num.try_into()?))
+ }
}
impl From<IStr> for Val {
@@ -560,7 +672,7 @@
(Val::Bool(a), Val::Bool(b)) => a == b,
(Val::Null, Val::Null) => true,
(Val::Str(a), Val::Str(b)) => a == b,
- (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,
+ (Val::Num(a), Val::Num(b)) => (a.get() - b.get()).abs() <= f64::EPSILON,
#[cfg(feature = "exp-bigint")]
(Val::BigInt(a), Val::BigInt(b)) => a == b,
(Val::Arr(_), Val::Arr(_)) => {
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -275,7 +275,7 @@
if arr.is_empty() {
return eval_on_empty(onEmpty);
}
- Ok(Val::Num(arr.iter().sum::<f64>() / (arr.len() as f64)))
+ Ok(Val::try_num(arr.iter().sum::<f64>() / (arr.len() as f64))?)
}
#[builtin]
crates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -6,12 +6,12 @@
operator::evaluate_mod_op,
stdlib::std_format,
typed::{Either, Either2},
- val::{equals, primitive_equals},
+ val::{equals, primitive_equals, NumValue},
IStr, Result, Val,
};
#[builtin]
-pub fn builtin_mod(a: Either![f64, IStr], b: Val) -> Result<Val> {
+pub fn builtin_mod(a: Either![NumValue, IStr], b: Val) -> Result<Val> {
use Either2::*;
evaluate_mod_op(
&match a {
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -20,20 +20,6 @@
Unknown,
}
-#[derive(PartialEq)]
-struct NonNaNf64(f64);
-impl PartialOrd for NonNaNf64 {
- fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
- Some(self.cmp(other))
- }
-}
-impl Eq for NonNaNf64 {}
-impl Ord for NonNaNf64 {
- fn cmp(&self, other: &Self) -> std::cmp::Ordering {
- self.0.partial_cmp(&other.0).expect("non nan")
- }
-}
-
fn get_sort_type<T>(values: &[T], key_getter: impl Fn(&T) -> &Val) -> Result<SortKeyType> {
let mut sort_type = SortKeyType::Unknown;
for i in values {
@@ -56,7 +42,7 @@
let sort_type = get_sort_type(&values, |k| k)?;
match sort_type {
SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
- Val::Num(n) => NonNaNf64(*n),
+ Val::Num(n) => *n,
_ => unreachable!(),
}),
SortKeyType::String => values.sort_unstable_by_key(|v| match v {
@@ -95,7 +81,7 @@
let sort_type = get_sort_type(&vk, |v| &v.1)?;
match sort_type {
SortKeyType::Number => vk.sort_by_key(|v| match v.1 {
- Val::Num(n) => NonNaNf64(n),
+ Val::Num(n) => n,
_ => unreachable!(),
}),
SortKeyType::String => vk.sort_by_key(|v| match &v.1 {
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -116,7 +116,9 @@
.enumerate()
{
if &strb[i..i + pat.len()] == pat {
- out.push(Val::Num(ch_idx as f64));
+ out.push(Val::Num(
+ ch_idx.try_into().expect("unrealisticly long string"),
+ ));
}
}
out.into()