difftreelog
fix enforce Val::Num finityness at type level
in: master
13 files changed
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -120,7 +120,7 @@
}
fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0.get(index).map(|v| Val::Num(f64::from(*v)))
+ self.0.get(index).map(|v| Val::Num((*v).into()))
}
fn is_cheap(&self) -> bool {
true
@@ -399,7 +399,7 @@
}
fn get_cheap(&self, index: usize) -> Option<Val> {
- self.range().nth(index).map(|i| Val::Num(f64::from(i)))
+ self.range().nth(index).map(|i| Val::Num(i.into()))
}
fn is_cheap(&self) -> bool {
true
@@ -430,12 +430,12 @@
}
#[derive(Trace, Debug, Clone)]
-pub struct MappedArray<const WithIndex: bool> {
+pub struct MappedArray<const WITH_INDEX: bool> {
inner: ArrValue,
cached: Cc<RefCell<Vec<ArrayThunk<()>>>>,
mapper: FuncVal,
}
-impl<const WithIndex: bool> MappedArray<WithIndex> {
+impl<const WITH_INDEX: bool> MappedArray<WITH_INDEX> {
pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {
let len = inner.len();
Self {
@@ -445,14 +445,14 @@
}
}
fn evaluate(&self, index: usize, value: Val) -> Result<Val> {
- if WithIndex {
+ if WITH_INDEX {
self.mapper.evaluate_simple(&(index, value), false)
} else {
self.mapper.evaluate_simple(&(value,), false)
}
}
}
-impl<const WithIndex: bool> ArrayLike for MappedArray<WithIndex> {
+impl<const WITH_INDEX: bool> ArrayLike for MappedArray<WITH_INDEX> {
fn len(&self) -> usize {
self.cached.borrow().len()
}
@@ -493,12 +493,12 @@
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
#[derive(Trace)]
- struct ArrayElement<const WithIndex: bool> {
- arr_thunk: MappedArray<WithIndex>,
+ struct ArrayElement<const WITH_INDEX: bool> {
+ arr_thunk: MappedArray<WITH_INDEX>,
index: usize,
}
- impl<const WithIndex: bool> ThunkValue for ArrayElement<WithIndex> {
+ impl<const WITH_INDEX: bool> ThunkValue for ArrayElement<WITH_INDEX> {
type Output = Val;
fn get(self: Box<Self>) -> Result<Self::Output> {
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.rsdiffbeforeafterboth1use std::borrow::Cow;23use jrsonnet_interner::IStr;4use serde::{5 de::Visitor,6 ser::{7 Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,8 SerializeTupleStruct, SerializeTupleVariant,9 },10 Deserialize, Serialize, Serializer,11};1213use crate::{14 arr::ArrValue, runtime_error, Error as JrError, ObjValue, ObjValueBuilder, Result, State, Val,15};1617impl<'de> Deserialize<'de> for Val {18 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>19 where20 D: serde::Deserializer<'de>,21 {22 struct ValVisitor;2324 // macro_rules! visit_num {25 // ($($method:ident => $ty:ty),* $(,)?) => {$(26 // fn $method<E>(self, v: $ty) -> Result<Self::Value, E>27 // where28 // E: serde::de::Error,29 // {30 // Ok(Val::Num(f64::from(v)))31 // }32 // )*};33 // }3435 impl<'de> Visitor<'de> for ValVisitor {36 type Value = Val;3738 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>39 where40 E: serde::de::Error,41 {42 Ok(Val::Bool(v))43 }44 fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>45 where46 E: serde::de::Error,47 {48 if !v.is_finite() {49 return Err(E::custom("only finite numbers are supported"));50 }51 Ok(Val::Num(v))52 }53 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>54 where55 E: serde::de::Error,56 {57 Ok(Val::string(v))58 }5960 // visit_num! {61 // visit_i8 => i8,62 // visit_i16 => i16,63 // visit_i32 => i32,64 // visit_u8 => u8,65 // visit_u16 => u16,66 // visit_u32 => u32,67 // }68 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>69 where70 E: serde::de::Error,71 {72 Ok(Val::Num(v as f64))73 }74 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>75 where76 E: serde::de::Error,77 {78 Ok(Val::Num(v as f64))79 }8081 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>82 where83 E: serde::de::Error,84 {85 Ok(Val::Arr(ArrValue::bytes(v.into())))86 }8788 fn visit_none<E>(self) -> Result<Self::Value, E>89 where90 E: serde::de::Error,91 {92 Ok(Val::Null)93 }94 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>95 where96 D: serde::Deserializer<'de>,97 {98 deserializer.deserialize_any(self)99 }100101 fn visit_unit<E>(self) -> Result<Self::Value, E>102 where103 E: serde::de::Error,104 {105 Ok(Val::Null)106 }107108 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>109 where110 D: serde::Deserializer<'de>,111 {112 deserializer.deserialize_any(self)113 }114115 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>116 where117 A: serde::de::SeqAccess<'de>,118 {119 let mut out = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);120121 while let Some(val) = seq.next_element::<Val>()? {122 out.push(val);123 }124125 Ok(Val::Arr(ArrValue::eager(out)))126 }127128 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>129 where130 A: serde::de::MapAccess<'de>,131 {132 let mut out = map133 .size_hint()134 .map_or_else(ObjValueBuilder::new, ObjValueBuilder::with_capacity);135136 while let Some((k, v)) = map.next_entry::<Cow<'de, str>, Val>()? {137 // Jsonnet ignores duplicate keys138 out.field(k).value(v);139 }140141 Ok(Val::Obj(out.build()))142 }143144 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {145 write!(formatter, "any valid jsonnet value")146 }147 }148 deserializer.deserialize_any(ValVisitor)149 }150}151152impl Serialize for Val {153 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>154 where155 S: serde::Serializer,156 {157 match self {158 Self::Bool(v) => serializer.serialize_bool(*v),159 Self::Null => serializer.serialize_none(),160 Self::Str(s) => serializer.serialize_str(&s.clone().into_flat()),161 Self::Num(n) => {162 if n.fract() == 0.0 {163 let n = *n as i64;164 serializer.serialize_i64(n)165 } else {166 serializer.serialize_f64(*n)167 }168 }169 #[cfg(feature = "exp-bigint")]170 Self::BigInt(b) => b.serialize(serializer),171 Self::Arr(arr) => {172 let mut seq = serializer.serialize_seq(Some(arr.len()))?;173 for (i, element) in arr.iter().enumerate() {174 let mut serde_error = None;175 // TODO: rewrite using try{} after stabilization176 State::push_description(177 || format!("array index [{i}]"),178 || {179 let e = element?;180 if let Err(e) = seq.serialize_element(&e) {181 serde_error = Some(e);182 }183 Ok(())184 },185 )186 .map_err(|e| S::Error::custom(e.to_string()))?;187 if let Some(e) = serde_error {188 return Err(e);189 }190 }191 seq.end()192 }193 Self::Obj(obj) => {194 let mut map = serializer.serialize_map(Some(obj.len()))?;195 for (field, value) in obj.iter(196 #[cfg(feature = "exp-preserve-order")]197 true,198 ) {199 let mut serde_error = None;200 // TODO: rewrite using try{} after stabilization201 State::push_description(202 || format!("object field {field:?}"),203 || {204 let v = value?;205 if let Err(e) = map.serialize_entry(field.as_str(), &v) {206 serde_error = Some(e);207 }208 Ok(())209 },210 )211 .map_err(|e| S::Error::custom(e.to_string()))?;212 if let Some(e) = serde_error {213 return Err(e);214 }215 }216 map.end()217 }218 Self::Func(_) => Err(S::Error::custom("tried to manifest function")),219 }220 }221}222223struct IntoVecValSerializer {224 variant: Option<IStr>,225 data: Vec<Val>,226}227impl IntoVecValSerializer {228 fn new() -> Self {229 Self {230 variant: None,231 data: Vec::new(),232 }233 }234 fn with_capacity(capacity: usize) -> Self {235 Self {236 variant: None,237 data: Vec::with_capacity(capacity),238 }239 }240 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {241 Self {242 variant: Some(variant.into()),243 data: Vec::with_capacity(capacity),244 }245 }246}247impl SerializeSeq for IntoVecValSerializer {248 type Ok = Val;249 type Error = JrError;250251 fn serialize_element<T>(&mut self, value: &T) -> Result<()>252 where253 T: ?Sized + Serialize,254 {255 let value = value.serialize(IntoValSerializer)?;256 self.data.push(value);257 Ok(())258 }259260 fn end(self) -> Result<Val> {261 let inner = Val::Arr(ArrValue::eager(self.data));262 if let Some(variant) = self.variant {263 let mut out = ObjValue::builder_with_capacity(1);264 out.field(variant).value(inner);265 Ok(Val::Obj(out.build()))266 } else {267 Ok(inner)268 }269 }270}271impl SerializeTuple for IntoVecValSerializer {272 type Ok = Val;273 type Error = JrError;274275 fn serialize_element<T>(&mut self, value: &T) -> Result<()>276 where277 T: ?Sized + Serialize,278 {279 SerializeSeq::serialize_element(self, value)280 }281282 fn end(self) -> Result<Val> {283 SerializeSeq::end(self)284 }285}286impl SerializeTupleVariant for IntoVecValSerializer {287 type Ok = Val;288 type Error = JrError;289290 fn serialize_field<T>(&mut self, value: &T) -> Result<()>291 where292 T: ?Sized + Serialize,293 {294 SerializeSeq::serialize_element(self, value)295 }296297 fn end(self) -> Result<Val> {298 SerializeSeq::end(self)299 }300}301impl SerializeTupleStruct for IntoVecValSerializer {302 type Ok = Val;303 type Error = JrError;304305 fn serialize_field<T>(&mut self, value: &T) -> Result<()>306 where307 T: ?Sized + Serialize,308 {309 SerializeSeq::serialize_element(self, value)310 }311312 fn end(self) -> Result<Val> {313 SerializeSeq::end(self)314 }315}316317struct IntoObjValueSerializer {318 variant: Option<IStr>,319 data: ObjValueBuilder,320 key: Option<IStr>,321}322impl IntoObjValueSerializer {323 fn new() -> Self {324 Self {325 variant: None,326 data: ObjValue::builder(),327 key: None,328 }329 }330 fn with_capacity(capacity: usize) -> Self {331 Self {332 variant: None,333 data: ObjValue::builder_with_capacity(capacity),334 key: None,335 }336 }337 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {338 Self {339 variant: Some(variant.into()),340 data: ObjValue::builder_with_capacity(capacity),341 key: None,342 }343 }344}345impl SerializeMap for IntoObjValueSerializer {346 type Ok = Val;347 type Error = JrError;348349 fn serialize_key<T>(&mut self, key: &T) -> Result<()>350 where351 T: ?Sized + Serialize,352 {353 let key = key.serialize(IntoValSerializer)?;354 let key = key.to_string()?;355 self.key = Some(key);356 Ok(())357 }358359 fn serialize_value<T>(&mut self, value: &T) -> Result<()>360 where361 T: ?Sized + Serialize,362 {363 let key = self.key.take().expect("no serialize_key called");364 let value = value.serialize(IntoValSerializer)?;365 self.data.field(key).try_value(value)?;366 Ok(())367 }368369 // TODO: serialize_key/serialize_value370 fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<()>371 where372 K: ?Sized + Serialize,373 V: ?Sized + Serialize,374 {375 let key = key.serialize(IntoValSerializer)?;376 let key = key.to_string()?;377 let value = value.serialize(IntoValSerializer)?;378 self.data.field(key).try_value(value)?;379 Ok(())380 }381382 fn end(self) -> Result<Val> {383 let inner = Val::Obj(self.data.build());384 if let Some(variant) = self.variant {385 let mut out = ObjValue::builder_with_capacity(1);386 out.field(variant).value(inner);387 Ok(Val::Obj(out.build()))388 } else {389 Ok(inner)390 }391 }392}393impl SerializeStruct for IntoObjValueSerializer {394 type Ok = Val;395 type Error = JrError;396397 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>398 where399 T: ?Sized + Serialize,400 {401 SerializeMap::serialize_entry(self, key, value)?;402 Ok(())403 }404405 fn end(self) -> Result<Val> {406 SerializeMap::end(self)407 }408}409impl SerializeStructVariant for IntoObjValueSerializer {410 type Ok = Val;411412 type Error = JrError;413414 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>415 where416 T: ?Sized + Serialize,417 {418 SerializeMap::serialize_entry(self, key, value)?;419 Ok(())420 }421422 fn end(self) -> Result<Val> {423 SerializeMap::end(self)424 }425}426427struct IntoValSerializer;428impl Serializer for IntoValSerializer {429 type Ok = Val;430431 type Error = JrError;432433 type SerializeSeq = IntoVecValSerializer;434435 type SerializeTuple = IntoVecValSerializer;436437 type SerializeTupleStruct = IntoVecValSerializer;438439 type SerializeTupleVariant = IntoVecValSerializer;440441 type SerializeMap = IntoObjValueSerializer;442443 type SerializeStruct = IntoObjValueSerializer;444445 type SerializeStructVariant = IntoObjValueSerializer;446447 fn serialize_bool(self, v: bool) -> Result<Val> {448 Ok(Val::Bool(v))449 }450451 fn serialize_i8(self, v: i8) -> Result<Val> {452 Ok(Val::Num(f64::from(v)))453 }454455 fn serialize_i16(self, v: i16) -> Result<Val> {456 Ok(Val::Num(f64::from(v)))457 }458459 fn serialize_i32(self, v: i32) -> Result<Val> {460 Ok(Val::Num(f64::from(v)))461 }462463 fn serialize_i64(self, v: i64) -> Result<Val> {464 Ok(Val::Str(v.to_string().into()))465 }466467 fn serialize_u8(self, v: u8) -> Result<Val> {468 Ok(Val::Num(f64::from(v)))469 }470471 fn serialize_u16(self, v: u16) -> Result<Val> {472 Ok(Val::Num(f64::from(v)))473 }474475 fn serialize_u32(self, v: u32) -> Result<Val> {476 Ok(Val::Num(f64::from(v)))477 }478479 fn serialize_u64(self, v: u64) -> Result<Val> {480 Ok(Val::Str(v.to_string().into()))481 }482483 fn serialize_f32(self, v: f32) -> Result<Val> {484 Ok(Val::Num(f64::from(v)))485 }486487 fn serialize_f64(self, v: f64) -> Result<Val> {488 Ok(Val::Num(v))489 }490491 fn serialize_char(self, v: char) -> Result<Val> {492 Ok(Val::Str(v.to_string().into()))493 }494495 fn serialize_str(self, v: &str) -> Result<Val> {496 Ok(Val::Str(v.into()))497 }498499 fn serialize_bytes(self, v: &[u8]) -> Result<Val> {500 Ok(Val::Arr(ArrValue::bytes(v.into())))501 }502503 fn serialize_none(self) -> Result<Val> {504 Ok(Val::Null)505 }506507 fn serialize_some<T>(self, value: &T) -> Result<Val>508 where509 T: ?Sized + Serialize,510 {511 value.serialize(self)512 }513514 fn serialize_unit(self) -> Result<Val> {515 Ok(Val::Null)516 }517518 fn serialize_unit_struct(self, _name: &'static str) -> Result<Val> {519 Ok(Val::Null)520 }521522 fn serialize_unit_variant(523 self,524 _name: &'static str,525 _variant_index: u32,526 variant: &'static str,527 ) -> Result<Val> {528 Ok(Val::Str(variant.into()))529 }530531 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Val>532 where533 T: ?Sized + Serialize,534 {535 value.serialize(self)536 }537538 fn serialize_newtype_variant<T>(539 self,540 _name: &'static str,541 _variant_index: u32,542 variant: &'static str,543 value: &T,544 ) -> Result<Val>545 where546 T: ?Sized + Serialize,547 {548 let mut out = ObjValue::builder_with_capacity(1);549 let value = value.serialize(self)?;550 out.field(variant).value(value);551 Ok(Val::Obj(out.build()))552 }553554 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {555 Ok(len.map_or_else(556 IntoVecValSerializer::new,557 IntoVecValSerializer::with_capacity,558 ))559 }560561 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {562 Ok(IntoVecValSerializer::with_capacity(len))563 }564565 fn serialize_tuple_struct(566 self,567 _name: &'static str,568 len: usize,569 ) -> Result<Self::SerializeTupleStruct, Self::Error> {570 Ok(IntoVecValSerializer::with_capacity(len))571 }572573 fn serialize_tuple_variant(574 self,575 _name: &'static str,576 _variant_index: u32,577 variant: &'static str,578 len: usize,579 ) -> Result<Self::SerializeTupleVariant, Self::Error> {580 Ok(IntoVecValSerializer::variant_with_capacity(variant, len))581 }582583 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {584 Ok(len.map_or_else(585 IntoObjValueSerializer::new,586 IntoObjValueSerializer::with_capacity,587 ))588 }589590 fn serialize_struct(591 self,592 _name: &'static str,593 len: usize,594 ) -> Result<Self::SerializeStruct, Self::Error> {595 Ok(IntoObjValueSerializer::with_capacity(len))596 }597598 fn serialize_struct_variant(599 self,600 _name: &'static str,601 _variant_index: u32,602 variant: &'static str,603 len: usize,604 ) -> Result<Self::SerializeStructVariant, Self::Error> {605 Ok(IntoObjValueSerializer::variant_with_capacity(variant, len))606 }607}608609impl Val {610 pub fn from_serde(v: impl Serialize) -> Result<Self, JrError> {611 v.serialize(IntoValSerializer)612 }613}614615impl serde::ser::Error for JrError {616 fn custom<T>(msg: T) -> Self617 where618 T: std::fmt::Display,619 {620 runtime_error!("serde: {msg}")621 }622}1use std::borrow::Cow;23use jrsonnet_interner::IStr;4use serde::{5 de::{self, Visitor},6 ser::{7 Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,8 SerializeTupleStruct, SerializeTupleVariant,9 },10 Deserialize, Serialize, Serializer,11};1213use crate::{14 arr::ArrValue, runtime_error, val::NumValue, Error as JrError, ObjValue, ObjValueBuilder,15 Result, State, Val,16};1718impl<'de> Deserialize<'de> for Val {19 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>20 where21 D: serde::Deserializer<'de>,22 {23 struct ValVisitor;2425 // macro_rules! visit_num {26 // ($($method:ident => $ty:ty),* $(,)?) => {$(27 // fn $method<E>(self, v: $ty) -> Result<Self::Value, E>28 // where29 // E: serde::de::Error,30 // {31 // Ok(Val::Num(f64::from(v)))32 // }33 // )*};34 // }3536 impl<'de> Visitor<'de> for ValVisitor {37 type Value = Val;3839 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>40 where41 E: de::Error,42 {43 Ok(Val::Bool(v))44 }45 fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>46 where47 E: de::Error,48 {49 Ok(Val::Num(NumValue::new(v).ok_or_else(|| {50 E::custom("only finite numbers are supported")51 })?))52 }53 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>54 where55 E: de::Error,56 {57 Ok(Val::string(v))58 }5960 // visit_num! {61 // visit_i8 => i8,62 // visit_i16 => i16,63 // visit_i32 => i32,64 // visit_u8 => u8,65 // visit_u16 => u16,66 // visit_u32 => u32,67 // }68 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>69 where70 E: de::Error,71 {72 Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))73 }74 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>75 where76 E: de::Error,77 {78 Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))79 }8081 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>82 where83 E: de::Error,84 {85 Ok(Val::Arr(ArrValue::bytes(v.into())))86 }8788 fn visit_none<E>(self) -> Result<Self::Value, E>89 where90 E: de::Error,91 {92 Ok(Val::Null)93 }94 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>95 where96 D: serde::Deserializer<'de>,97 {98 deserializer.deserialize_any(self)99 }100101 fn visit_unit<E>(self) -> Result<Self::Value, E>102 where103 E: de::Error,104 {105 Ok(Val::Null)106 }107108 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>109 where110 D: serde::Deserializer<'de>,111 {112 deserializer.deserialize_any(self)113 }114115 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>116 where117 A: de::SeqAccess<'de>,118 {119 let mut out = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);120121 while let Some(val) = seq.next_element::<Val>()? {122 out.push(val);123 }124125 Ok(Val::Arr(ArrValue::eager(out)))126 }127128 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>129 where130 A: de::MapAccess<'de>,131 {132 let mut out = map133 .size_hint()134 .map_or_else(ObjValueBuilder::new, ObjValueBuilder::with_capacity);135136 while let Some((k, v)) = map.next_entry::<Cow<'de, str>, Val>()? {137 // Jsonnet ignores duplicate keys138 out.field(k).value(v);139 }140141 Ok(Val::Obj(out.build()))142 }143144 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {145 write!(formatter, "any valid jsonnet value")146 }147 }148 deserializer.deserialize_any(ValVisitor)149 }150}151152impl Serialize for Val {153 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>154 where155 S: serde::Serializer,156 {157 match self {158 Self::Bool(v) => serializer.serialize_bool(*v),159 Self::Null => serializer.serialize_none(),160 Self::Str(s) => serializer.serialize_str(&s.clone().into_flat()),161 Self::Num(n) => {162 let n = n.get();163 if n.fract() == 0.0 {164 let n = n as i64;165 serializer.serialize_i64(n)166 } else {167 serializer.serialize_f64(n)168 }169 }170 #[cfg(feature = "exp-bigint")]171 Self::BigInt(b) => b.serialize(serializer),172 Self::Arr(arr) => {173 let mut seq = serializer.serialize_seq(Some(arr.len()))?;174 for (i, element) in arr.iter().enumerate() {175 let mut serde_error = None;176 // TODO: rewrite using try{} after stabilization177 State::push_description(178 || format!("array index [{i}]"),179 || {180 let e = element?;181 if let Err(e) = seq.serialize_element(&e) {182 serde_error = Some(e);183 }184 Ok(())185 },186 )187 .map_err(|e| S::Error::custom(e.to_string()))?;188 if let Some(e) = serde_error {189 return Err(e);190 }191 }192 seq.end()193 }194 Self::Obj(obj) => {195 let mut map = serializer.serialize_map(Some(obj.len()))?;196 for (field, value) in obj.iter(197 #[cfg(feature = "exp-preserve-order")]198 true,199 ) {200 let mut serde_error = None;201 // TODO: rewrite using try{} after stabilization202 State::push_description(203 || format!("object field {field:?}"),204 || {205 let v = value?;206 if let Err(e) = map.serialize_entry(field.as_str(), &v) {207 serde_error = Some(e);208 }209 Ok(())210 },211 )212 .map_err(|e| S::Error::custom(e.to_string()))?;213 if let Some(e) = serde_error {214 return Err(e);215 }216 }217 map.end()218 }219 Self::Func(_) => Err(S::Error::custom("tried to manifest function")),220 }221 }222}223224struct IntoVecValSerializer {225 variant: Option<IStr>,226 data: Vec<Val>,227}228impl IntoVecValSerializer {229 fn new() -> Self {230 Self {231 variant: None,232 data: Vec::new(),233 }234 }235 fn with_capacity(capacity: usize) -> Self {236 Self {237 variant: None,238 data: Vec::with_capacity(capacity),239 }240 }241 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {242 Self {243 variant: Some(variant.into()),244 data: Vec::with_capacity(capacity),245 }246 }247}248impl SerializeSeq for IntoVecValSerializer {249 type Ok = Val;250 type Error = JrError;251252 fn serialize_element<T>(&mut self, value: &T) -> Result<()>253 where254 T: ?Sized + Serialize,255 {256 let value = value.serialize(IntoValSerializer)?;257 self.data.push(value);258 Ok(())259 }260261 fn end(self) -> Result<Val> {262 let inner = Val::Arr(ArrValue::eager(self.data));263 if let Some(variant) = self.variant {264 let mut out = ObjValue::builder_with_capacity(1);265 out.field(variant).value(inner);266 Ok(Val::Obj(out.build()))267 } else {268 Ok(inner)269 }270 }271}272impl SerializeTuple for IntoVecValSerializer {273 type Ok = Val;274 type Error = JrError;275276 fn serialize_element<T>(&mut self, value: &T) -> Result<()>277 where278 T: ?Sized + Serialize,279 {280 SerializeSeq::serialize_element(self, value)281 }282283 fn end(self) -> Result<Val> {284 SerializeSeq::end(self)285 }286}287impl SerializeTupleVariant for IntoVecValSerializer {288 type Ok = Val;289 type Error = JrError;290291 fn serialize_field<T>(&mut self, value: &T) -> Result<()>292 where293 T: ?Sized + Serialize,294 {295 SerializeSeq::serialize_element(self, value)296 }297298 fn end(self) -> Result<Val> {299 SerializeSeq::end(self)300 }301}302impl SerializeTupleStruct for IntoVecValSerializer {303 type Ok = Val;304 type Error = JrError;305306 fn serialize_field<T>(&mut self, value: &T) -> Result<()>307 where308 T: ?Sized + Serialize,309 {310 SerializeSeq::serialize_element(self, value)311 }312313 fn end(self) -> Result<Val> {314 SerializeSeq::end(self)315 }316}317318struct IntoObjValueSerializer {319 variant: Option<IStr>,320 data: ObjValueBuilder,321 key: Option<IStr>,322}323impl IntoObjValueSerializer {324 fn new() -> Self {325 Self {326 variant: None,327 data: ObjValue::builder(),328 key: None,329 }330 }331 fn with_capacity(capacity: usize) -> Self {332 Self {333 variant: None,334 data: ObjValue::builder_with_capacity(capacity),335 key: None,336 }337 }338 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {339 Self {340 variant: Some(variant.into()),341 data: ObjValue::builder_with_capacity(capacity),342 key: None,343 }344 }345}346impl SerializeMap for IntoObjValueSerializer {347 type Ok = Val;348 type Error = JrError;349350 fn serialize_key<T>(&mut self, key: &T) -> Result<()>351 where352 T: ?Sized + Serialize,353 {354 let key = key.serialize(IntoValSerializer)?;355 let key = key.to_string()?;356 self.key = Some(key);357 Ok(())358 }359360 fn serialize_value<T>(&mut self, value: &T) -> Result<()>361 where362 T: ?Sized + Serialize,363 {364 let key = self.key.take().expect("no serialize_key called");365 let value = value.serialize(IntoValSerializer)?;366 self.data.field(key).try_value(value)?;367 Ok(())368 }369370 // TODO: serialize_key/serialize_value371 fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<()>372 where373 K: ?Sized + Serialize,374 V: ?Sized + Serialize,375 {376 let key = key.serialize(IntoValSerializer)?;377 let key = key.to_string()?;378 let value = value.serialize(IntoValSerializer)?;379 self.data.field(key).try_value(value)?;380 Ok(())381 }382383 fn end(self) -> Result<Val> {384 let inner = Val::Obj(self.data.build());385 if let Some(variant) = self.variant {386 let mut out = ObjValue::builder_with_capacity(1);387 out.field(variant).value(inner);388 Ok(Val::Obj(out.build()))389 } else {390 Ok(inner)391 }392 }393}394impl SerializeStruct for IntoObjValueSerializer {395 type Ok = Val;396 type Error = JrError;397398 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>399 where400 T: ?Sized + Serialize,401 {402 SerializeMap::serialize_entry(self, key, value)?;403 Ok(())404 }405406 fn end(self) -> Result<Val> {407 SerializeMap::end(self)408 }409}410impl SerializeStructVariant for IntoObjValueSerializer {411 type Ok = Val;412413 type Error = JrError;414415 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>416 where417 T: ?Sized + Serialize,418 {419 SerializeMap::serialize_entry(self, key, value)?;420 Ok(())421 }422423 fn end(self) -> Result<Val> {424 SerializeMap::end(self)425 }426}427428struct IntoValSerializer;429impl Serializer for IntoValSerializer {430 type Ok = Val;431432 type Error = JrError;433434 type SerializeSeq = IntoVecValSerializer;435436 type SerializeTuple = IntoVecValSerializer;437438 type SerializeTupleStruct = IntoVecValSerializer;439440 type SerializeTupleVariant = IntoVecValSerializer;441442 type SerializeMap = IntoObjValueSerializer;443444 type SerializeStruct = IntoObjValueSerializer;445446 type SerializeStructVariant = IntoObjValueSerializer;447448 fn serialize_bool(self, v: bool) -> Result<Val> {449 Ok(Val::Bool(v))450 }451452 fn serialize_i8(self, v: i8) -> Result<Val> {453 Ok(Val::Num(v.into()))454 }455456 fn serialize_i16(self, v: i16) -> Result<Val> {457 Ok(Val::Num(v.into()))458 }459460 fn serialize_i32(self, v: i32) -> Result<Val> {461 Ok(Val::Num(v.into()))462 }463464 fn serialize_i64(self, v: i64) -> Result<Val> {465 Ok(Val::Str(v.to_string().into()))466 }467468 fn serialize_u8(self, v: u8) -> Result<Val> {469 Ok(Val::Num(v.into()))470 }471472 fn serialize_u16(self, v: u16) -> Result<Val> {473 Ok(Val::Num(v.into()))474 }475476 fn serialize_u32(self, v: u32) -> Result<Val> {477 Ok(Val::Num(v.into()))478 }479480 fn serialize_u64(self, v: u64) -> Result<Val> {481 Ok(Val::Str(v.to_string().into()))482 }483484 fn serialize_f32(self, v: f32) -> Result<Val> {485 Ok(Val::try_num(f64::from(v))?)486 }487488 fn serialize_f64(self, v: f64) -> Result<Val> {489 Ok(Val::try_num(v)?)490 }491492 fn serialize_char(self, v: char) -> Result<Val> {493 Ok(Val::Str(v.to_string().into()))494 }495496 fn serialize_str(self, v: &str) -> Result<Val> {497 Ok(Val::Str(v.into()))498 }499500 fn serialize_bytes(self, v: &[u8]) -> Result<Val> {501 Ok(Val::Arr(ArrValue::bytes(v.into())))502 }503504 fn serialize_none(self) -> Result<Val> {505 Ok(Val::Null)506 }507508 fn serialize_some<T>(self, value: &T) -> Result<Val>509 where510 T: ?Sized + Serialize,511 {512 value.serialize(self)513 }514515 fn serialize_unit(self) -> Result<Val> {516 Ok(Val::Null)517 }518519 fn serialize_unit_struct(self, _name: &'static str) -> Result<Val> {520 Ok(Val::Null)521 }522523 fn serialize_unit_variant(524 self,525 _name: &'static str,526 _variant_index: u32,527 variant: &'static str,528 ) -> Result<Val> {529 Ok(Val::Str(variant.into()))530 }531532 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Val>533 where534 T: ?Sized + Serialize,535 {536 value.serialize(self)537 }538539 fn serialize_newtype_variant<T>(540 self,541 _name: &'static str,542 _variant_index: u32,543 variant: &'static str,544 value: &T,545 ) -> Result<Val>546 where547 T: ?Sized + Serialize,548 {549 let mut out = ObjValue::builder_with_capacity(1);550 let value = value.serialize(self)?;551 out.field(variant).value(value);552 Ok(Val::Obj(out.build()))553 }554555 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {556 Ok(len.map_or_else(557 IntoVecValSerializer::new,558 IntoVecValSerializer::with_capacity,559 ))560 }561562 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {563 Ok(IntoVecValSerializer::with_capacity(len))564 }565566 fn serialize_tuple_struct(567 self,568 _name: &'static str,569 len: usize,570 ) -> Result<Self::SerializeTupleStruct, Self::Error> {571 Ok(IntoVecValSerializer::with_capacity(len))572 }573574 fn serialize_tuple_variant(575 self,576 _name: &'static str,577 _variant_index: u32,578 variant: &'static str,579 len: usize,580 ) -> Result<Self::SerializeTupleVariant, Self::Error> {581 Ok(IntoVecValSerializer::variant_with_capacity(variant, len))582 }583584 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {585 Ok(len.map_or_else(586 IntoObjValueSerializer::new,587 IntoObjValueSerializer::with_capacity,588 ))589 }590591 fn serialize_struct(592 self,593 _name: &'static str,594 len: usize,595 ) -> Result<Self::SerializeStruct, Self::Error> {596 Ok(IntoObjValueSerializer::with_capacity(len))597 }598599 fn serialize_struct_variant(600 self,601 _name: &'static str,602 _variant_index: u32,603 variant: &'static str,604 len: usize,605 ) -> Result<Self::SerializeStructVariant, Self::Error> {606 Ok(IntoObjValueSerializer::variant_with_capacity(variant, len))607 }608}609610impl Val {611 pub fn from_serde(v: impl Serialize) -> Result<Self, JrError> {612 v.serialize(IntoValSerializer)613 }614}615616impl serde::ser::Error for JrError {617 fn custom<T>(msg: T) -> Self618 where619 T: std::fmt::Display,620 {621 runtime_error!("serde: {msg}")622 }623}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()