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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -2,7 +2,9 @@
use jrsonnet_gcmodule::{Acyclic, Trace};
use jrsonnet_interner::IStr;
-use jrsonnet_ir::{BinaryOpType, Source, SourcePath, Span, Spanned, UnaryOpType};
+use jrsonnet_ir::{
+ BinaryOpType, ConvertNumValueError, Source, SourcePath, Span, Spanned, UnaryOpType,
+};
use jrsonnet_types::ValType;
use thiserror::Error;
@@ -11,7 +13,6 @@
function::{CallLocation, FunctionSignature, ParamName},
stdlib::format::FormatError,
typed::TypeLocError,
- val::ConvertNumValueError,
};
#[derive(Debug, Clone)]
@@ -228,6 +229,11 @@
Self::new(e)
}
}
+impl From<ConvertNumValueError> for Error {
+ fn from(e: ConvertNumValueError) -> Self {
+ Self::new(ErrorKind::ConvertNumValue(e))
+ }
+}
impl From<Infallible> for Error {
fn from(_value: Infallible) -> Self {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_ir::{6 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprParams, FieldMember,7 FieldName, ForSpecData, IfSpecData, ImportKind, LiteralType, ObjBody, ObjMembers, Spanned,8 function::ParamName,9};10use jrsonnet_types::ValType;1112use self::destructure::destruct;13use crate::{14 Context, ContextBuilder, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,15 ResultExt, SupThis, Unbound, Val,16 arr::ArrValue,17 bail,18 destructure::evaluate_dest,19 error::{ErrorKind::*, suggest_object_fields},20 evaluate::operator::{evaluate_binary_op_special, evaluate_unary_op},21 function::{CallLocation, FuncDesc, FuncVal, PreparedFuncVal},22 in_frame,23 typed::{FromUntyped, IntoUntyped as _, Typed},24 val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},25 with_state,26};27pub mod destructure;28pub mod operator;2930// This is the amount of bytes that need to be left on the stack before increasing the size.31// It must be at least as large as the stack required by any code that does not call32// `ensure_sufficient_stack`.33const RED_ZONE: usize = 100 * 1024; // 100k3435// Only the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then36// on. This flag has performance relevant characteristics. Don't set it too high.37const STACK_PER_RECURSION: usize = 1024 * 1024; // 1MB3839/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations40/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit41/// from this.42///43/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.44#[inline]45pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {46 stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)47}4849pub fn evaluate_trivial(expr: &Expr) -> Option<Val> {50 fn is_trivial(expr: &Expr) -> bool {51 match expr {52 Expr::Str(_)53 | Expr::Num(_)54 | Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,55 Expr::Arr(a) => a.iter().all(is_trivial),56 _ => false,57 }58 }59 Some(match expr {60 Expr::Str(s) => Val::string(s.clone()),61 Expr::Num(n) => {62 Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))63 }64 Expr::Literal(LiteralType::False) => Val::Bool(false),65 Expr::Literal(LiteralType::True) => Val::Bool(true),66 Expr::Literal(LiteralType::Null) => Val::Null,67 Expr::Arr(n) => {68 if n.iter().any(|e| !is_trivial(e)) {69 return None;70 }71 Val::Arr(72 n.iter()73 .map(evaluate_trivial)74 .map(|e| e.expect("checked trivial"))75 .collect(),76 )77 }78 _ => return None,79 })80}8182pub fn evaluate_method(ctx: Context, name: IStr, params: ExprParams, body: Rc<Expr>) -> Val {83 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {84 name,85 ctx,86 params,87 body,88 })))89}9091pub fn evaluate_field_name(ctx: Context, field_name: &Spanned<FieldName>) -> Result<Option<IStr>> {92 Ok(match &field_name.value {93 FieldName::Fixed(n) => Some(n.clone()),94 FieldName::Dyn(expr) => in_frame(95 CallLocation::new(&field_name.span),96 || "evaluating field name".to_string(),97 || {98 let v = evaluate(ctx, expr)?;99 Ok(if matches!(v, Val::Null) {100 None101 } else {102 Some(IStr::from_untyped(v)?)103 })104 },105 )?,106 })107}108109pub fn evaluate_comp(110 ctx: Context,111 specs: &[CompSpec],112 mut guaranteed_reserve: usize,113 callback: &mut impl FnMut(Context, usize) -> Result<()>,114) -> Result<()> {115 match specs.first() {116 None => callback(ctx, guaranteed_reserve)?,117 Some(CompSpec::IfSpec(IfSpecData { cond, span: _ })) => {118 if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {119 evaluate_comp(ctx, &specs[1..], 0, callback)?;120 }121 }122 Some(CompSpec::ForSpec(ForSpecData {123 destruct: into,124 over,125 })) => {126 match evaluate(ctx.clone(), over)? {127 Val::Arr(list) => {128 guaranteed_reserve = guaranteed_reserve.max(1) * list.len();129 for (i, item) in list.iter_lazy().enumerate() {130 let fctx = Pending::new();131 let mut ctx = ContextBuilder::extend_fast(ctx.clone());132 destruct(into, item, fctx.clone(), &mut ctx)?;133 let ctx = ctx.build().into_future(fctx);134135 let specs = &specs[1..];136 evaluate_comp(137 ctx,138 specs,139 if i == 0 || !specs.is_empty() {140 guaranteed_reserve141 } else {142 0143 },144 callback,145 )?;146 }147 }148 Val::Obj(obj) if cfg!(feature = "exp-object-iteration") => {149 let fields = obj.fields(150 // TODO: Should there be ability to preserve iteration order?151 #[cfg(feature = "exp-preserve-order")]152 false,153 );154 guaranteed_reserve = guaranteed_reserve.max(1) * fields.len();155 for (i, field) in fields.into_iter().enumerate() {156 let fctx = Pending::new();157 let mut ctx = ContextBuilder::extend_fast(ctx.clone());158 let obj = obj.clone();159 let value = Thunk::evaluated(Val::arr(vec![160 Thunk::evaluated(Val::string(field.clone())),161 obj.get_lazy(field).expect(162 "field exists, as field name was obtained from object.fields()",163 ),164 ]));165 destruct(into, value, fctx.clone(), &mut ctx)?;166 let ctx = ctx.build().into_future(fctx);167168 evaluate_comp(169 ctx,170 &specs[1..],171 if i == 0 || !specs.is_empty() {172 guaranteed_reserve173 } else {174 0175 },176 callback,177 )?;178 }179 }180 _ => bail!(InComprehensionCanOnlyIterateOverArray),181 }182 }183 }184 Ok(())185}186187fn evaluate_arr_comp(ctx: Context, expr: &Rc<Expr>, comp_specs: &[CompSpec]) -> Result<ArrValue> {188 let ctx = ctx.branch_point();189 'eager: {190 let mut out = Vec::new();191192 if evaluate_comp(ctx.clone(), comp_specs, 0, &mut |ctx, reserve| {193 if reserve != 0 {194 out.reserve(reserve);195 }196 out.push(evaluate(ctx, expr)?);197 Ok(())198 })199 .is_err()200 {201 break 'eager;202 }203204 return Ok(ArrValue::new(out));205 };206 let mut out = Vec::new();207 evaluate_comp(ctx, comp_specs, 0, &mut |ctx, reserve| {208 if reserve != 0 {209 out.reserve(reserve);210 }211 let expr = expr.clone();212 out.push(Thunk!(move || evaluate(ctx, &expr)));213 Ok(())214 })?;215 Ok(ArrValue::new(out))216}217218trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}219impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}220221fn evaluate_object_locals(222 fctx: Context,223 locals: Rc<Vec<BindSpec>>,224) -> impl CloneableUnbound<Context> {225 #[derive(Trace, Clone)]226 struct UnboundLocals {227 fctx: Context,228 locals: Rc<Vec<BindSpec>>,229 }230 impl Unbound for UnboundLocals {231 type Bound = Context;232233 fn bind(&self, sup_this: SupThis) -> Result<Context> {234 let fctx = Context::new_future();235 let ctx = self.fctx.clone();236 let mut ctx = ContextBuilder::extend(ctx);237 for b in self.locals.iter() {238 evaluate_dest(b, fctx.clone(), &mut ctx)?;239 }240241 let ctx = ctx.build_sup_this(sup_this).into_future(fctx);242243 Ok(ctx)244 }245 }246247 UnboundLocals { fctx, locals }248}249250pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(251 builder: &mut ObjValueBuilder,252 ctx: Context,253 uctx: B,254 field: &FieldMember,255) -> Result<()> {256 let name = evaluate_field_name(ctx, &field.name)?;257 let Some(name) = name else {258 return Ok(());259 };260261 match field {262 FieldMember {263 plus,264 params: None,265 visibility,266 value,267 ..268 } => {269 #[derive(Trace)]270 struct UnboundValue<B: Trace> {271 uctx: B,272 value: Rc<Expr>,273 name: IStr,274 }275 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {276 type Bound = Val;277 fn bind(&self, sup_this: SupThis) -> Result<Val> {278 evaluate_named(self.uctx.bind(sup_this)?, &self.value, self.name.clone())279 }280 }281282 builder283 .field(name.clone())284 .with_add(*plus)285 .with_visibility(*visibility)286 .with_location(field.name.span.clone())287 .bindable(UnboundValue {288 uctx,289 value: value.clone(),290 name,291 })?;292 }293 FieldMember {294 params: Some(params),295 visibility,296 value,297 ..298 } => {299 #[derive(Trace)]300 struct UnboundMethod<B: Trace> {301 uctx: B,302 value: Rc<Expr>,303 params: ExprParams,304 name: IStr,305 }306 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {307 type Bound = Val;308 fn bind(&self, sup_this: SupThis) -> Result<Val> {309 Ok(evaluate_method(310 self.uctx.bind(sup_this)?,311 self.name.clone(),312 self.params.clone(),313 self.value.clone(),314 ))315 }316 }317318 builder319 .field(name.clone())320 .with_visibility(*visibility)321 // .with_location(value.span())322 .bindable(UnboundMethod {323 uctx,324 value: value.clone(),325 params: params.clone(),326 name,327 })?;328 }329 }330 Ok(())331}332333#[derive(Trace, Clone)]334struct DirectUnbound(Context);335impl Unbound for DirectUnbound {336 type Bound = Context;337 fn bind(&self, sup_this: SupThis) -> Result<Context> {338 Ok(ContextBuilder::extend(self.0.clone()).build_sup_this(sup_this))339 }340}341342#[allow(clippy::too_many_lines)]343pub fn evaluate_member_list_object(344 super_obj: Option<ObjValue>,345 ctx: Context,346 members: &ObjMembers,347) -> Result<ObjValue> {348 #[derive(Trace)]349 struct ObjectAssert<B: Trace> {350 uctx: B,351 asserts: Rc<Vec<AssertStmt>>,352 }353 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {354 fn run(&self, sup_this: SupThis) -> Result<()> {355 let ctx = self.uctx.bind(sup_this)?;356 for assert in &*self.asserts {357 evaluate_assert(ctx.clone(), assert)?;358 }359 Ok(())360 }361 }362363 let mut builder = ObjValueBuilder::new();364 if let Some(super_obj) = super_obj {365 builder.with_super(super_obj);366 }367368 if members.locals.is_empty() {369 // We can use the same context for all field evaluation, it doesn't depends on locals, only on this/super370 let uctx = DirectUnbound(ctx.clone());371 for field in &members.fields {372 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;373 }374 if !members.asserts.is_empty() {375 builder.assert(ObjectAssert {376 uctx,377 asserts: members.asserts.clone(),378 });379 }380 } else {381 let locals = members.locals.clone();382 // We have single context for all fields, so we can cache them together383 let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));384 for field in &members.fields {385 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;386 }387 if !members.asserts.is_empty() {388 builder.assert(ObjectAssert {389 uctx,390 asserts: members.asserts.clone(),391 });392 }393 }394395 Ok(builder.build())396}397398pub fn evaluate_object(399 super_obj: Option<ObjValue>,400 ctx: Context,401 object: &ObjBody,402) -> Result<ObjValue> {403 Ok(match object {404 ObjBody::MemberList(members) => evaluate_member_list_object(super_obj, ctx, members)?,405 ObjBody::ObjComp(obj) => {406 let mut builder = ObjValueBuilder::new();407 if let Some(super_obj) = super_obj {408 builder.with_super(super_obj);409 }410 let locals = obj.locals.clone();411 evaluate_comp(412 ctx.branch_point(),413 &obj.compspecs,414 0,415 &mut |ctx, reserve| {416 let uctx = evaluate_object_locals(ctx.clone(), locals.clone());417 builder.reserve_fields(reserve);418419 evaluate_field_member(&mut builder, ctx, uctx, &obj.field)420 },421 )?;422423 builder.build()424 }425 })426}427428pub fn evaluate_apply(429 ctx: Context,430 value: &Expr,431 args: &ArgsDesc,432 loc: CallLocation<'_>,433 tailstrict: bool,434) -> Result<Val> {435 let value = evaluate(ctx.clone(), value)?;436 Ok(match value {437 Val::Func(f) => {438 let name = f.name();439 let unnamed = args440 .unnamed441 .iter()442 .cloned()443 .map(|un| evaluate_thunk(ctx.clone(), un, tailstrict))444 .collect::<Result<Vec<_>>>()?;445 let named = args446 .values447 .iter()448 .cloned()449 .map(|un| evaluate_thunk(ctx.clone(), un, tailstrict))450 .collect::<Result<Vec<_>>>()?;451 let prepare = PreparedFuncVal::new(f, args.unnamed.len(), &args.names)452 .with_description_src(loc, || format!("function <{name}> call"))?;453 let body = || prepare.call(loc, &unnamed, &named);454 if tailstrict {455 body()?456 } else {457 in_frame(loc, || format!("function <{name}> call"), body)?458 }459 }460 v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),461 })462}463464pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {465 let AssertStmt { assertion, message } = assertion;466 let assertion_result = in_frame(467 CallLocation::new(&assertion.span),468 || "assertion condition".to_owned(),469 || bool::from_untyped(evaluate(ctx.clone(), assertion)?),470 )?;471 if !assertion_result {472 in_frame(473 CallLocation::new(&assertion.span),474 || "assertion failure".to_owned(),475 || {476 if let Some(msg) = message {477 bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));478 }479 bail!(AssertionFailed(Val::Null.to_string()?));480 },481 )?;482 }483 Ok(())484}485486pub fn evaluate_named_param(ctx: Context, expr: &Expr, name: ParamName) -> Result<Val> {487 match name {488 ParamName::Named(name) => evaluate_named(ctx, expr, name),489 ParamName::Unnamed => evaluate(ctx, expr),490 }491}492493pub fn evaluate_named(ctx: Context, expr: &Expr, name: IStr) -> Result<Val> {494 use Expr::*;495 Ok(match expr {496 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),497 _ => evaluate(ctx, expr)?,498 })499}500501pub fn evaluate_thunk(ctx: Context, expr: Rc<Expr>, tailstrict: bool) -> Result<Thunk<Val>> {502 Ok(if tailstrict {503 Thunk::evaluated(evaluate(ctx, &expr)?)504 } else {505 Thunk!(move || { evaluate(ctx, &expr) })506 })507}508#[allow(clippy::too_many_lines)]509pub fn evaluate(ctx: Context, expr: &Expr) -> Result<Val> {510 use Expr::*;511512 Ok(match expr {513 Literal(LiteralType::This) => Val::Obj(ctx.try_this()?),514 Literal(LiteralType::Super) => Val::Obj(ctx.try_sup_this()?.standalone_super()?),515 Literal(LiteralType::Dollar) => Val::Obj(ctx.try_dollar()?),516 Literal(LiteralType::True) => Val::Bool(true),517 Literal(LiteralType::False) => Val::Bool(false),518 Literal(LiteralType::Null) => Val::Null,519 Str(v) => Val::string(v.clone()),520 Num(v) => Val::try_num(*v)?,521 // I have tried to remove special behavior from super by implementing standalone-super522 // expresion, but looks like this case still needs special treatment.523 //524 // Note that other jsonnet implementations will fail on `if value in (super)` expression,525 // because the standalone super literal is not supported, that is because in other526 // implementations `in super` treated differently from `in smth_else`.527 BinaryOp(bin)528 if matches!(&bin.rhs, Expr::Literal(LiteralType::Super))529 && bin.op == BinaryOpType::In =>530 {531 let sup_this = ctx.try_sup_this()?;532 // In jsonnet, "field" in e is eager, LHS expression is always executed regardless of super existence.533 // In jrsonnet, however, this wasn't true, this was kept here for compatibility.534 if !sup_this.has_super() {535 return Ok(Val::Bool(false));536 }537 let field = evaluate(ctx, &bin.lhs)?;538 Val::Bool(sup_this.field_in_super(field.to_string()?))539 }540 BinaryOp(bin) => evaluate_binary_op_special(ctx, &bin.lhs, bin.op, &bin.rhs)?,541 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,542 Var(name) => in_frame(543 CallLocation::new(&name.span),544 || format!("local <{}> access", &**name),545 || ctx.binding((**name).clone())?.evaluate(),546 )?,547 Index { indexable, parts } => ensure_sufficient_stack(|| {548 let mut parts = parts.iter();549 let mut indexable = if matches!(&**indexable, Expr::Literal(LiteralType::Super)) {550 let part = parts.next().expect("at least part should exist");551 // sup_this existence check might also be skipped here for null-coalesce...552 // But I believe this might cause errors.553 let sup_this = ctx.try_sup_this()?;554 if !sup_this.has_super() {555 #[cfg(feature = "exp-null-coaelse")]556 if part.null_coaelse {557 return Ok(Val::Null);558 }559 bail!(NoSuperFound)560 }561 let name = evaluate(ctx.clone(), &part.value)?;562563 let Val::Str(name) = name else {564 bail!(ValueIndexMustBeTypeGot(565 ValType::Obj,566 ValType::Str,567 name.value_type(),568 ))569 };570571 let name = name.into_flat();572 match sup_this573 .get_super(name.clone())574 .with_description_src(&part.span, || format!("field <{name}> access"))?575 {576 Some(v) => v,577 #[cfg(feature = "exp-null-coaelse")]578 None if part.null_coaelse => return Ok(Val::Null),579 None => {580 let suggestions = suggest_object_fields(581 &sup_this.standalone_super().expect("super exists"),582 name.clone(),583 );584585 bail!(NoSuchField(name, suggestions))586 }587 }588 } else {589 evaluate(ctx.clone(), indexable)?590 };591592 for part in parts {593 indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {594 (Val::Obj(v), Val::Str(key)) => match v595 .get(key.clone().into_flat())596 .with_description_src(&part.span, || format!("field <{key}> access"))?597 {598 Some(v) => v,599 #[cfg(feature = "exp-null-coaelse")]600 None if part.null_coaelse => return Ok(Val::Null),601 None => {602 let suggestions = suggest_object_fields(&v, key.into_flat());603604 return Err(Error::from(NoSuchField(605 key.clone().into_flat(),606 suggestions,607 )))608 .with_description_src(&part.span, || format!("field <{key}> access"));609 }610 },611 (Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(612 ValType::Obj,613 ValType::Str,614 n.value_type(),615 )),616 (Val::Arr(v), Val::Num(n)) => {617 let n = n.get();618 if n.fract() > f64::EPSILON {619 bail!(FractionalIndex)620 }621 if n < 0.0 {622 #[expect(623 clippy::cast_possible_truncation,624 reason = "it would be truncated anyway"625 )]626 let n = n as isize;627 bail!(ArrayBoundsError(n, v.len()));628 }629 #[expect(630 clippy::cast_possible_truncation,631 clippy::cast_sign_loss,632 reason = "n is checked postive"633 )]634 v.get(n as usize)?635 .ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?636 }637 (Val::Arr(_), Val::Str(n)) => {638 bail!(AttemptedIndexAnArrayWithString(n.into_flat()))639 }640 (Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(641 ValType::Arr,642 ValType::Num,643 n.value_type(),644 )),645646 (Val::Str(s), Val::Num(n)) => Val::Str({647 let n = n.get();648 if n.fract() > f64::EPSILON {649 bail!(FractionalIndex)650 }651 if n < 0.0 {652 #[expect(653 clippy::cast_possible_truncation,654 reason = "it would be truncated anyway"655 )]656 let n = n as isize;657 bail!(ArrayBoundsError(n, s.into_flat().chars().count()));658 }659 #[expect(660 clippy::cast_sign_loss,661 clippy::cast_possible_truncation,662 reason = "n is positive, overflow will truncate as expected"663 )]664 let n = n as usize;665 let v: IStr = s666 .clone()667 .into_flat()668 .chars()669 .skip(n)670 .take(1)671 .collect::<String>()672 .into();673 if v.is_empty() {674 bail!(StringBoundsError(n, s.into_flat().chars().count()))675 }676 StrValue::Flat(v)677 }),678 (Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(679 ValType::Str,680 ValType::Num,681 n.value_type(),682 )),683 #[cfg(feature = "exp-null-coaelse")]684 (Val::Null, _) if part.null_coaelse => return Ok(Val::Null),685 (v, _) => bail!(CantIndexInto(v.value_type())),686 };687 }688 Ok(indexable)689 })?,690 LocalExpr(bindings, returned) => {691 let fctx = Context::new_future();692 let mut ctx = ContextBuilder::extend(ctx);693 for b in bindings {694 evaluate_dest(b, fctx.clone(), &mut ctx)?;695 }696 let ctx = ctx.build().into_future(fctx);697 evaluate(ctx, returned)?698 }699 Arr(items) => {700 if items.is_empty() {701 Val::arr(())702 } else {703 Val::Arr(ArrValue::expr(ctx, items.clone()))704 }705 }706 ArrComp(expr, comp_specs) => Val::Arr(evaluate_arr_comp(ctx, expr, comp_specs)?),707 Obj(body) => Val::Obj(evaluate_object(None, ctx, body)?),708 ObjExtend(a, b) => {709 let base = evaluate(ctx.clone(), a)?;710 match base {711 Val::Obj(base_obj) => Val::Obj(evaluate_object(Some(base_obj), ctx, b)?),712 _ => bail!("ObjExtend lhs should be an object value"),713 }714 }715 Apply(value, args, tailstrict) => ensure_sufficient_stack(|| {716 evaluate_apply(ctx, value, args, CallLocation::new(&args.span), *tailstrict)717 })?,718 Function(params, body) => {719 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())720 }721 AssertExpr(assert) => {722 evaluate_assert(ctx.clone(), &assert.assert)?;723 evaluate(ctx, &assert.rest)?724 }725 ErrorStmt(s, e) => in_frame(726 CallLocation::new(s),727 || "error statement".to_owned(),728 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),729 )?,730 IfElse(if_else) => {731 if in_frame(732 CallLocation::new(&if_else.cond.span),733 || "if condition".to_owned(),734 || bool::from_untyped(evaluate(ctx.clone(), &if_else.cond.cond)?),735 )? {736 evaluate(ctx, &if_else.cond_then)?737 } else {738 match &if_else.cond_else {739 Some(v) => evaluate(ctx, v)?,740 None => Val::Null,741 }742 }743 }744 Slice(slice) => {745 fn parse_idx<T: Typed + FromUntyped>(746 ctx: Context,747 expr: Option<&Spanned<Expr>>,748 desc: &'static str,749 ) -> Result<Option<T>> {750 if let Some(value) = expr {751 Ok(in_frame(752 CallLocation::new(&value.span),753 || format!("slice {desc}"),754 || <Option<T>>::from_untyped(evaluate(ctx, value)?),755 )?)756 } else {757 Ok(None)758 }759 }760761 let indexable = evaluate(ctx.clone(), &slice.value)?;762763 let start = parse_idx(ctx.clone(), slice.slice.start.as_ref(), "start")?;764 let end = parse_idx(ctx.clone(), slice.slice.end.as_ref(), "end")?;765 let step = parse_idx(ctx, slice.slice.step.as_ref(), "step")?;766767 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?768 }769 Import(kind, path) => {770 let Expr::Str(path) = &**path else {771 bail!("computed imports are not supported")772 };773 with_state(|s| {774 let span = &kind.span;775 let resolved_path = s.resolve_from(span.0.source_path(), path)?;776 Ok(match &**kind {777 ImportKind::Normal => in_frame(778 CallLocation::new(span),779 || format!("import {:?}", path.clone()),780 || s.import_resolved(resolved_path),781 )?,782 ImportKind::Str => Val::string(s.import_resolved_str(resolved_path)?),783 ImportKind::Bin => Val::arr(s.import_resolved_bin(resolved_path)?),784 }) as Result<Val>785 })?786 }787 })788}1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_ir::{6 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprParams, FieldMember,7 FieldName, ForSpecData, IfSpecData, ImportKind, LiteralType, ObjBody, ObjMembers, Spanned,8 function::ParamName,9};10use jrsonnet_types::ValType;1112use self::destructure::destruct;13use crate::{14 Context, ContextBuilder, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,15 ResultExt, SupThis, Unbound, Val,16 arr::ArrValue,17 bail,18 destructure::evaluate_dest,19 error::{ErrorKind::*, suggest_object_fields},20 evaluate::operator::{evaluate_binary_op_special, evaluate_unary_op},21 function::{CallLocation, FuncDesc, FuncVal, PreparedFuncVal},22 in_frame,23 typed::{FromUntyped, IntoUntyped as _, Typed},24 val::{CachedUnbound, IndexableVal, StrValue, Thunk},25 with_state,26};27pub mod destructure;28pub mod operator;2930// This is the amount of bytes that need to be left on the stack before increasing the size.31// It must be at least as large as the stack required by any code that does not call32// `ensure_sufficient_stack`.33const RED_ZONE: usize = 100 * 1024; // 100k3435// Only the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then36// on. This flag has performance relevant characteristics. Don't set it too high.37const STACK_PER_RECURSION: usize = 1024 * 1024; // 1MB3839/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations40/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit41/// from this.42///43/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.44#[inline]45pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {46 stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)47}4849pub fn evaluate_trivial(expr: &Expr) -> Option<Val> {50 fn is_trivial(expr: &Expr) -> bool {51 match expr {52 Expr::Str(_)53 | Expr::Num(_)54 | Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,55 Expr::Arr(a) => a.iter().all(is_trivial),56 _ => false,57 }58 }59 Some(match expr {60 Expr::Str(s) => Val::string(s.clone()),61 Expr::Num(n) => Val::Num(*n),62 Expr::Literal(LiteralType::False) => Val::Bool(false),63 Expr::Literal(LiteralType::True) => Val::Bool(true),64 Expr::Literal(LiteralType::Null) => Val::Null,65 Expr::Arr(n) => {66 if n.iter().any(|e| !is_trivial(e)) {67 return None;68 }69 Val::Arr(70 n.iter()71 .map(evaluate_trivial)72 .map(|e| e.expect("checked trivial"))73 .collect(),74 )75 }76 _ => return None,77 })78}7980pub fn evaluate_method(ctx: Context, name: IStr, params: ExprParams, body: Rc<Expr>) -> Val {81 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {82 name,83 ctx,84 params,85 body,86 })))87}8889pub fn evaluate_field_name(ctx: Context, field_name: &Spanned<FieldName>) -> Result<Option<IStr>> {90 Ok(match &field_name.value {91 FieldName::Fixed(n) => Some(n.clone()),92 FieldName::Dyn(expr) => in_frame(93 CallLocation::new(&field_name.span),94 || "evaluating field name".to_string(),95 || {96 let v = evaluate(ctx, expr)?;97 Ok(if matches!(v, Val::Null) {98 None99 } else {100 Some(IStr::from_untyped(v)?)101 })102 },103 )?,104 })105}106107pub fn evaluate_comp(108 ctx: Context,109 specs: &[CompSpec],110 mut guaranteed_reserve: usize,111 callback: &mut impl FnMut(Context, usize) -> Result<()>,112) -> Result<()> {113 match specs.first() {114 None => callback(ctx, guaranteed_reserve)?,115 Some(CompSpec::IfSpec(IfSpecData { cond, span: _ })) => {116 if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {117 evaluate_comp(ctx, &specs[1..], 0, callback)?;118 }119 }120 Some(CompSpec::ForSpec(ForSpecData {121 destruct: into,122 over,123 })) => {124 match evaluate(ctx.clone(), over)? {125 Val::Arr(list) => {126 guaranteed_reserve = guaranteed_reserve.max(1) * list.len();127 for (i, item) in list.iter_lazy().enumerate() {128 let fctx = Pending::new();129 let mut ctx = ContextBuilder::extend_fast(ctx.clone());130 destruct(into, item, fctx.clone(), &mut ctx)?;131 let ctx = ctx.build().into_future(fctx);132133 let specs = &specs[1..];134 evaluate_comp(135 ctx,136 specs,137 if i == 0 || !specs.is_empty() {138 guaranteed_reserve139 } else {140 0141 },142 callback,143 )?;144 }145 }146 Val::Obj(obj) if cfg!(feature = "exp-object-iteration") => {147 let fields = obj.fields(148 // TODO: Should there be ability to preserve iteration order?149 #[cfg(feature = "exp-preserve-order")]150 false,151 );152 guaranteed_reserve = guaranteed_reserve.max(1) * fields.len();153 for (i, field) in fields.into_iter().enumerate() {154 let fctx = Pending::new();155 let mut ctx = ContextBuilder::extend_fast(ctx.clone());156 let obj = obj.clone();157 let value = Thunk::evaluated(Val::arr(vec![158 Thunk::evaluated(Val::string(field.clone())),159 obj.get_lazy(field).expect(160 "field exists, as field name was obtained from object.fields()",161 ),162 ]));163 destruct(into, value, fctx.clone(), &mut ctx)?;164 let ctx = ctx.build().into_future(fctx);165166 evaluate_comp(167 ctx,168 &specs[1..],169 if i == 0 || !specs.is_empty() {170 guaranteed_reserve171 } else {172 0173 },174 callback,175 )?;176 }177 }178 _ => bail!(InComprehensionCanOnlyIterateOverArray),179 }180 }181 }182 Ok(())183}184185fn evaluate_arr_comp(ctx: Context, expr: &Rc<Expr>, comp_specs: &[CompSpec]) -> Result<ArrValue> {186 let ctx = ctx.branch_point();187 'eager: {188 let mut out = Vec::new();189190 if evaluate_comp(ctx.clone(), comp_specs, 0, &mut |ctx, reserve| {191 if reserve != 0 {192 out.reserve(reserve);193 }194 out.push(evaluate(ctx, expr)?);195 Ok(())196 })197 .is_err()198 {199 break 'eager;200 }201202 return Ok(ArrValue::new(out));203 };204 let mut out = Vec::new();205 evaluate_comp(ctx, comp_specs, 0, &mut |ctx, reserve| {206 if reserve != 0 {207 out.reserve(reserve);208 }209 let expr = expr.clone();210 out.push(Thunk!(move || evaluate(ctx, &expr)));211 Ok(())212 })?;213 Ok(ArrValue::new(out))214}215216trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}217impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}218219fn evaluate_object_locals(220 fctx: Context,221 locals: Rc<Vec<BindSpec>>,222) -> impl CloneableUnbound<Context> {223 #[derive(Trace, Clone)]224 struct UnboundLocals {225 fctx: Context,226 locals: Rc<Vec<BindSpec>>,227 }228 impl Unbound for UnboundLocals {229 type Bound = Context;230231 fn bind(&self, sup_this: SupThis) -> Result<Context> {232 let fctx = Context::new_future();233 let ctx = self.fctx.clone();234 let mut ctx = ContextBuilder::extend(ctx);235 for b in self.locals.iter() {236 evaluate_dest(b, fctx.clone(), &mut ctx)?;237 }238239 let ctx = ctx.build_sup_this(sup_this).into_future(fctx);240241 Ok(ctx)242 }243 }244245 UnboundLocals { fctx, locals }246}247248pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(249 builder: &mut ObjValueBuilder,250 ctx: Context,251 uctx: B,252 field: &FieldMember,253) -> Result<()> {254 let name = evaluate_field_name(ctx, &field.name)?;255 let Some(name) = name else {256 return Ok(());257 };258259 match field {260 FieldMember {261 plus,262 params: None,263 visibility,264 value,265 ..266 } => {267 #[derive(Trace)]268 struct UnboundValue<B: Trace> {269 uctx: B,270 value: Rc<Expr>,271 name: IStr,272 }273 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {274 type Bound = Val;275 fn bind(&self, sup_this: SupThis) -> Result<Val> {276 evaluate_named(self.uctx.bind(sup_this)?, &self.value, self.name.clone())277 }278 }279280 builder281 .field(name.clone())282 .with_add(*plus)283 .with_visibility(*visibility)284 .with_location(field.name.span.clone())285 .bindable(UnboundValue {286 uctx,287 value: value.clone(),288 name,289 })?;290 }291 FieldMember {292 params: Some(params),293 visibility,294 value,295 ..296 } => {297 #[derive(Trace)]298 struct UnboundMethod<B: Trace> {299 uctx: B,300 value: Rc<Expr>,301 params: ExprParams,302 name: IStr,303 }304 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {305 type Bound = Val;306 fn bind(&self, sup_this: SupThis) -> Result<Val> {307 Ok(evaluate_method(308 self.uctx.bind(sup_this)?,309 self.name.clone(),310 self.params.clone(),311 self.value.clone(),312 ))313 }314 }315316 builder317 .field(name.clone())318 .with_visibility(*visibility)319 // .with_location(value.span())320 .bindable(UnboundMethod {321 uctx,322 value: value.clone(),323 params: params.clone(),324 name,325 })?;326 }327 }328 Ok(())329}330331#[derive(Trace, Clone)]332struct DirectUnbound(Context);333impl Unbound for DirectUnbound {334 type Bound = Context;335 fn bind(&self, sup_this: SupThis) -> Result<Context> {336 Ok(ContextBuilder::extend(self.0.clone()).build_sup_this(sup_this))337 }338}339340#[allow(clippy::too_many_lines)]341pub fn evaluate_member_list_object(342 super_obj: Option<ObjValue>,343 ctx: Context,344 members: &ObjMembers,345) -> Result<ObjValue> {346 #[derive(Trace)]347 struct ObjectAssert<B: Trace> {348 uctx: B,349 asserts: Rc<Vec<AssertStmt>>,350 }351 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {352 fn run(&self, sup_this: SupThis) -> Result<()> {353 let ctx = self.uctx.bind(sup_this)?;354 for assert in &*self.asserts {355 evaluate_assert(ctx.clone(), assert)?;356 }357 Ok(())358 }359 }360361 let mut builder = ObjValueBuilder::new();362 if let Some(super_obj) = super_obj {363 builder.with_super(super_obj);364 }365366 if members.locals.is_empty() {367 // We can use the same context for all field evaluation, it doesn't depends on locals, only on this/super368 let uctx = DirectUnbound(ctx.clone());369 for field in &members.fields {370 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;371 }372 if !members.asserts.is_empty() {373 builder.assert(ObjectAssert {374 uctx,375 asserts: members.asserts.clone(),376 });377 }378 } else {379 let locals = members.locals.clone();380 // We have single context for all fields, so we can cache them together381 let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));382 for field in &members.fields {383 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;384 }385 if !members.asserts.is_empty() {386 builder.assert(ObjectAssert {387 uctx,388 asserts: members.asserts.clone(),389 });390 }391 }392393 Ok(builder.build())394}395396pub fn evaluate_object(397 super_obj: Option<ObjValue>,398 ctx: Context,399 object: &ObjBody,400) -> Result<ObjValue> {401 Ok(match object {402 ObjBody::MemberList(members) => evaluate_member_list_object(super_obj, ctx, members)?,403 ObjBody::ObjComp(obj) => {404 let mut builder = ObjValueBuilder::new();405 if let Some(super_obj) = super_obj {406 builder.with_super(super_obj);407 }408 let locals = obj.locals.clone();409 evaluate_comp(410 ctx.branch_point(),411 &obj.compspecs,412 0,413 &mut |ctx, reserve| {414 let uctx = evaluate_object_locals(ctx.clone(), locals.clone());415 builder.reserve_fields(reserve);416417 evaluate_field_member(&mut builder, ctx, uctx, &obj.field)418 },419 )?;420421 builder.build()422 }423 })424}425426pub fn evaluate_apply(427 ctx: Context,428 value: &Expr,429 args: &ArgsDesc,430 loc: CallLocation<'_>,431 tailstrict: bool,432) -> Result<Val> {433 let value = evaluate(ctx.clone(), value)?;434 Ok(match value {435 Val::Func(f) => {436 let name = f.name();437 let unnamed = args438 .unnamed439 .iter()440 .cloned()441 .map(|un| evaluate_thunk(ctx.clone(), un, tailstrict))442 .collect::<Result<Vec<_>>>()?;443 let named = args444 .values445 .iter()446 .cloned()447 .map(|un| evaluate_thunk(ctx.clone(), un, tailstrict))448 .collect::<Result<Vec<_>>>()?;449 let prepare = PreparedFuncVal::new(f, args.unnamed.len(), &args.names)450 .with_description_src(loc, || format!("function <{name}> call"))?;451 let body = || prepare.call(loc, &unnamed, &named);452 if tailstrict {453 body()?454 } else {455 in_frame(loc, || format!("function <{name}> call"), body)?456 }457 }458 v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),459 })460}461462pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {463 let AssertStmt { assertion, message } = assertion;464 let assertion_result = in_frame(465 CallLocation::new(&assertion.span),466 || "assertion condition".to_owned(),467 || bool::from_untyped(evaluate(ctx.clone(), assertion)?),468 )?;469 if !assertion_result {470 in_frame(471 CallLocation::new(&assertion.span),472 || "assertion failure".to_owned(),473 || {474 if let Some(msg) = message {475 bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));476 }477 bail!(AssertionFailed(Val::Null.to_string()?));478 },479 )?;480 }481 Ok(())482}483484pub fn evaluate_named_param(ctx: Context, expr: &Expr, name: ParamName) -> Result<Val> {485 match name {486 ParamName::Named(name) => evaluate_named(ctx, expr, name),487 ParamName::Unnamed => evaluate(ctx, expr),488 }489}490491pub fn evaluate_named(ctx: Context, expr: &Expr, name: IStr) -> Result<Val> {492 use Expr::*;493 Ok(match expr {494 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),495 _ => evaluate(ctx, expr)?,496 })497}498499pub fn evaluate_thunk(ctx: Context, expr: Rc<Expr>, tailstrict: bool) -> Result<Thunk<Val>> {500 Ok(if tailstrict {501 Thunk::evaluated(evaluate(ctx, &expr)?)502 } else {503 Thunk!(move || { evaluate(ctx, &expr) })504 })505}506#[allow(clippy::too_many_lines)]507pub fn evaluate(ctx: Context, expr: &Expr) -> Result<Val> {508 use Expr::*;509510 Ok(match expr {511 Literal(LiteralType::This) => Val::Obj(ctx.try_this()?),512 Literal(LiteralType::Super) => Val::Obj(ctx.try_sup_this()?.standalone_super()?),513 Literal(LiteralType::Dollar) => Val::Obj(ctx.try_dollar()?),514 Literal(LiteralType::True) => Val::Bool(true),515 Literal(LiteralType::False) => Val::Bool(false),516 Literal(LiteralType::Null) => Val::Null,517 Str(v) => Val::string(v.clone()),518 Num(v) => Val::try_num(*v)?,519 // I have tried to remove special behavior from super by implementing standalone-super520 // expresion, but looks like this case still needs special treatment.521 //522 // Note that other jsonnet implementations will fail on `if value in (super)` expression,523 // because the standalone super literal is not supported, that is because in other524 // implementations `in super` treated differently from `in smth_else`.525 BinaryOp(bin)526 if matches!(&bin.rhs, Expr::Literal(LiteralType::Super))527 && bin.op == BinaryOpType::In =>528 {529 let sup_this = ctx.try_sup_this()?;530 // In jsonnet, "field" in e is eager, LHS expression is always executed regardless of super existence.531 // In jrsonnet, however, this wasn't true, this was kept here for compatibility.532 if !sup_this.has_super() {533 return Ok(Val::Bool(false));534 }535 let field = evaluate(ctx, &bin.lhs)?;536 Val::Bool(sup_this.field_in_super(field.to_string()?))537 }538 BinaryOp(bin) => evaluate_binary_op_special(ctx, &bin.lhs, bin.op, &bin.rhs)?,539 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,540 Var(name) => in_frame(541 CallLocation::new(&name.span),542 || format!("local <{}> access", &**name),543 || ctx.binding((**name).clone())?.evaluate(),544 )?,545 Index { indexable, parts } => ensure_sufficient_stack(|| {546 let mut parts = parts.iter();547 let mut indexable = if matches!(&**indexable, Expr::Literal(LiteralType::Super)) {548 let part = parts.next().expect("at least part should exist");549 // sup_this existence check might also be skipped here for null-coalesce...550 // But I believe this might cause errors.551 let sup_this = ctx.try_sup_this()?;552 if !sup_this.has_super() {553 #[cfg(feature = "exp-null-coaelse")]554 if part.null_coaelse {555 return Ok(Val::Null);556 }557 bail!(NoSuperFound)558 }559 let name = evaluate(ctx.clone(), &part.value)?;560561 let Val::Str(name) = name else {562 bail!(ValueIndexMustBeTypeGot(563 ValType::Obj,564 ValType::Str,565 name.value_type(),566 ))567 };568569 let name = name.into_flat();570 match sup_this571 .get_super(name.clone())572 .with_description_src(&part.span, || format!("field <{name}> access"))?573 {574 Some(v) => v,575 #[cfg(feature = "exp-null-coaelse")]576 None if part.null_coaelse => return Ok(Val::Null),577 None => {578 let suggestions = suggest_object_fields(579 &sup_this.standalone_super().expect("super exists"),580 name.clone(),581 );582583 bail!(NoSuchField(name, suggestions))584 }585 }586 } else {587 evaluate(ctx.clone(), indexable)?588 };589590 for part in parts {591 indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {592 (Val::Obj(v), Val::Str(key)) => match v593 .get(key.clone().into_flat())594 .with_description_src(&part.span, || format!("field <{key}> access"))?595 {596 Some(v) => v,597 #[cfg(feature = "exp-null-coaelse")]598 None if part.null_coaelse => return Ok(Val::Null),599 None => {600 let suggestions = suggest_object_fields(&v, key.into_flat());601602 return Err(Error::from(NoSuchField(603 key.clone().into_flat(),604 suggestions,605 )))606 .with_description_src(&part.span, || format!("field <{key}> access"));607 }608 },609 (Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(610 ValType::Obj,611 ValType::Str,612 n.value_type(),613 )),614 (Val::Arr(v), Val::Num(n)) => {615 let n = n.get();616 if n.fract() > f64::EPSILON {617 bail!(FractionalIndex)618 }619 if n < 0.0 {620 #[expect(621 clippy::cast_possible_truncation,622 reason = "it would be truncated anyway"623 )]624 let n = n as isize;625 bail!(ArrayBoundsError(n, v.len()));626 }627 #[expect(628 clippy::cast_possible_truncation,629 clippy::cast_sign_loss,630 reason = "n is checked postive"631 )]632 v.get(n as usize)?633 .ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?634 }635 (Val::Arr(_), Val::Str(n)) => {636 bail!(AttemptedIndexAnArrayWithString(n.into_flat()))637 }638 (Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(639 ValType::Arr,640 ValType::Num,641 n.value_type(),642 )),643644 (Val::Str(s), Val::Num(n)) => Val::Str({645 let n = n.get();646 if n.fract() > f64::EPSILON {647 bail!(FractionalIndex)648 }649 if n < 0.0 {650 #[expect(651 clippy::cast_possible_truncation,652 reason = "it would be truncated anyway"653 )]654 let n = n as isize;655 bail!(ArrayBoundsError(n, s.into_flat().chars().count()));656 }657 #[expect(658 clippy::cast_sign_loss,659 clippy::cast_possible_truncation,660 reason = "n is positive, overflow will truncate as expected"661 )]662 let n = n as usize;663 let v: IStr = s664 .clone()665 .into_flat()666 .chars()667 .skip(n)668 .take(1)669 .collect::<String>()670 .into();671 if v.is_empty() {672 bail!(StringBoundsError(n, s.into_flat().chars().count()))673 }674 StrValue::Flat(v)675 }),676 (Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(677 ValType::Str,678 ValType::Num,679 n.value_type(),680 )),681 #[cfg(feature = "exp-null-coaelse")]682 (Val::Null, _) if part.null_coaelse => return Ok(Val::Null),683 (v, _) => bail!(CantIndexInto(v.value_type())),684 };685 }686 Ok(indexable)687 })?,688 LocalExpr(bindings, returned) => {689 let fctx = Context::new_future();690 let mut ctx = ContextBuilder::extend(ctx);691 for b in bindings {692 evaluate_dest(b, fctx.clone(), &mut ctx)?;693 }694 let ctx = ctx.build().into_future(fctx);695 evaluate(ctx, returned)?696 }697 Arr(items) => {698 if items.is_empty() {699 Val::arr(())700 } else {701 Val::Arr(ArrValue::expr(ctx, items.clone()))702 }703 }704 ArrComp(expr, comp_specs) => Val::Arr(evaluate_arr_comp(ctx, expr, comp_specs)?),705 Obj(body) => Val::Obj(evaluate_object(None, ctx, body)?),706 ObjExtend(a, b) => {707 let base = evaluate(ctx.clone(), a)?;708 match base {709 Val::Obj(base_obj) => Val::Obj(evaluate_object(Some(base_obj), ctx, b)?),710 _ => bail!("ObjExtend lhs should be an object value"),711 }712 }713 Apply(value, args, tailstrict) => ensure_sufficient_stack(|| {714 evaluate_apply(ctx, value, args, CallLocation::new(&args.span), *tailstrict)715 })?,716 Function(params, body) => {717 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())718 }719 AssertExpr(assert) => {720 evaluate_assert(ctx.clone(), &assert.assert)?;721 evaluate(ctx, &assert.rest)?722 }723 ErrorStmt(s, e) => in_frame(724 CallLocation::new(s),725 || "error statement".to_owned(),726 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),727 )?,728 IfElse(if_else) => {729 if in_frame(730 CallLocation::new(&if_else.cond.span),731 || "if condition".to_owned(),732 || bool::from_untyped(evaluate(ctx.clone(), &if_else.cond.cond)?),733 )? {734 evaluate(ctx, &if_else.cond_then)?735 } else {736 match &if_else.cond_else {737 Some(v) => evaluate(ctx, v)?,738 None => Val::Null,739 }740 }741 }742 Slice(slice) => {743 fn parse_idx<T: Typed + FromUntyped>(744 ctx: Context,745 expr: Option<&Spanned<Expr>>,746 desc: &'static str,747 ) -> Result<Option<T>> {748 if let Some(value) = expr {749 Ok(in_frame(750 CallLocation::new(&value.span),751 || format!("slice {desc}"),752 || <Option<T>>::from_untyped(evaluate(ctx, value)?),753 )?)754 } else {755 Ok(None)756 }757 }758759 let indexable = evaluate(ctx.clone(), &slice.value)?;760761 let start = parse_idx(ctx.clone(), slice.slice.start.as_ref(), "start")?;762 let end = parse_idx(ctx.clone(), slice.slice.end.as_ref(), "end")?;763 let step = parse_idx(ctx, slice.slice.step.as_ref(), "step")?;764765 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?766 }767 Import(kind, path) => {768 let Expr::Str(path) = &**path else {769 bail!("computed imports are not supported")770 };771 with_state(|s| {772 let span = &kind.span;773 let resolved_path = s.resolve_from(span.0.source_path(), path)?;774 Ok(match &**kind {775 ImportKind::Normal => in_frame(776 CallLocation::new(span),777 || format!("import {:?}", path.clone()),778 || s.import_resolved(resolved_path),779 )?,780 ImportKind::Str => Val::string(s.import_resolved_str(resolved_path)?),781 ImportKind::Bin => Val::arr(s.import_resolved_bin(resolved_path)?),782 }) as Result<Val>783 })?784 }785 })786}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]