difftreelog
feat return NumValue directly from parser
in: master
15 files changed
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -5,10 +5,7 @@
os::raw::{c_char, c_double, c_int},
};
-use jrsonnet_evaluator::{
- ObjValue, Val,
- val::{ArrValue, NumValue},
-};
+use jrsonnet_evaluator::{NumValue, ObjValue, Val};
use crate::VM;
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth1use std::{cmp::Ordering, convert::Infallible, fmt};23use jrsonnet_gcmodule::{Acyclic, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_ir::{BinaryOpType, Source, SourcePath, Span, Spanned, UnaryOpType};6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{10 ObjValue, ResolvePathOwned,11 function::{CallLocation, FunctionSignature, ParamName},12 stdlib::format::FormatError,13 typed::TypeLocError,14 val::ConvertNumValueError,15};1617#[derive(Debug, Clone)]18pub struct SyntaxError {19 pub message: String,20 pub location: (u32, u32),21}22impl fmt::Display for SyntaxError {23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {24 write!(f, "{}", self.message)25 }26}2728pub(crate) fn format_found(list: &[IStr], what: &str) -> String {29 if list.is_empty() {30 return String::new();31 }32 let mut out = String::new();33 out.push_str("\nThere ");34 if list.len() > 1 {35 out.push_str("are ");36 } else {37 out.push_str("is a ");38 }39 out.push_str(what);40 if list.len() > 1 {41 out.push('s');42 }43 out.push_str(" with similar name");44 if list.len() > 1 {45 out.push('s');46 }47 out.push_str(" present: ");48 for (i, v) in list.iter().enumerate() {49 if i != 0 {50 out.push_str(", ");51 }52 out.push_str(v as &str);53 }54 out55}5657const fn format_empty_str(str: &str) -> &str {58 if str.is_empty() {59 "\"\" (empty string)"60 } else {61 str62 }63}6465pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {66 let mut heap = Vec::new();67 for field in v.fields_ex(68 true,69 #[cfg(feature = "exp-preserve-order")]70 false,71 ) {72 let conf = strsim::jaro_winkler(field.as_str(), key.as_str());73 if conf < 0.8 {74 continue;75 }76 assert!(77 field.as_str() != key.as_str(),78 "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!"79 );8081 heap.push((conf, field));82 }83 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));84 heap.into_iter().map(|v| v.1).collect()85}8687/// Possible errors88#[allow(missing_docs)]89#[derive(Error, Debug, Clone, Trace)]90#[non_exhaustive]91pub enum ErrorKind {92 #[error("intrinsic not found: {0}")]93 IntrinsicNotFound(IStr),9495 #[error("operator {0} does not operate on type {1}")]96 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),97 #[error("binary operation {1} {0} {2} is not implemented")]98 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),99100 #[error("self/super/$ are only usable inside objects")]101 CantUseSelfSupOutsideOfObject,102 #[error("no super found")]103 NoSuperFound,104105 #[error("for loop can only iterate over arrays")]106 InComprehensionCanOnlyIterateOverArray,107108 #[error("array out of bounds: {0} is not within [0,{1})")]109 ArrayBoundsError(isize, usize),110 #[error("string out of bounds: {0} is not within [0,{1})")]111 StringBoundsError(usize, usize),112113 #[error("assert failed: {}", format_empty_str(.0))]114 AssertionFailed(IStr),115116 #[error("local is not defined: {0}{found}", found = format_found(.1, "local"))]117 VariableIsNotDefined(IStr, Vec<IStr>),118 #[error("duplicate local var: {0}")]119 DuplicateLocalVar(IStr),120121 #[error("type mismatch: expected {expected}, got {2} {0}", expected = .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]122 TypeMismatch(&'static str, Vec<ValType>, ValType),123 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]124 NoSuchField(IStr, Vec<IStr>),125126 #[error("only functions can be called, got {0}")]127 OnlyFunctionsCanBeCalledGot(ValType),128 #[error("parameter {0} is not defined")]129 UnknownFunctionParameter(IStr),130 #[error("argument {0} is already bound")]131 BindingParameterASecondTime(IStr),132 #[error("too many args, function has {0}\nFunction has the following signature: {1}")]133 TooManyArgsFunctionHas(usize, FunctionSignature),134 #[error("function argument is not passed: {0}\nFunction has the following signature: {1}")]135 FunctionParameterNotBoundInCall(ParamName, FunctionSignature),136137 #[error("external variable is not defined: {0}")]138 UndefinedExternalVariable(IStr),139140 #[error("field name should be string, got {0}")]141 FieldMustBeStringGot(ValType),142 #[error("duplicate field name: {}", format_empty_str(.0))]143 DuplicateFieldName(IStr),144145 #[error("attempted to index array with string {}", format_empty_str(.0))]146 AttemptedIndexAnArrayWithString(IStr),147 #[error("{0} index type should be {1}, got {2}")]148 ValueIndexMustBeTypeGot(ValType, ValType, ValType),149 #[error("cant index into {0}")]150 CantIndexInto(ValType),151 #[error("{0} is not indexable")]152 ValueIsNotIndexable(ValType),153154 #[error("super can't be used standalone")]155 StandaloneSuper,156157 #[error("can't resolve {1} from {0}")]158 ImportFileNotFound(SourcePath, ResolvePathOwned),159 #[error("resolved file not found: {:?}", .0)]160 ResolvedFileNotFound(SourcePath),161 #[error("can't import {0}: is a directory")]162 ImportIsADirectory(SourcePath),163 #[error("imported file is not valid utf-8: {0:?}")]164 ImportBadFileUtf8(SourcePath),165 #[error("import io error: {0}")]166 ImportIo(String),167 #[error("tried to import {1} from {0}, but imports are not supported")]168 ImportNotSupported(SourcePath, ResolvePathOwned),169 #[error("can't import from virtual file")]170 CantImportFromVirtualFile,171 #[error("syntax error: {error}")]172 ImportSyntaxError {173 path: Source,174 #[trace(skip)]175 error: Box<SyntaxError>,176 },177178 #[error("runtime error: {}", format_empty_str(.0))]179 RuntimeError(IStr),180 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]181 StackOverflow,182 #[error("infinite recursion detected")]183 InfiniteRecursionDetected,184 #[error("tried to index by fractional value")]185 FractionalIndex,186 #[error("attempted to divide by zero")]187 DivisionByZero,188189 #[error("string manifest output is not an string")]190 StringManifestOutputIsNotAString,191 #[error("stream manifest output is not an array")]192 StreamManifestOutputIsNotAArray,193 #[error("multi manifest output is not an object")]194 MultiManifestOutputIsNotAObject,195196 #[error("cant recurse stream manifest")]197 StreamManifestOutputCannotBeRecursed,198 #[error("stream manifest output cannot consist of raw strings")]199 StreamManifestCannotNestString,200201 #[error("{}", format_empty_str(.0))]202 ImportCallbackError(String),203 #[error("invalid unicode codepoint: {0}")]204 InvalidUnicodeCodepointGot(u32),205206 #[error("convert num value: {0}")]207 ConvertNumValue(#[from] ConvertNumValueError),208209 #[error("format error: {0}")]210 Format(#[from] FormatError),211 #[error("type error: {0}")]212 TypeError(TypeLocError),213214 #[cfg(feature = "anyhow-error")]215 #[error(transparent)]216 Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),217}218219#[cfg(feature = "anyhow-error")]220impl From<anyhow::Error> for Error {221 fn from(e: anyhow::Error) -> Self {222 Self::new(ErrorKind::Other(std::rc::Rc::new(e)))223 }224}225226impl From<ErrorKind> for Error {227 fn from(e: ErrorKind) -> Self {228 Self::new(e)229 }230}231232impl From<Infallible> for Error {233 fn from(_value: Infallible) -> Self {234 unreachable!()235 }236}237238/// Single stack trace frame239#[derive(Clone, Debug, Trace)]240pub struct StackTraceElement {241 /// Source of this frame242 /// Some frames only act as description, without attached source243 pub location: Option<Span>,244 /// Frame description245 pub desc: String,246}247#[derive(Debug, Clone, Trace)]248pub struct StackTrace(pub Vec<StackTraceElement>);249250#[derive(Clone, Trace)]251pub struct Error(Box<(ErrorKind, StackTrace)>);252253#[cfg(target_pointer_width = "64")]254static_assertions::assert_eq_size!(Error, usize);255256impl Error {257 pub fn new(e: ErrorKind) -> Self {258 Self(Box::new((e, StackTrace(vec![]))))259 }260261 pub const fn error(&self) -> &ErrorKind {262 &(self.0).0263 }264 pub fn error_mut(&mut self) -> &mut ErrorKind {265 &mut (self.0).0266 }267 pub const fn trace(&self) -> &StackTrace {268 &(self.0).1269 }270 pub fn trace_mut(&mut self) -> &mut StackTrace {271 &mut (self.0).1272 }273}274impl fmt::Display for Error {275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {276 writeln!(f, "{}", self.0.0)?;277 for el in &self.0.1.0 {278 write!(f, "\t{}", el.desc)?;279 if let Some(loc) = &el.location {280 write!(f, "at {}", loc.0.0.0)?;281 loc.0.map_source_locations(&[loc.1, loc.2]);282 }283 writeln!(f)?;284 }285 Ok(())286 }287}288impl fmt::Debug for Error {289 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {290 f.debug_tuple("LocError").field(&self.0).finish()291 }292}293impl std::error::Error for Error {}294295pub trait ErrorSource {296 fn to_location(self) -> Option<Span>;297}298impl<T: Acyclic> ErrorSource for &Spanned<T> {299 fn to_location(self) -> Option<Span> {300 Some(self.span.clone())301 }302}303impl ErrorSource for &Span {304 fn to_location(self) -> Option<Span> {305 Some(self.clone())306 }307}308impl ErrorSource for CallLocation<'_> {309 fn to_location(self) -> Option<Span> {310 self.0.cloned()311 }312}313314pub type Result<V, E = Error> = std::result::Result<V, E>;315pub trait ResultExt: Sized {316 #[must_use]317 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;318 #[must_use]319 fn description(self, msg: &str) -> Self {320 self.with_description(|| msg)321 }322323 #[must_use]324 fn with_description_src<O: Into<String>>(325 self,326 src: impl ErrorSource,327 msg: impl FnOnce() -> O,328 ) -> Self;329 #[must_use]330 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {331 self.with_description_src(src, || msg)332 }333}334impl<T> ResultExt for Result<T, Error> {335 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {336 if let Err(e) = &mut self {337 let trace = e.trace_mut();338 trace.0.push(StackTraceElement {339 location: None,340 desc: msg().into(),341 });342 }343 self344 }345346 fn with_description_src<O: Into<String>>(347 mut self,348 src: impl ErrorSource,349 msg: impl FnOnce() -> O,350 ) -> Self {351 if let Err(e) = &mut self {352 let trace = e.trace_mut();353 trace.0.push(StackTraceElement {354 location: src.to_location(),355 desc: msg().into(),356 });357 }358 self359 }360}361362#[macro_export]363macro_rules! bail {364 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {365 return Err($w$(::$i)*$(($($tt)*))?.into())366 };367 ($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {368 return Err($w$(::$i)*$({$($tt)*})?.into())369 };370 ($l:literal$(, $($tt:tt)*)?) => {371 return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())372 };373}374375#[macro_export]376macro_rules! runtime_error {377 ($l:literal$(, $($tt:tt)*)?) => {378 $crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))379 };380}crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -21,7 +21,7 @@
function::{CallLocation, FuncDesc, FuncVal, PreparedFuncVal},
in_frame,
typed::{FromUntyped, IntoUntyped as _, Typed},
- val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
+ val::{CachedUnbound, IndexableVal, StrValue, Thunk},
with_state,
};
pub mod destructure;
@@ -58,9 +58,7 @@
}
Some(match expr {
Expr::Str(s) => Val::string(s.clone()),
- Expr::Num(n) => {
- Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))
- }
+ Expr::Num(n) => Val::Num(*n),
Expr::Literal(LiteralType::False) => Val::Bool(false),
Expr::Literal(LiteralType::True) => Val::Bool(true),
Expr::Literal(LiteralType::Null) => Val::Null,
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,6 +1,7 @@
use std::borrow::Cow;
use jrsonnet_interner::{IBytes, IStr};
+use jrsonnet_ir::NumValue;
use serde::{
Deserialize, Serialize, Serializer,
de::{self, Visitor},
@@ -12,7 +13,6 @@
use crate::{
Error as JrError, ObjValue, ObjValueBuilder, Result, Val, in_description_frame, runtime_error,
- val::NumValue,
};
impl<'de> Deserialize<'de> for Val {
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -42,6 +42,7 @@
use jrsonnet_gcmodule::{Cc, Trace, cc_dyn};
pub use jrsonnet_interner::{IBytes, IStr};
pub use jrsonnet_ir as parser;
+pub use jrsonnet_ir::NumValue;
use jrsonnet_ir::{Expr, Source, SourcePath};
#[doc(hidden)]
pub use jrsonnet_macros;
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -829,7 +829,7 @@
#[cfg(test)]
pub mod test_format {
use super::*;
- use crate::val::NumValue;
+ use crate::NumValue;
#[test]
fn parse() {
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -2,6 +2,8 @@
use jrsonnet_gcmodule::Trace;
use jrsonnet_interner::{IBytes, IStr};
+use jrsonnet_ir::NumValue;
+pub use jrsonnet_ir::{MAX_SAFE_INTEGER, MIN_SAFE_INTEGER};
use jrsonnet_types::{ComplexValType, ValType};
use crate::{
@@ -10,7 +12,7 @@
bail,
function::FuncVal,
typed::CheckType,
- val::{IndexableVal, NumValue, StrValue, ThunkMapper},
+ val::{IndexableVal, StrValue, ThunkMapper},
};
#[doc(hidden)]
@@ -219,11 +221,6 @@
Ok(inner.map(<ThunkFromUntyped<T>>::default()))
}
}
-
-#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]
-pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS)) - 1) as f64;
-#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]
-pub const MIN_SAFE_INTEGER: f64 = (-((1i64 << (f64::MANTISSA_DIGITS)) - 1)) as f64;
macro_rules! impl_int {
($($ty:ty)*) => {$(
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -5,7 +5,6 @@
marker::PhantomData,
mem::replace,
num::NonZeroU32,
- ops::Deref,
rc::Rc,
};
@@ -14,16 +13,15 @@
pub use jrsonnet_macros::Thunk;
use jrsonnet_types::ValType;
use rustc_hash::FxHashMap;
-use thiserror::Error;
pub use crate::arr::{ArrValue, ArrayLike};
use crate::{
- ObjValue, Result, SupThis, Unbound, WeakSupThis, bail,
+ NumValue, ObjValue, Result, SupThis, Unbound, WeakSupThis, bail,
error::{Error, ErrorKind::*},
function::FuncVal,
gc::WithCapacityExt as _,
manifest::{ManifestFormat, ToStringFormat},
- typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},
+ typed::BoundedUsize,
};
pub trait ThunkValue: Trace {
@@ -439,134 +437,6 @@
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)]
-#[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))
- }
- #[inline]
- pub const fn get(&self) -> f64 {
- self.0
- }
- pub(crate) fn truncate_for_bitwise(self) -> Result<i64> {
- if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {
- bail!("numberic value outside of safe integer range for bitwise operation");
- }
- #[expect(clippy::cast_possible_truncation, reason = "intended")]
- Ok(self.0 as i64)
- }
-}
-impl PartialEq for NumValue {
- fn eq(&self, other: &Self) -> bool {
- self.0 == other.0
- }
-}
-impl Eq for NumValue {}
-impl Ord for NumValue {
- #[inline]
- fn cmp(&self, other: &Self) -> Ordering {
- // Can't use `total_cmp`: its behavior for `-0` and `0`
- // is not following wanted.
- unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }
- }
-}
-impl PartialOrd for NumValue {
- #[inline]
- fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
- Some(self.cmp(other))
- }
-}
-impl Debug for NumValue {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- Debug::fmt(&self.0, f)
- }
-}
-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;
-
- #[inline]
- fn deref(&self) -> &Self::Target {
- &self.0
- }
-}
-macro_rules! impl_num {
- ($($ty:ty),+) => {$(
- impl From<$ty> for NumValue {
- #[inline]
- 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;
- #[inline]
- fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {
- #[expect(clippy::cast_precision_loss, reason = "precision loss is explicitly handled")]
- 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;
-
- #[inline]
- fn try_from(value: f64) -> Result<Self, Self::Error> {
- Self::new(value).ok_or(ConvertNumValueError::NonFinite)
- }
-}
-impl TryFrom<f32> for NumValue {
- type Error = ConvertNumValueError;
-
- #[inline]
- fn try_from(value: f32) -> Result<Self, Self::Error> {
- Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)
}
}
crates/jrsonnet-ir-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-ir-parser/src/lib.rs
+++ b/crates/jrsonnet-ir-parser/src/lib.rs
@@ -4,8 +4,8 @@
use jrsonnet_ir::{
ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType, BindSpec, CompSpec, Destruct, Expr,
ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse, IfSpecData,
- ImportKind, IndexPart, LiteralType, Member, ObjBody, ObjComp, ObjMembers, Slice, SliceDesc,
- Source, Span, Spanned, UnaryOpType, Visibility, unescape,
+ ImportKind, IndexPart, LiteralType, Member, NumValue, ObjBody, ObjComp, ObjMembers, Slice,
+ SliceDesc, Source, Span, Spanned, UnaryOpType, Visibility, unescape,
};
use jrsonnet_lexer::{Lexeme, Lexer, Span as LexSpan, SyntaxKind, T, collect_lexed_str_block};
@@ -202,17 +202,21 @@
)
}
-fn parse_number(p: &mut Parser<'_>) -> Result<f64> {
+fn parse_number(p: &mut Parser<'_>) -> Result<NumValue> {
let text = p.text();
let n: f64 = text
.replace('_', "")
.parse()
.map_err(|_| p.error(format!("invalid number literal: {text}")))?;
- if !n.is_finite() {
- return Err(p.error("numbers are finite".into()));
- }
+
+ let v = match NumValue::try_from(n) {
+ Ok(v) => v,
+ Err(e) => return Err(p.error(format!("invalid number value: {e}"))),
+ };
+
p.eat_any();
- Ok(n)
+
+ Ok(v)
}
fn ident(p: &mut Parser<'_>) -> Result<IStr> {
crates/jrsonnet-ir/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-ir/Cargo.toml
+++ b/crates/jrsonnet-ir/Cargo.toml
@@ -19,6 +19,7 @@
static_assertions.workspace = true
peg.workspace = true
+thiserror.workspace = true
[dev-dependencies]
insta.workspace = true
crates/jrsonnet-ir/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-ir/src/expr.rs
+++ b/crates/jrsonnet-ir/src/expr.rs
@@ -8,6 +8,7 @@
use jrsonnet_interner::IStr;
use crate::{
+ NumValue,
function::{FunctionSignature, ParamDefault, ParamName, ParamParse},
source::Source,
};
@@ -398,7 +399,7 @@
/// String value: "hello"
Str(IStr),
/// Number: 1, 2.0, 2e+20
- Num(f64),
+ Num(NumValue),
/// Variable name: test
Var(Spanned<IStr>),
crates/jrsonnet-ir/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-ir/src/lib.rs
+++ b/crates/jrsonnet-ir/src/lib.rs
@@ -1,7 +1,10 @@
#![allow(clippy::redundant_closure_call, clippy::derive_partial_eq_without_eq)]
mod expr;
+use std::{cmp::Ordering, fmt, ops::Deref};
+
pub use expr::*;
+use jrsonnet_gcmodule::Acyclic;
pub use jrsonnet_interner::IStr;
pub mod function;
mod location;
@@ -14,3 +17,134 @@
Source, SourceDefaultIgnoreJpath, SourceDirectory, SourceFifo, SourceFile, SourcePath,
SourcePathT, SourceVirtual,
};
+
+// It seels to be a wrong place for this kind of stuff, but as it would also be used for static analysis and
+// is already wanted for NumValue, I don't know a better place.
+#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]
+pub const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS)) - 1) as f64;
+#[expect(clippy::cast_precision_loss, reason = "checked to not overflow")]
+pub const MIN_SAFE_INTEGER: f64 = (-((1i64 << (f64::MANTISSA_DIGITS)) - 1)) as f64;
+
+/// Represents jsonnet number
+/// Jsonnet numbers are finite f64, with NaNs disallowed
+#[derive(Acyclic, Clone, Copy)]
+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))
+ }
+ #[inline]
+ pub const fn get(&self) -> f64 {
+ self.0
+ }
+ pub fn truncate_for_bitwise(self) -> Result<i64, ConvertNumValueError> {
+ if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {
+ return Err(ConvertNumValueError::BitwiseSafeRange);
+ }
+ #[expect(clippy::cast_possible_truncation, reason = "intended")]
+ Ok(self.0 as i64)
+ }
+}
+impl PartialEq for NumValue {
+ fn eq(&self, other: &Self) -> bool {
+ self.0 == other.0
+ }
+}
+impl Eq for NumValue {}
+impl Ord for NumValue {
+ #[inline]
+ fn cmp(&self, other: &Self) -> Ordering {
+ // Can't use `total_cmp`: its behavior for `-0` and `0`
+ // is not following wanted.
+ unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }
+ }
+}
+impl PartialOrd for NumValue {
+ #[inline]
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.cmp(other))
+ }
+}
+impl fmt::Debug for NumValue {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Debug::fmt(&self.0, f)
+ }
+}
+impl fmt::Display for NumValue {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Display::fmt(&self.0, f)
+ }
+}
+impl Deref for NumValue {
+ type Target = f64;
+
+ #[inline]
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+macro_rules! impl_num {
+ ($($ty:ty),+) => {$(
+ impl From<$ty> for NumValue {
+ #[inline]
+ fn from(value: $ty) -> Self {
+ Self(value.into())
+ }
+ }
+ )+};
+}
+impl_num!(i8, u8, i16, u16, i32, u32);
+
+#[derive(Clone, Copy, Debug, thiserror::Error, Acyclic)]
+pub enum ConvertNumValueError {
+ #[error("overflow")]
+ Overflow,
+ #[error("underflow")]
+ Underflow,
+ #[error("non-finite")]
+ NonFinite,
+ #[error("float out of safe int range")]
+ BitwiseSafeRange,
+}
+
+macro_rules! impl_try_num {
+ ($($ty:ty),+) => {$(
+ impl TryFrom<$ty> for NumValue {
+ type Error = ConvertNumValueError;
+ #[inline]
+ fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {
+ #[expect(clippy::cast_precision_loss, reason = "precision loss is explicitly handled")]
+ 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;
+
+ #[inline]
+ fn try_from(value: f64) -> Result<Self, Self::Error> {
+ Self::new(value).ok_or(ConvertNumValueError::NonFinite)
+ }
+}
+impl TryFrom<f32> for NumValue {
+ type Error = ConvertNumValueError;
+
+ #[inline]
+ fn try_from(value: f32) -> Result<Self, Self::Error> {
+ Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)
+ }
+}
crates/jrsonnet-peg-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-peg-parser/src/lib.rs
+++ b/crates/jrsonnet-peg-parser/src/lib.rs
@@ -4,8 +4,8 @@
use jrsonnet_ir::{
ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BindSpec, CompSpec, Destruct, DestructRest, Expr,
ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse, IfSpecData,
- ImportKind, IndexPart, LiteralType, Member, ObjBody, ObjComp, ObjMembers, Slice, SliceDesc,
- Source, Span, Spanned, Visibility, unescape,
+ ImportKind, IndexPart, LiteralType, Member, NumValue, ObjBody, ObjComp, ObjMembers, Slice,
+ SliceDesc, Source, Span, Spanned, Visibility, unescape,
};
use peg::parser;
@@ -52,7 +52,7 @@
/// Sequence of digits
rule uint_str() -> &'input str = a:$(digit()+ ("_" digit()+)*) { a }
/// Number in scientific notation format
- rule number() -> f64 = quiet!{a:$(uint_str() ("." uint_str())? (['e'|'E'] (s:['+'|'-'])? uint_str())?) {? a.replace("_","").parse().map_err(|_| "<number>") }} / expected!("<number>")
+ rule number() -> f64 = quiet!{a:$(uint_str() ("." uint_str())? (['e'|'E'] (s:['+'|'-'])? uint_str())?) {? a.replace('_',"").parse().map_err(|_| "<number>") }} / expected!("<number>")
/// Reserved word followed by any non-alphanumberic
rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "importbin" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()
@@ -267,7 +267,7 @@
Expr::ArrComp(Rc::new(expr), specs)
}
pub rule number_expr(s: &ParserSettings) -> Expr
- = n:number() {? if n.is_finite() {
+ = n:number() {? if let Some(n) = NumValue::new(n) {
Ok(Expr::Num(n))
} else {
Err("!!!numbers are finite")
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -12,13 +12,12 @@
pub use encoding::*;
pub use hash::*;
use jrsonnet_evaluator::{
- ContextBuilder, IStr, ObjValue, ObjValueBuilder, Thunk, Val,
+ ContextBuilder, IStr, NumValue, ObjValue, ObjValueBuilder, Thunk, Val,
error::Result,
function::{CallLocation, FuncVal, builtin_id},
tla::TlaArg,
trace::PathResolver,
typed::SerializeTypedObj as _,
- val::NumValue,
};
use jrsonnet_gcmodule::{Acyclic, Cc, Trace};
use jrsonnet_ir::Source;
crates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -2,12 +2,12 @@
//! However, in our case we instead implement them in native, and implement native functions on top of core for backwards compatibility
use jrsonnet_evaluator::{
- IStr, Result, Val,
+ IStr, NumValue, Result, Val,
function::builtin,
operator::evaluate_mod_op,
stdlib::std_format,
typed::{Either, Either2},
- val::{NumValue, equals, primitive_equals},
+ val::{equals, primitive_equals},
};
#[builtin]