difftreelog
refactor greately simplify object self/super implementation
in: master
18 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -310,6 +310,18 @@
checksum = "9bda8e21c04aca2ae33ffc2fd8c23134f3cac46db123ba97bd9d3f3b8a4a85e1"
[[package]]
+name = "educe"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d7bc049e1bd8cdeb31b68bbd586a9464ecf9f3944af3958a7a9d0f8b9799417"
+dependencies = [
+ "enum-ordinalize",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
name = "either"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -340,6 +352,26 @@
]
[[package]]
+name = "enum-ordinalize"
+version = "4.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a1091a7bb1f8f2c4b28f1fe2cef4980ca2d410a3d727d67ecc3178c9b0800f0"
+dependencies = [
+ "enum-ordinalize-derive",
+]
+
+[[package]]
+name = "enum-ordinalize-derive"
+version = "4.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ca9601fb2d62598ee17836250842873a413586e5d7ed88b356e38ddbb0ec631"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -576,6 +608,7 @@
dependencies = [
"annotate-snippets",
"anyhow",
+ "educe",
"hi-doc",
"jrsonnet-gcmodule",
"jrsonnet-interner",
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -57,6 +57,7 @@
num-bigint = { workspace = true, features = ["serde"], optional = true }
stacker = "0.1.23"
+educe = { version = "0.6.0", default-features = false, features = ["Clone", "Debug", "Eq", "Hash", "PartialEq"] }
[build-dependencies]
rustversion = "1.0.22"
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -1,32 +1,27 @@
use std::fmt::Debug;
+use educe::Educe;
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
use rustc_hash::FxHashMap;
use crate::{
error::ErrorKind::*, gc::WithCapacityExt as _, map::LayeredHashMap, ObjValue, Pending, Result,
- Thunk, Val,
+ SupThis, Thunk, Val,
};
+/// Context keeps information about current lexical code location
+///
+/// This information includes local variables, top-level object (`$`), current object (`this`), and super object (`super`)
+#[derive(Debug, Trace, Clone, Educe)]
+#[educe(PartialEq)]
+pub struct Context(#[educe(PartialEq(method = Cc::ptr_eq))] Cc<ContextInternal>);
-#[derive(Trace)]
-struct ContextInternals {
+#[derive(Debug, Trace)]
+struct ContextInternal {
dollar: Option<ObjValue>,
- sup: Option<ObjValue>,
- this: Option<ObjValue>,
+ sup_this: Option<SupThis>,
bindings: LayeredHashMap,
-}
-impl Debug for ContextInternals {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("Context").finish()
- }
}
-
-/// Context keeps information about current lexical code location
-///
-/// This information includes local variables, top-level object (`$`), current object (`this`), and super object (`super`)
-#[derive(Debug, Clone, Trace)]
-pub struct Context(Cc<ContextInternals>);
impl Context {
pub fn new_future() -> Pending<Self> {
Pending::new()
@@ -36,12 +31,35 @@
self.0.dollar.as_ref()
}
+ pub fn try_dollar(&self) -> Result<ObjValue> {
+ self.0
+ .dollar
+ .clone()
+ .ok_or_else(|| CantUseSelfSupOutsideOfObject.into())
+ }
+
pub fn this(&self) -> Option<&ObjValue> {
- self.0.this.as_ref()
+ self.0.sup_this.as_ref().map(SupThis::this)
+ }
+
+ pub fn try_this(&self) -> Result<ObjValue> {
+ self.0
+ .sup_this
+ .as_ref()
+ .ok_or_else(|| CantUseSelfSupOutsideOfObject.into())
+ .map(SupThis::this)
+ .cloned()
+ }
+
+ pub fn sup_this(&self) -> Option<&SupThis> {
+ self.0.sup_this.as_ref()
}
- pub fn super_obj(&self) -> Option<&ObjValue> {
- self.0.sup.as_ref()
+ pub fn try_sup_this(&self) -> Result<SupThis> {
+ self.0
+ .sup_this
+ .clone()
+ .ok_or_else(|| CantUseSelfSupOutsideOfObject.into())
}
pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {
@@ -83,41 +101,52 @@
pub fn with_var(self, name: impl Into<IStr>, value: Val) -> Self {
let mut new_bindings = FxHashMap::with_capacity(1);
new_bindings.insert(name.into(), Thunk::evaluated(value));
- self.extend(new_bindings, None, None, None)
+ self.extend_bindings(new_bindings)
}
#[must_use]
- pub fn extend(
+ pub fn extend_bindings_sup_this(
self,
new_bindings: FxHashMap<IStr, Thunk<Val>>,
- new_dollar: Option<ObjValue>,
- new_sup: Option<ObjValue>,
- new_this: Option<ObjValue>,
+ sup_this: SupThis,
) -> Self {
- let ctx = &self.0;
- let dollar = new_dollar.or_else(|| ctx.dollar.clone());
- let this = new_this.or_else(|| ctx.this.clone());
- let sup = new_sup.or_else(|| ctx.sup.clone());
+ let ctx = &self;
+ let dollar = ctx
+ .0
+ .dollar
+ .clone()
+ .or_else(|| Some(sup_this.this().clone()));
let bindings = if new_bindings.is_empty() {
- ctx.bindings.clone()
+ ctx.0.bindings.clone()
} else {
- ctx.bindings.clone().extend(new_bindings)
+ ctx.0.bindings.clone().extend(new_bindings)
};
- Self(Cc::new(ContextInternals {
+ Self(Cc::new(ContextInternal {
dollar,
- sup,
- this,
+ sup_this: Some(sup_this),
bindings,
}))
}
-}
-
-impl PartialEq for Context {
- fn eq(&self, other: &Self) -> bool {
- Cc::ptr_eq(&self.0, &other.0)
+ #[must_use]
+ pub fn extend_bindings(self, new_bindings: FxHashMap<IStr, Thunk<Val>>) -> Self {
+ if new_bindings.is_empty() {
+ return self;
+ }
+ let ctx = &self;
+ let bindings = if new_bindings.is_empty() {
+ ctx.0.bindings.clone()
+ } else {
+ ctx.0.bindings.clone().extend(new_bindings)
+ };
+ Self(Cc::new(ContextInternal {
+ dollar: ctx.0.dollar.clone(),
+ sup_this: ctx.0.sup_this.clone(),
+ bindings,
+ }))
}
}
+#[derive(Default)]
pub struct ContextBuilder {
bindings: FxHashMap<IStr, Thunk<Val>>,
extend: Option<Context>,
@@ -127,20 +156,25 @@
pub fn new() -> Self {
Self::with_capacity(0)
}
+
pub fn with_capacity(capacity: usize) -> Self {
Self {
bindings: FxHashMap::with_capacity(capacity),
extend: None,
}
}
+
pub fn extend(parent: Context) -> Self {
Self {
bindings: FxHashMap::new(),
extend: Some(parent),
}
}
+
/// # Panics
- /// If `name` is already bound
+ ///
+ /// If `name` is already bound. Makes no sense to bind same local multiple times,
+ /// unless it is separate context layers.
pub fn bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) -> &mut Self {
let old = self.bindings.insert(name.into(), value);
assert!(old.is_none(), "variable bound twice in single context call");
@@ -148,14 +182,12 @@
}
pub fn build(self) -> Context {
if let Some(parent) = self.extend {
- // TODO: replace self.extend with Result<Context, State>, and remove `state` field
- parent.extend(self.bindings, None, None, None)
+ parent.extend_bindings(self.bindings)
} else {
- Context(Cc::new(ContextInternals {
+ Context(Cc::new(ContextInternal {
bindings: LayeredHashMap::new(self.bindings),
dollar: None,
- sup: None,
- this: None,
+ sup_this: None,
}))
}
}
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -1,11 +1,13 @@
-use std::cell::OnceCell;
+use std::ptr::addr_of;
+use std::{cell::OnceCell, hash::Hasher};
+use educe::Educe;
use jrsonnet_gcmodule::{Cc, Trace};
use crate::{bail, error::ErrorKind::InfiniteRecursionDetected, val::ThunkValue, Result};
-// TODO: Replace with OnceCell once in std
-#[derive(Clone, Trace)]
+#[derive(Trace, Educe)]
+#[educe(Clone)]
pub struct Pending<V: Trace + 'static>(pub Cc<OnceCell<V>>);
impl<T: Trace + 'static> Pending<T> {
pub fn new() -> Self {
@@ -25,7 +27,7 @@
.expect("wrapper is filled already");
}
}
-impl<T: Clone + Trace + 'static> Pending<T> {
+impl<T: Trace + 'static + Clone> Pending<T> {
/// # Panics
/// If wrapper is not yet filled
pub fn unwrap(&self) -> T {
@@ -52,3 +54,7 @@
Self::new()
}
}
+
+pub fn identity_hash<T, H: Hasher>(v: &Cc<T>, hasher: &mut H) {
+ hasher.write_usize(addr_of!(**v) as usize);
+}
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -119,10 +119,8 @@
#[error("binary operation {1} {0} {2} is not implemented")]
BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),
- #[error("no top level object in this context")]
- NoTopLevelObjectFound,
- #[error("self is only usable inside objects")]
- CantUseSelfOutsideOfObject,
+ #[error("self/super/$ are only usable inside objects")]
+ CantUseSelfSupOutsideOfObject,
#[error("no super found")]
NoSuperFound,
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -11,18 +11,7 @@
use self::destructure::destruct;
use crate::{
- arr::ArrValue,
- bail,
- destructure::evaluate_dest,
- error::{suggest_object_fields, ErrorKind::*},
- evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
- function::{CallLocation, FuncDesc, FuncVal},
- gc::WithCapacityExt as _,
- in_frame,
- typed::Typed,
- val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
- Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt,
- Unbound, Val,
+ Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt, SupThis, Unbound, Val, arr::ArrValue, bail, destructure::evaluate_dest, error::{ErrorKind::*, suggest_object_fields}, evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op}, function::{CallLocation, FuncDesc, FuncVal}, gc::WithCapacityExt as _, in_frame, typed::Typed, val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk}, with_state
};
pub mod destructure;
pub mod operator;
@@ -126,10 +115,7 @@
let fctx = Pending::new();
let mut new_bindings = FxHashMap::with_capacity(var.capacity_hint());
destruct(var, item, fctx.clone(), &mut new_bindings)?;
- let ctx = ctx
- .clone()
- .extend(new_bindings, None, None, None)
- .into_future(fctx);
+ let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);
evaluate_comp(ctx, &specs[1..], callback)?;
}
@@ -169,18 +155,18 @@
impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}
fn evaluate_object_locals(
- fctx: Pending<Context>,
+ fctx: Context,
locals: Rc<Vec<BindSpec>>,
) -> impl CloneableUnbound<Context> {
#[derive(Trace, Clone)]
struct UnboundLocals {
- fctx: Pending<Context>,
+ fctx: Context,
locals: Rc<Vec<BindSpec>>,
}
impl Unbound for UnboundLocals {
type Bound = Context;
- fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {
+ fn bind(&self, sup_this: SupThis) -> Result<Context> {
let fctx = Context::new_future();
let mut new_bindings =
FxHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());
@@ -188,11 +174,10 @@
evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
}
- let ctx = self.fctx.unwrap();
- let new_dollar = ctx.dollar().cloned().or_else(|| this.clone());
+ let ctx = self.fctx.clone();
let ctx = ctx
- .extend(new_bindings, new_dollar, sup, this)
+ .extend_bindings_sup_this(new_bindings, sup_this)
.into_future(fctx);
Ok(ctx)
@@ -229,8 +214,8 @@
}
impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {
type Bound = Val;
- fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {
- evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())
+ fn bind(&self, sup_this: SupThis) -> Result<Val> {
+ evaluate_named(self.uctx.bind(sup_this)?, &self.value, self.name.clone())
}
}
@@ -260,9 +245,9 @@
}
impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {
type Bound = Val;
- fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {
+ fn bind(&self, sup_this: SupThis) -> Result<Val> {
Ok(evaluate_method(
- self.uctx.bind(sup, this)?,
+ self.uctx.bind(sup_this)?,
self.name.clone(),
self.params.clone(),
self.value.clone(),
@@ -298,10 +283,8 @@
.collect::<Vec<_>>(),
);
- let fctx = Context::new_future();
-
// We have single context for all fields, so we can cache binds
- let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));
+ let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));
for member in members {
match member {
@@ -315,8 +298,8 @@
assert: AssertStmt,
}
impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {
- fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {
- let ctx = self.uctx.bind(sup, this)?;
+ fn run(&self, sup_this: SupThis) -> Result<()> {
+ let ctx = self.uctx.bind(sup_this)?;
evaluate_assert(ctx, &self.assert)
}
}
@@ -330,9 +313,7 @@
}
}
}
- let this = builder.build();
- fctx.fill(ctx.extend(FxHashMap::new(), None, None, Some(this.clone())));
- Ok(this)
+ Ok(builder.build())
}
pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {
@@ -347,22 +328,13 @@
.cloned()
.collect::<Vec<_>>(),
);
- let mut ctxs = vec![];
evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {
- let fctx = Context::new_future();
- ctxs.push((ctx.clone(), fctx.clone()));
- let uctx = evaluate_object_locals(fctx, locals.clone());
+ let uctx = evaluate_object_locals(ctx.clone(), locals.clone());
evaluate_field_member(&mut builder, ctx, uctx, &obj.field)
})?;
- let this = builder.build();
- for (ctx, fctx) in ctxs {
- let _ctx = ctx
- .extend(FxHashMap::new(), None, None, Some(this.clone()))
- .into_future(fctx);
- }
- this
+ builder.build()
}
})
}
@@ -428,19 +400,9 @@
}
let loc = expr.span();
Ok(match expr.expr() {
- Literal(LiteralType::This) => {
- Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())
- }
- Literal(LiteralType::Super) => Val::Obj(
- ctx.super_obj().ok_or(NoSuperFound)?.with_this(
- ctx.this()
- .expect("if super exists - then this should too")
- .clone(),
- ),
- ),
- Literal(LiteralType::Dollar) => {
- Val::Obj(ctx.dollar().ok_or(NoTopLevelObjectFound)?.clone())
- }
+ Literal(LiteralType::This) => Val::Obj(ctx.try_this()?),
+ Literal(LiteralType::Super) => Val::Obj(ctx.try_sup_this()?.standalone_super()?),
+ Literal(LiteralType::Dollar) => Val::Obj(ctx.try_dollar()?),
Literal(LiteralType::True) => Val::Bool(true),
Literal(LiteralType::False) => Val::Bool(false),
Literal(LiteralType::Null) => Val::Null,
@@ -452,15 +414,18 @@
//
// Note that other jsonnet implementations will fail on `if value in (super)` expression,
// because the standalone super literal is not supported, that is because in other
- // implementations `in super` treated differently from in `smth_else`.
+ // implementations `in super` treated differently from `in smth_else`.
BinaryOp(field, BinaryOpType::In, e)
if matches!(e.expr(), Expr::Literal(LiteralType::Super)) =>
{
- let Some(super_obj) = ctx.super_obj() else {
+ let sup_this = ctx.try_sup_this()?;
+ // In jsonnet, "field" in e is eager, LHS expression is always executed regardless of super existence.
+ // In jrsonnet, however, this wasn't true, this was kept here for compatibility.
+ if !sup_this.has_super() {
return Ok(Val::Bool(false));
- };
- let field = evaluate(ctx.clone(), field)?;
- Val::Bool(super_obj.has_field_ex(field.to_string()?, true))
+ }
+ let field = evaluate(ctx, field)?;
+ Val::Bool(sup_this.field_in_super(field.to_string()?))
}
BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
@@ -473,13 +438,16 @@
let mut parts = parts.iter();
let mut indexable = if matches!(indexable.expr(), Expr::Literal(LiteralType::Super)) {
let part = parts.next().expect("at least part should exist");
- let Some(super_obj) = ctx.super_obj() else {
+ // sup_this existence check might also be skipped here for null-coalesce...
+ // But I believe this might cause errors.
+ let sup_this = ctx.try_sup_this()?;
+ if !sup_this.has_super() {
#[cfg(feature = "exp-null-coaelse")]
if part.null_coaelse {
return Ok(Val::Null);
}
bail!(NoSuperFound)
- };
+ }
let name = evaluate(ctx.clone(), &part.value)?;
let Val::Str(name) = name else {
@@ -490,19 +458,19 @@
))
};
- let this = ctx
- .this()
- .expect("no this found, while super present, should not happen");
let name = name.into_flat();
- match super_obj
- .get_for(name.clone(), this.clone())
+ match sup_this
+ .get_super(name.clone())
.with_description_src(&part.value, || format!("field <{name}> access"))?
{
Some(v) => v,
#[cfg(feature = "exp-null-coaelse")]
None if part.null_coaelse => return Ok(Val::Null),
None => {
- let suggestions = suggest_object_fields(super_obj, name.clone());
+ let suggestions = suggest_object_fields(
+ &sup_this.standalone_super().expect("super exists"),
+ name.clone(),
+ );
bail!(NoSuchField(name, suggestions))
}
@@ -589,7 +557,7 @@
for b in bindings {
evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
}
- let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);
+ let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);
evaluate(ctx, &returned.clone())?
}
Arr(items) => {
@@ -652,7 +620,7 @@
Slice(value, desc) => {
fn parse_idx<T: Typed>(
loc: CallLocation<'_>,
- ctx: &Context,
+ ctx: Context,
expr: Option<&LocExpr>,
desc: &'static str,
) -> Result<Option<T>> {
@@ -660,7 +628,7 @@
Ok(in_frame(
loc,
|| format!("slice {desc}"),
- || <Option<T>>::from_untyped(evaluate(ctx.clone(), value)?),
+ || <Option<T>>::from_untyped(evaluate(ctx, value)?),
)?)
} else {
Ok(None)
@@ -670,9 +638,9 @@
let indexable = evaluate(ctx.clone(), value)?;
let loc = CallLocation::new(&loc);
- let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;
- let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;
- let step = parse_idx(loc, &ctx, desc.step.as_ref(), "step")?;
+ let start = parse_idx(loc, ctx.clone(), desc.start.as_ref(), "start")?;
+ let end = parse_idx(loc, ctx.clone(), desc.end.as_ref(), "end")?;
+ let step = parse_idx(loc, ctx, desc.step.as_ref(), "step")?;
IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?
}
@@ -681,18 +649,21 @@
bail!("computed imports are not supported")
};
let tmp = loc.clone().0;
- let s = ctx.state();
- let resolved_path = s.resolve_from(tmp.source_path(), path)?;
- match i {
- Import(_) => in_frame(
- CallLocation::new(&loc),
- || format!("import {:?}", path.clone()),
- || s.import_resolved(resolved_path),
- )?,
- ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),
- ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),
- _ => unreachable!(),
- }
+ with_state(|s| {
+ let resolved_path = s.resolve_from(tmp.source_path(), path)?;
+ Ok(match i {
+ Import(_) => in_frame(
+ CallLocation::new(&loc),
+ || format!("import {:?}", path.clone()),
+ || s.import_resolved(resolved_path),
+ )?,
+ ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),
+ ImportBin(_) => {
+ Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?))
+ }
+ _ => unreachable!(),
+ }) as Result<Val>
+ })?
}
})
}
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -40,7 +40,7 @@
}
/// Represents Jsonnet function defined in code.
-#[derive(Debug, PartialEq, Trace)]
+#[derive(Debug, Trace, PartialEq)]
pub struct FuncDesc {
/// # Example
///
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -129,11 +129,11 @@
}
Ok(body_ctx
- .extend(passed_args, None, None, None)
- .extend(defaults, None, None, None)
+ .extend_bindings(passed_args)
+ .extend_bindings(defaults)
.into_future(fctx))
} else {
- let body_ctx = body_ctx.extend(passed_args, None, None, None);
+ let body_ctx = body_ctx.extend_bindings(passed_args);
Ok(body_ctx)
}
}
@@ -257,7 +257,5 @@
}
}
- Ok(body_ctx
- .extend(bindings, None, None, None)
- .into_future(fctx))
+ Ok(body_ctx.extend_bindings(bindings).into_future(fctx))
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -28,8 +28,10 @@
any::Any,
cell::{RefCell, RefMut},
collections::hash_map::Entry,
+ clone::Clone,
fmt::{self, Debug},
rc::Rc,
+ marker::PhantomData,
};
pub use ctx::*;
@@ -65,7 +67,7 @@
/// Type of value after object context is bound
type Bound;
/// Create value bound to specified object context
- fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;
+ fn bind(&self, sup_this: SupThis) -> Result<Self::Bound>;
}
/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code
@@ -85,9 +87,9 @@
}
impl MaybeUnbound {
/// Attach object context to value, if required
- pub fn evaluate(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {
+ pub fn evaluate(&self, sup_this: SupThis) -> Result<Val> {
match self {
- Self::Unbound(v) => v.0.bind(sup, this),
+ Self::Unbound(v) => v.0.bind(sup_this),
Self::Bound(v) => Ok(v.evaluate()?),
}
}
@@ -105,8 +107,8 @@
/// Initialize default file context.
/// Has default implementation, which calls `populate`.
/// Prefer to always implement `populate` instead.
- fn initialize(&self, state: State, for_file: Source) -> Context {
- let mut builder = ContextBuilder::with_capacity(state, self.reserve_vars());
+ fn initialize(&self, for_file: Source) -> Context {
+ let mut builder = ContextBuilder::with_capacity(self.reserve_vars());
self.populate(for_file, &mut builder);
builder.build()
}
@@ -130,11 +132,11 @@
where
T: ContextInitializer,
{
- fn initialize(&self, state: State, for_file: Source) -> Context {
+ fn initialize(&self, for_file: Source) -> Context {
if let Some(ctx) = self {
- ctx.initialize(state, for_file)
+ ctx.initialize(for_file)
} else {
- ().initialize(state, for_file)
+ ().initialize(for_file)
}
}
@@ -237,7 +239,40 @@
#[derive(Clone, Trace)]
pub struct State(Cc<EvaluationStateInternals>);
+thread_local! {
+ pub static DEFAULT_STATE: State = State::builder().build();
+ pub static STATE: RefCell<Option<State>> = const {RefCell::new(None)};
+}
+pub struct StateEnterGuard(PhantomData<()>);
+impl Drop for StateEnterGuard {
+ fn drop(&mut self) {
+ STATE.with_borrow_mut(|v| *v = None);
+ }
+}
+
+pub fn with_state<V>(v: impl FnOnce(State) -> V) -> V {
+ if let Some(state) = STATE.with_borrow(Clone::clone) {
+ v(state)
+ } else {
+ let s = DEFAULT_STATE.with(Clone::clone);
+ v(s)
+ }
+}
+
impl State {
+ pub fn enter(&self) -> StateEnterGuard {
+ self.try_enter().expect("entered state already exists")
+ }
+ pub fn try_enter(&self) -> Option<StateEnterGuard> {
+ STATE.with_borrow_mut(|v| {
+ if v.is_none() {
+ *v = Some(self.clone());
+ Some(StateEnterGuard(PhantomData))
+ } else {
+ None
+ }
+ })
+ }
/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise
pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {
let mut file_cache = self.file_cache();
@@ -359,7 +394,7 @@
/// Creates context with all passed global variables
pub fn create_default_context(&self, source: Source) -> Context {
- self.context_initializer().initialize(self.clone(), source)
+ self.context_initializer().initialize(source)
}
/// Creates context with all passed global variables, calling custom modifier
@@ -370,7 +405,6 @@
) -> Context {
let default_initializer = self.context_initializer();
let mut builder = ContextBuilder::with_capacity(
- self.clone(),
default_initializer.reserve_vars() + context_initializer.reserve_vars(),
);
default_initializer.populate(source.clone(), &mut builder);
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -4,14 +4,14 @@
use crate::{gc::WithCapacityExt as _, Thunk, Val};
-#[derive(Trace)]
+#[derive(Trace, Debug)]
#[trace(tracking(force))]
pub struct LayeredHashMapInternals {
parent: Option<LayeredHashMap>,
current: FxHashMap<IStr, Thunk<Val>>,
}
-#[derive(Trace)]
+#[derive(Trace, Debug)]
pub struct LayeredHashMap(Cc<LayeredHashMapInternals>);
impl LayeredHashMap {
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,12 +1,9 @@
use std::{
- any::Any,
- cell::RefCell,
- fmt::Debug,
- hash::{Hash, Hasher},
- ptr::addr_of,
+ any::Any, cell::{Cell, RefCell}, collections::hash_map::Entry, fmt::{self, Debug}, hash::{Hash, Hasher}
};
use jrsonnet_gcmodule::{cc_dyn, Cc, Trace, Weak};
+use educe::Educe;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{Span, Visibility};
use rustc_hash::{FxHashMap, FxHashSet};
@@ -14,10 +11,11 @@
use crate::{
arr::{PickObjectKeyValues, PickObjectValues},
bail,
- error::{suggest_object_fields, Error, ErrorKind::*},
+ error::{suggest_object_fields, ErrorKind::*},
function::{CallLocation, FuncVal},
gc::WithCapacityExt as _,
in_frame,
+ identity_hash,
operator::evaluate_add_op,
val::ArrValue,
CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
@@ -43,12 +41,10 @@
#[derive(Clone, Copy, Default, Debug, Trace)]
pub struct SuperDepth(());
impl SuperDepth {
- pub const fn deeper(self) -> Self {
- Self(())
- }
+ pub(super) fn deepen(self) {}
}
- #[derive(Clone, Copy)]
+ #[derive(Clone, Copy, Debug)]
pub struct FieldSortKey(());
impl FieldSortKey {
pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {
@@ -74,8 +70,8 @@
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct SuperDepth(u32);
impl SuperDepth {
- pub fn deeper(self) -> Self {
- Self(self.0 + 1)
+ pub(super) fn deepen(&mut self) {
+ *self.0 += 1
}
}
@@ -120,7 +116,7 @@
}
}
impl Debug for ObjFieldFlags {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ObjFieldFlags")
.field("add", &self.add())
.field("visibility", &self.visibility())
@@ -140,34 +136,29 @@
cc_dyn!(CcObjectAssertion, ObjectAssertion);
pub trait ObjectAssertion: Trace {
- fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;
+ fn run(&self, sup_this: SupThis) -> Result<()>;
}
// Field => This
-#[derive(Trace)]
+#[derive(Trace, Debug)]
enum CacheValue {
- Cached(Val),
- NotFound,
+ Cached(Result<Option<Val>>),
Pending,
- Errored(Error),
}
#[allow(clippy::module_name_repetitions)]
#[derive(Trace)]
#[trace(tracking(force))]
pub struct OopObject {
- sup: Option<ObjValue>,
// this: Option<ObjValue>,
assertions: Cc<Vec<CcObjectAssertion>>,
- assertions_ran: RefCell<FxHashSet<ObjValue>>,
this_entries: Cc<FxHashMap<IStr, ObjMember>>,
value_cache: RefCell<FxHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,
}
impl Debug for OopObject {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OopObject")
- .field("sup", &self.sup)
// .field("assertions", &self.assertions)
// .field("assertions_ran", &self.assertions_ran)
.field("this_entries", &self.this_entries)
@@ -178,32 +169,36 @@
type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;
-pub trait ObjectLike: Trace + Any + Debug {
- fn extend_from(&self, sup: ObjValue) -> ObjValue;
- /// When using standalone super in object, `this.super_obj.with_this(this)` is executed
- fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {
- ObjValue::new(ThisOverride { inner: me, this })
- }
- fn this(&self) -> Option<ObjValue> {
- None
- }
- fn len(&self) -> usize;
- fn is_empty(&self) -> bool;
- // If callback returns false, iteration stops
- fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;
+#[derive(Trace, Clone)]
+pub enum ValueProcess {
+ None,
+ SuperPlus,
+}
+
+pub trait ObjectCore: Trace + Any + Debug {
+ // If callback returns false, iteration stops, and this call returns false.
+ fn enum_fields_core(
+ &self,
+ super_depth: &mut SuperDepth,
+ handler: &mut EnumFieldsHandler<'_>,
+ ) -> bool;
fn has_field_include_hidden(&self, name: IStr) -> bool;
- fn has_field(&self, name: IStr) -> bool;
- fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;
- fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;
+ fn get_for(&self, key: IStr, sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>>;
+ // fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<(Val, ValueProcess)>>;
fn field_visibility(&self, field: IStr) -> Option<Visibility>;
- fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;
+ fn run_assertions_raw(&self, sup_this: SupThis) -> Result<()>;
}
#[derive(Clone, Trace)]
-pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<dyn ObjectLike>);
+pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);
+impl Debug for WeakObjValue {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_tuple("WeakObjValue").finish()
+ }
+}
impl PartialEq for WeakObjValue {
fn eq(&self, other: &Self) -> bool {
@@ -222,50 +217,97 @@
cc_dyn!(
#[derive(Clone, Debug)]
- ObjValue, ObjectLike,
+ ObjCore, ObjectCore,
pub fn new() {...}
);
+#[derive(Trace, Educe)]
+#[educe(Debug)]
+struct ObjValueInner {
+ cores: Vec<ObjCore>,
+ assertions_ran: Cell<bool>,
+ value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,
+}
-#[derive(Debug, Trace)]
-struct EmptyObject;
-impl ObjectLike for EmptyObject {
- fn extend_from(&self, sup: ObjValue) -> ObjValue {
- // obj + {} == obj
- sup
+thread_local! {
+ static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();
+}
+fn is_asserting(obj: &ObjValue) -> bool {
+ RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))
+}
+/// Returns false if already asserting
+fn start_asserting(obj: &ObjValue) -> bool {
+ RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))
+}
+fn finish_asserting(obj: &ObjValue) {
+ RUNNING_ASSERTIONS.with_borrow_mut(|v| {
+ let r = v.remove(obj);
+ debug_assert!(
+ r,
+ "finish_asserting was called before start_asserting or twice"
+ );
+ });
+}
+
+#[allow(clippy::module_name_repetitions)]
+#[derive(Clone, Trace, Debug, Educe)]
+#[educe(PartialEq, Hash, Eq)]
+pub struct ObjValue(
+ #[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,
+);
+
+#[derive(Trace, Debug)]
+struct StandaloneSuperCore {
+ sup: CoreIdx,
+ this: ObjValue,
+}
+impl ObjectCore for StandaloneSuperCore {
+ fn enum_fields_core(
+ &self,
+ super_depth: &mut SuperDepth,
+ handler: &mut EnumFieldsHandler<'_>,
+ ) -> bool {
+ self.this
+ .enum_fields_internal(super_depth, handler, self.sup)
}
- fn this(&self) -> Option<ObjValue> {
- None
+ fn has_field_include_hidden(&self, name: IStr) -> bool {
+ self.this.has_field_include_hidden_idx(name, self.sup)
}
- fn len(&self) -> usize {
- 0
+ fn get_for(&self, key: IStr, _sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
+ let v = self.this.get_idx(key, self.sup)?;
+ Ok(v.map(|v| (v, ValueProcess::None)))
}
- fn is_empty(&self) -> bool {
- true
+ fn field_visibility(&self, field: IStr) -> Option<Visibility> {
+ self.this.field_visibility_idx(field, self.sup)
}
- fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {
- false
+ fn run_assertions_raw(&self, _sup_this: SupThis) -> Result<()> {
+ self.this.run_assertions()
}
+}
- fn has_field_include_hidden(&self, _name: IStr) -> bool {
- false
+#[derive(Debug, Trace)]
+struct EmptyObject;
+impl ObjectCore for EmptyObject {
+ fn enum_fields_core(
+ &self,
+ _super_depth: &mut SuperDepth,
+ _handler: &mut EnumFieldsHandler<'_>,
+ ) -> bool {
+ true
}
- fn has_field(&self, _name: IStr) -> bool {
+ fn has_field_include_hidden(&self, _name: IStr) -> bool {
false
}
- fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {
- Ok(None)
- }
- fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {
+ fn get_for(&self, _key: IStr, _sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
Ok(None)
}
- fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {
+ fn run_assertions_raw(&self, _sup_this: SupThis) -> Result<()> {
Ok(())
}
@@ -274,65 +316,79 @@
}
}
-#[derive(Trace, Debug)]
-struct ThisOverride {
- inner: ObjValue,
- this: ObjValue,
+#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]
+struct CoreIdx {
+ idx: usize,
}
-impl ObjectLike for ThisOverride {
- fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {
- ObjValue::new(Self {
- inner: self.inner.clone(),
- this,
- })
+impl CoreIdx {
+ fn super_exists(self) -> bool {
+ self.idx != 0
}
-
- fn extend_from(&self, sup: ObjValue) -> ObjValue {
- self.inner.extend_from(sup).with_this(self.this.clone())
+}
+#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]
+pub struct SupThis {
+ sup: CoreIdx,
+ this: ObjValue,
+}
+impl SupThis {
+ pub fn has_super(&self) -> bool {
+ self.sup.super_exists()
}
-
- fn this(&self) -> Option<ObjValue> {
- Some(self.this.clone())
+ /// Implementation of `"field" in super` operation,
+ /// works faster than standalone super path.
+ ///
+ /// In case of no `super` existence, returns false.
+ pub fn field_in_super(&self, field: IStr) -> bool {
+ self.this.has_field_include_hidden_idx(field, self.sup)
}
-
- fn len(&self) -> usize {
- self.inner.len()
+ /// Implementation of `super.field` operation,
+ /// works faster than standalone super path.
+ ///
+ /// In case of no `super` existence, returns `NoSuperFound`
+ pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {
+ if !self.sup.super_exists() {
+ bail!(NoSuperFound);
+ }
+ self.this.get_idx(field, self.sup)
}
-
- fn is_empty(&self) -> bool {
- self.inner.is_empty()
+ /// `super` with `self` overriden for top-level lookups.
+ /// Exists when super appears outside of `super.field`/`"field" in super` expressions
+ /// Exclusive to jrsonnet.
+ ///
+ /// Might return `NoSuperFound` error.
+ pub fn standalone_super(&self) -> Result<ObjValue> {
+ if !self.sup.super_exists() {
+ bail!(NoSuperFound)
+ }
+ Ok(ObjValue::new(StandaloneSuperCore {
+ sup: self.sup,
+ this: self.this.clone(),
+ }))
}
-
- fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {
- self.inner.enum_fields(depth, handler)
+ pub fn this(&self) -> &ObjValue {
+ &self.this
}
-
- fn has_field_include_hidden(&self, name: IStr) -> bool {
- self.inner.has_field_include_hidden(name)
- }
-
- fn has_field(&self, name: IStr) -> bool {
- self.inner.has_field(name)
+ pub fn downgrade(self) -> WeakSupThis {
+ WeakSupThis {
+ sup: self.sup,
+ this: self.this.downgrade(),
+ }
}
-
- fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
- self.inner.get_for(key, this)
- }
-
- fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
- self.inner.get_raw(key, this)
- }
-
- fn field_visibility(&self, field: IStr) -> Option<Visibility> {
- self.inner.field_visibility(field)
- }
-
- fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {
- self.inner.run_assertions_raw(this)
- }
}
+#[derive(Trace, PartialEq, Eq, Hash, Debug)]
+pub struct WeakSupThis {
+ sup: CoreIdx,
+ this: WeakObjValue,
+}
impl ObjValue {
+ pub fn new(v: impl ObjectCore) -> Self {
+ Self(Cc::new(ObjValueInner {
+ cores: vec![ObjCore::new(v)],
+ assertions_ran: Cell::new(false),
+ value_cache: RefCell::new(FxHashMap::new()),
+ }))
+ }
pub fn new_empty() -> Self {
Self::new(EmptyObject)
}
@@ -363,27 +419,77 @@
#[must_use]
pub fn extend_from(&self, sup: Self) -> Self {
- self.0.extend_from(sup)
+ let mut cores = sup.0.cores.clone();
+ cores.extend(self.0.cores.iter().cloned());
+ ObjValue(Cc::new(ObjValueInner {
+ cores,
+ value_cache: RefCell::default(),
+ assertions_ran: Cell::new(false),
+ }))
}
- #[must_use]
- pub fn with_this(&self, this: Self) -> Self {
- self.0.with_this(self.clone(), this)
- }
+ // #[must_use]
+ // pub fn with_this(&self, this: Self) -> Self {
+ // self.0.with_this(self.clone(), this)
+ // }
+ /// Returns amount of visible object fields
+ /// If object only contains hidden fields - may return zero.
pub fn len(&self) -> usize {
- self.0.len()
+ self.fields_visibility()
+ .iter()
+ .filter(|(_, (visible, _))| *visible)
+ .count()
}
pub fn is_empty(&self) -> bool {
- self.0.is_empty()
+ self.len() == 0
+ }
+ /// For each field, calls callback.
+ /// If callback returns false - ends iteration prematurely.
+ ///
+ /// Returns false if ended prematurely
+ pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {
+ let mut super_depth = SuperDepth::default();
+ self.enum_fields_internal(
+ &mut super_depth,
+ handler,
+ CoreIdx {
+ idx: self.0.cores.len(),
+ },
+ )
}
- pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {
- self.0.enum_fields(depth, handler)
+ fn enum_fields_internal(
+ &self,
+ super_depth: &mut SuperDepth,
+ handler: &mut EnumFieldsHandler<'_>,
+ idx: CoreIdx,
+ ) -> bool {
+ for core in self.0.cores[..idx.idx].iter() {
+ if !core.0.enum_fields_core(super_depth, handler) {
+ return false;
+ }
+ super_depth.deepen();
+ }
+ true
}
pub fn has_field_include_hidden(&self, name: IStr) -> bool {
- self.0.has_field_include_hidden(name)
+ self.has_field_include_hidden_idx(
+ name,
+ CoreIdx {
+ idx: self.0.cores.len(),
+ },
+ )
+ }
+ fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {
+ self.0.cores[..core.idx]
+ .iter()
+ .rev()
+ .any(|v| v.0.has_field_include_hidden(name.clone()))
}
pub fn has_field(&self, name: IStr) -> bool {
- self.0.has_field(name)
+ match self.field_visibility(name) {
+ Some(Visibility::Unhide | Visibility::Normal) => true,
+ Some(Visibility::Hidden) | None => false,
+ }
}
pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {
if include_hidden {
@@ -392,14 +498,78 @@
self.has_field(name)
}
}
+ pub fn get(&self, key: IStr) -> Result<Option<Val>> {
+ self.get_idx(
+ key,
+ CoreIdx {
+ idx: self.0.cores.len(),
+ },
+ )
+ }
- pub fn get(&self, key: IStr) -> Result<Option<Val>> {
- self.run_assertions()?;
- self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))
+ fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {
+ let cache_key = (key.clone(), core);
+ {
+ let mut cache = self.0.value_cache.borrow_mut();
+ // entry_ref candidate?
+ match cache.entry(cache_key.clone()) {
+ Entry::Occupied(v) => match v.get() {
+ CacheValue::Cached(v) => return v.clone(),
+ CacheValue::Pending => {
+ if !is_asserting(self) {
+ bail!(InfiniteRecursionDetected);
+ }
+ }
+ },
+ Entry::Vacant(v) => {
+ v.insert(CacheValue::Pending);
+ }
+ };
+ }
+ let result = self.get_idx_uncached(key, core);
+ {
+ let mut cache = self.0.value_cache.borrow_mut();
+ cache.insert(cache_key, CacheValue::Cached(result.clone()));
+ }
+ result
}
+ fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {
+ self.run_assertions()?;
+ let mut add_stack = Vec::with_capacity(2);
+ for (sup, core) in self.0.cores[..core.idx].iter().enumerate().rev() {
+ let sup_this = SupThis {
+ sup: CoreIdx { idx: sup },
+ this: self.clone(),
+ };
+ if let Some((val, proc)) = core.0.get_for(key.clone(), sup_this)? {
+ match proc {
+ ValueProcess::None if add_stack.is_empty() => return Ok(Some(val)),
+ ValueProcess::None => {
+ add_stack.push(val);
+ break;
+ }
+ ValueProcess::SuperPlus => {
+ add_stack.push(val);
+ }
+ }
+ }
+ }
+ if add_stack.is_empty() {
+ // None of layers had this field
+ return Ok(None);
+ } else if add_stack.len() == 1 {
+ // A layer had this field, but it wanted this field to be added with super.
+ // However, no super had this field, fail-safe
+ return Ok(Some(add_stack.pop().expect("single element on stack")));
+ }
+ let mut values = add_stack.into_iter().rev();
+ let init = values.next().expect("at least 2 elements");
- pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {
- self.0.get_for(key, this)
+ values
+ .try_fold(init, |a, b| evaluate_add_op(&a, &b))
+ .map(Some)
+
+ // self.0.get_raw(key, this)
}
pub fn get_or_bail(&self, key: IStr) -> Result<Val> {
@@ -408,22 +578,48 @@
bail!(NoSuchField(key, suggestions))
};
Ok(value)
- }
-
- fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {
- self.0.get_for_uncached(key, this)
}
fn field_visibility(&self, field: IStr) -> Option<Visibility> {
- self.0.field_visibility(field)
+ self.field_visibility_idx(
+ field,
+ CoreIdx {
+ idx: self.0.cores.len(),
+ },
+ )
}
+ fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {
+ let mut exists = false;
+ for ele in self.0.cores[..core.idx].iter().rev() {
+ let vis = ele.0.field_visibility(field.clone());
+ match vis {
+ Some(Visibility::Unhide | Visibility::Hidden) => return vis,
+ Some(Visibility::Normal) => exists = true,
+ None => {}
+ }
+ }
+ exists.then_some(Visibility::Normal)
+ }
pub fn run_assertions(&self) -> Result<()> {
- // FIXME: Should it use `self.0.this()` in case of standalone super?
- self.run_assertions_raw(self.clone())
- }
- fn run_assertions_raw(&self, this: Self) -> Result<()> {
- self.0.run_assertions_raw(this)
+ if self.0.assertions_ran.get() {
+ return Ok(());
+ }
+ if !start_asserting(self) {
+ return Ok(());
+ }
+ for (idx, ele) in self.0.cores.iter().enumerate() {
+ let sup_this = SupThis {
+ sup: CoreIdx { idx },
+ this: self.clone(),
+ };
+ ele.0.run_assertions_raw(sup_this).inspect_err(|_e| {
+ finish_asserting(self);
+ })?;
+ }
+ finish_asserting(self);
+ self.0.assertions_ran.set(true);
+ Ok(())
}
pub fn iter(
@@ -462,24 +658,22 @@
}
fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {
let mut out = FxHashMap::default();
- self.enum_fields(
- SuperDepth::default(),
- &mut |depth, index, name, visibility| {
- let new_sort_key = FieldSortKey::new(depth, index);
- let entry = out.entry(name);
- let (visible, _) = entry.or_insert((true, new_sort_key));
- match visibility {
- Visibility::Normal => {}
- Visibility::Hidden => {
- *visible = false;
- }
- Visibility::Unhide => {
- *visible = true;
- }
- };
- false
- },
- );
+ self.enum_fields(&mut |depth, index, name, visibility| {
+ dbg!(&name, visibility);
+ let new_sort_key = FieldSortKey::new(depth, index);
+ let entry = out.entry(name);
+ let (visible, _) = entry.or_insert((true, new_sort_key));
+ match visibility {
+ Visibility::Normal => {}
+ Visibility::Hidden => {
+ *visible = false;
+ }
+ Visibility::Unhide => {
+ *visible = true;
+ }
+ };
+ false
+ });
out
}
pub fn fields_ex(
@@ -515,8 +709,8 @@
return fields;
}
- let mut fields: Vec<_> = self
- .fields_visibility()
+ let mut fields: Vec<_> = dbg!(self
+ .fields_visibility())
.into_iter()
.filter(|(_, (visible, _))| include_hidden || *visible)
.map(|(k, _)| k)
@@ -580,210 +774,65 @@
impl OopObject {
pub fn new(
- sup: Option<ObjValue>,
this_entries: Cc<FxHashMap<IStr, ObjMember>>,
assertions: Cc<Vec<CcObjectAssertion>>,
) -> Self {
Self {
- sup,
- // this: None,
- assertions,
- assertions_ran: RefCell::new(FxHashSet::new()),
this_entries,
value_cache: RefCell::new(FxHashMap::new()),
+ assertions,
}
}
-
- fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {
- v.invoke.evaluate(self.sup.clone(), Some(real_this))
- }
-
- // FIXME: Duplication between ObjValue and OopObject
- fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {
- let mut out = FxHashMap::default();
- self.enum_fields(
- SuperDepth::default(),
- &mut |depth, index, name, visibility| {
- let new_sort_key = FieldSortKey::new(depth, index);
- let entry = out.entry(name);
- let (visible, _) = entry.or_insert((true, new_sort_key));
- match visibility {
- Visibility::Normal => {}
- Visibility::Hidden => {
- *visible = false;
- }
- Visibility::Unhide => {
- *visible = true;
- }
- };
- false
- },
- );
- out
- }
}
-impl ObjectLike for OopObject {
- fn extend_from(&self, sup: ObjValue) -> ObjValue {
- ObjValue::new(match &self.sup {
- None => Self::new(
- Some(sup),
- self.this_entries.clone(),
- self.assertions.clone(),
- ),
- Some(v) => Self::new(
- Some(v.extend_from(sup)),
- self.this_entries.clone(),
- self.assertions.clone(),
- ),
- })
- }
-
- fn len(&self) -> usize {
- // Maybe it will be better to not compute sort key here?
- self.fields_visibility()
- .into_iter()
- .filter(|(_, (visible, _))| *visible)
- .count()
- }
-
- /// Returns false only if there is any visible entry.
- ///
- /// Note that object with hidden fields `{a:: 1}` will be reported as empty here.
- fn is_empty(&self) -> bool {
- self.len() == 0
- }
-
- /// Run callback for every field found in object
- ///
- /// Returns true if ended prematurely
- fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {
- if let Some(s) = &self.sup {
- if s.enum_fields(depth.deeper(), handler) {
- return true;
- }
- }
+impl ObjectCore for OopObject {
+ fn enum_fields_core(
+ &self,
+ super_depth: &mut SuperDepth,
+ handler: &mut EnumFieldsHandler<'_>,
+ ) -> bool {
for (name, member) in self.this_entries.iter() {
if handler(
- depth,
+ *super_depth,
member.original_index,
name.clone(),
member.flags.visibility(),
) {
- return true;
+ return false;
}
}
- false
+ true
}
fn has_field_include_hidden(&self, name: IStr) -> bool {
- if self.this_entries.contains_key(&name) {
- true
- } else if let Some(super_obj) = &self.sup {
- super_obj.has_field_include_hidden(name)
- } else {
- false
- }
+ self.this_entries.contains_key(&name)
}
- fn has_field(&self, name: IStr) -> bool {
- self.field_visibility(name)
- .map_or(false, |v| v.is_visible())
- }
- fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
- let cache_key = (key.clone(), Some(this.clone().downgrade()));
- if let Some(v) = self.value_cache.borrow().get(&cache_key) {
- return Ok(match v {
- CacheValue::Cached(v) => Some(v.clone()),
- CacheValue::NotFound => None,
- CacheValue::Pending => bail!(InfiniteRecursionDetected),
- CacheValue::Errored(e) => return Err(e.clone()),
- });
- }
- self.value_cache
- .borrow_mut()
- .insert(cache_key.clone(), CacheValue::Pending);
- let value = self.get_for_uncached(key, this).inspect_err(|e| {
- self.value_cache
- .borrow_mut()
- .insert(cache_key.clone(), CacheValue::Errored(e.clone()));
- })?;
- self.value_cache.borrow_mut().insert(
- cache_key,
- value
- .as_ref()
- .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),
- );
- Ok(value)
- }
- fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {
- match (self.this_entries.get(&key), &self.sup) {
- (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),
- (Some(k), Some(super_obj)) => {
- let our = self.evaluate_this(k, real_this.clone())?;
+ fn get_for(&self, key: IStr, sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
+ match self.this_entries.get(&key) {
+ Some(k) => Ok(Some((
+ k.invoke.evaluate(sup_this)?,
if k.flags.add() {
- super_obj
- .get_raw(key, real_this)?
- .map_or(Ok(Some(our.clone())), |v| {
- Ok(Some(evaluate_add_op(&v, &our)?))
- })
+ ValueProcess::SuperPlus
} else {
- Ok(Some(our))
- }
- }
- (None, Some(super_obj)) => super_obj.get_raw(key, real_this),
- (None, None) => Ok(None),
+ ValueProcess::None
+ },
+ ))),
+ None => Ok(None),
}
}
fn field_visibility(&self, name: IStr) -> Option<Visibility> {
- if let Some(m) = self.this_entries.get(&name) {
- Some(match &m.flags.visibility() {
- Visibility::Normal => self
- .sup
- .as_ref()
- .and_then(|super_obj| super_obj.field_visibility(name))
- .unwrap_or(Visibility::Normal),
- v => *v,
- })
- } else if let Some(super_obj) = &self.sup {
- super_obj.field_visibility(name)
- } else {
- None
- }
+ Some(self.this_entries.get(&name)?.flags.visibility())
}
- fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {
+ fn run_assertions_raw(&self, sup_this: SupThis) -> Result<()> {
if self.assertions.is_empty() {
- if let Some(super_obj) = &self.sup {
- super_obj.run_assertions_raw(real_this)?;
- }
return Ok(());
}
- if self.assertions_ran.borrow_mut().insert(real_this.clone()) {
- for assertion in self.assertions.iter() {
- if let Err(e) = assertion.0.run(self.sup.clone(), Some(real_this.clone())) {
- self.assertions_ran.borrow_mut().remove(&real_this);
- return Err(e);
- }
- }
- if let Some(super_obj) = &self.sup {
- super_obj.run_assertions_raw(real_this)?;
- }
+ for assertion in self.assertions.iter() {
+ assertion.0.run(sup_this.clone())?;
}
Ok(())
- }
-}
-
-impl PartialEq for ObjValue {
- fn eq(&self, other: &Self) -> bool {
- Cc::ptr_eq(&self.0, &other.0)
- }
-}
-
-impl Eq for ObjValue {}
-impl Hash for ObjValue {
- fn hash<H: Hasher>(&self, hasher: &mut H) {
- hasher.write_usize(addr_of!(*self.0).expose_provenance() as usize);
}
}
@@ -845,11 +894,8 @@
if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {
return ObjValue::new_empty();
}
- ObjValue::new(OopObject::new(
- self.sup,
- Cc::new(self.map),
- Cc::new(self.assertions),
- ))
+ let res = ObjValue::new(OopObject::new(Cc::new(self.map), Cc::new(self.assertions)));
+ self.sup.map(|sup| res.extend_from(sup)).unwrap_or(res)
}
}
impl Default for ObjValueBuilder {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use std::{2 cell::RefCell,3 cmp::Ordering,4 fmt::{self, Debug, Display},5 mem::replace,6 num::NonZeroU32,7 ops::Deref,8 rc::Rc,9};1011use jrsonnet_gcmodule::{Acyclic, Cc, Trace, TraceBox};12use jrsonnet_interner::IStr;13pub use jrsonnet_macros::Thunk;14use jrsonnet_types::ValType;15use rustc_hash::FxHashMap;16use thiserror::Error;1718pub use crate::arr::{ArrValue, ArrayLike};19use crate::{20 bail,21 error::{Error, ErrorKind::*},22 function::FuncVal,23 gc::WithCapacityExt as _,24 manifest::{ManifestFormat, ToStringFormat},25 typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},26 ObjValue, Result, Unbound, WeakObjValue,27};2829pub trait ThunkValue: Trace {30 type Output;31 fn get(self: Box<Self>) -> Result<Self::Output>;32}3334#[derive(Trace)]35pub struct ThunkValueClosure<D: Trace, O: 'static> {36 env: D,37 // Carries no data, as it is not a real closure, all the38 // captured environment is stored in `env` field.39 #[trace(skip)]40 closure: fn(D) -> Result<O>,41}42impl<D: Trace, O: 'static> ThunkValueClosure<D, O> {43 pub fn new(env: D, closure: fn(D) -> Result<O>) -> Self {44 Self { env, closure }45 }46}47impl<D: Trace, O: 'static> ThunkValue for ThunkValueClosure<D, O> {48 type Output = O;4950 fn get(self: Box<Self>) -> Result<Self::Output> {51 (self.closure)(self.env)52 }53}5455#[derive(Trace)]56enum ThunkInner<T: Trace> {57 Computed(T),58 Errored(Error),59 Waiting(TraceBox<dyn ThunkValue<Output = T>>),60 Pending,61}6263/// Lazily evaluated value64#[allow(clippy::module_name_repetitions)]65#[derive(Clone, Trace)]66pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);6768impl<T: Trace> Thunk<T> {69 pub fn evaluated(val: T) -> Self {70 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))71 }72 pub fn new(f: impl ThunkValue<Output = T> + 'static) -> Self {73 Self(Cc::new(RefCell::new(ThunkInner::Waiting(TraceBox(74 Box::new(f),75 )))))76 }77 pub fn errored(e: Error) -> Self {78 Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))79 }80 pub fn result(res: Result<T, Error>) -> Self {81 match res {82 Ok(o) => Self::evaluated(o),83 Err(e) => Self::errored(e),84 }85 }86}8788impl<T> Thunk<T>89where90 T: Clone + Trace,91{92 pub fn force(&self) -> Result<()> {93 self.evaluate()?;94 Ok(())95 }9697 /// Evaluate thunk, or return cached value98 ///99 /// # Errors100 ///101 /// - Lazy value evaluation returned error102 /// - This method was called during inner value evaluation103 pub fn evaluate(&self) -> Result<T> {104 match &*self.0.borrow() {105 ThunkInner::Computed(v) => return Ok(v.clone()),106 ThunkInner::Errored(e) => return Err(e.clone()),107 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),108 ThunkInner::Waiting(..) => (),109 };110 let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)111 else {112 unreachable!();113 };114 let new_value = match value.0.get() {115 Ok(v) => v,116 Err(e) => {117 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());118 return Err(e);119 }120 };121 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());122 Ok(new_value)123 }124}125126pub trait ThunkMapper<Input>: Trace {127 type Output;128 fn map(self, from: Input) -> Result<Self::Output>;129}130impl<Input> Thunk<Input>131where132 Input: Trace + Clone,133{134 pub fn map<M>(self, mapper: M) -> Thunk<M::Output>135 where136 M: ThunkMapper<Input>,137 M::Output: Trace,138 {139 let inner = self;140 Thunk!(move || {141 let value = inner.evaluate()?;142 let mapped = mapper.map(value)?;143 Ok(mapped)144 })145 }146}147148impl<T: Trace> From<Result<T>> for Thunk<T> {149 fn from(value: Result<T>) -> Self {150 match value {151 Ok(o) => Self::evaluated(o),152 Err(e) => Self::errored(e),153 }154 }155}156impl<T, V: Trace> From<T> for Thunk<V>157where158 T: ThunkValue<Output = V>,159{160 fn from(value: T) -> Self {161 Self::new(value)162 }163}164165impl<T: Trace + Default> Default for Thunk<T> {166 fn default() -> Self {167 Self::evaluated(T::default())168 }169}170171type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);172173#[derive(Trace, Clone)]174pub struct CachedUnbound<I, T>175where176 I: Unbound<Bound = T>,177 T: Trace,178{179 cache: Cc<RefCell<FxHashMap<CacheKey, T>>>,180 value: I,181}182impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {183 pub fn new(value: I) -> Self {184 Self {185 cache: Cc::new(RefCell::new(FxHashMap::new())),186 value,187 }188 }189}190impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {191 type Bound = T;192 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {193 let cache_key = (194 sup.as_ref().map(|s| s.clone().downgrade()),195 this.as_ref().map(|t| t.clone().downgrade()),196 );197 {198 if let Some(t) = self.cache.borrow().get(&cache_key) {199 return Ok(t.clone());200 }201 }202 let bound = self.value.bind(sup, this)?;203204 {205 let mut cache = self.cache.borrow_mut();206 cache.insert(cache_key, bound.clone());207 }208209 Ok(bound)210 }211}212213impl<T: Debug + Trace> Debug for Thunk<T> {214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {215 write!(f, "Lazy")216 }217}218impl<T: Trace> PartialEq for Thunk<T> {219 fn eq(&self, other: &Self) -> bool {220 Cc::ptr_eq(&self.0, &other.0)221 }222}223224/// Represents a Jsonnet value, which can be sliced or indexed (string or array).225#[allow(clippy::module_name_repetitions)]226pub enum IndexableVal {227 /// String.228 Str(IStr),229 /// Array.230 Arr(ArrValue),231}232impl IndexableVal {233 pub fn is_empty(&self) -> bool {234 match self {235 Self::Str(s) => s.is_empty(),236 Self::Arr(s) => s.is_empty(),237 }238 }239240 pub fn to_array(self) -> ArrValue {241 match self {242 Self::Str(s) => ArrValue::chars(s.chars()),243 Self::Arr(arr) => arr,244 }245 }246 /// Slice the value.247 ///248 /// # Implementation249 ///250 /// For strings, will create a copy of specified interval.251 ///252 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.253 pub fn slice(254 self,255 index: Option<i32>,256 end: Option<i32>,257 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,258 ) -> Result<Self> {259 match &self {260 Self::Str(s) => {261 let mut computed_len = None;262 let mut get_len = || {263 computed_len.map_or_else(264 || {265 let len = s.chars().count();266 let _ = computed_len.insert(len);267 len268 },269 |len| len,270 )271 };272 let mut get_idx = |pos: Option<i32>, default| {273 match pos {274 Some(v) if v < 0 => get_len().saturating_sub((-v) as usize),275 // No need to clamp, as iterator interface is used276 Some(v) => v as usize,277 None => default,278 }279 };280281 let index = get_idx(index, 0);282 let end = get_idx(end, usize::MAX);283 let step = step.as_deref().copied().unwrap_or(1);284285 if index >= end {286 return Ok(Self::Str("".into()));287 }288289 Ok(Self::Str(290 (s.chars()291 .skip(index)292 .take(end - index)293 .step_by(step)294 .collect::<String>())295 .into(),296 ))297 }298 Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice(299 index,300 end,301 step.map(|v| NonZeroU32::new(v.value() as u32).expect("bounded != 0")),302 ))),303 }304 }305}306307#[derive(Debug, Clone, Acyclic)]308pub enum StrValue {309 Flat(IStr),310 Tree(Rc<(StrValue, StrValue, usize)>),311}312impl StrValue {313 pub fn concat(a: Self, b: Self) -> Self {314 // TODO: benchmark for an optimal value, currently just a arbitrary choice315 const STRING_EXTEND_THRESHOLD: usize = 100;316317 if a.is_empty() {318 b319 } else if b.is_empty() {320 a321 } else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {322 Self::Flat(format!("{a}{b}").into())323 } else {324 let len = a.len() + b.len();325 Self::Tree(Rc::new((a, b, len)))326 }327 }328 pub fn into_flat(self) -> IStr {329 #[cold]330 fn write_buf(s: &StrValue, out: &mut String) {331 match s {332 StrValue::Flat(f) => out.push_str(f),333 StrValue::Tree(t) => {334 write_buf(&t.0, out);335 write_buf(&t.1, out);336 }337 }338 }339 match self {340 Self::Flat(f) => f,341 Self::Tree(_) => {342 let mut buf = String::with_capacity(self.len());343 write_buf(&self, &mut buf);344 buf.into()345 }346 }347 }348 pub fn len(&self) -> usize {349 match self {350 Self::Flat(v) => v.len(),351 Self::Tree(t) => t.2,352 }353 }354 pub fn is_empty(&self) -> bool {355 match self {356 Self::Flat(v) => v.is_empty(),357 // Can't create non-flat empty string358 Self::Tree(_) => false,359 }360 }361}362impl<T> From<T> for StrValue363where364 IStr: From<T>,365{366 fn from(value: T) -> Self {367 Self::Flat(IStr::from(value))368 }369}370impl Display for StrValue {371 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {372 match self {373 Self::Flat(v) => write!(f, "{v}"),374 Self::Tree(t) => {375 write!(f, "{}", t.0)?;376 write!(f, "{}", t.1)377 }378 }379 }380}381impl PartialEq for StrValue {382 // False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.383 #[allow(clippy::unconditional_recursion)]384 fn eq(&self, other: &Self) -> bool {385 let a = self.clone().into_flat();386 let b = other.clone().into_flat();387 a == b388 }389}390impl Eq for StrValue {}391impl PartialOrd for StrValue {392 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {393 Some(self.cmp(other))394 }395}396impl Ord for StrValue {397 fn cmp(&self, other: &Self) -> Ordering {398 let a = self.clone().into_flat();399 let b = other.clone().into_flat();400 a.cmp(&b)401 }402}403404/// Represents jsonnet number405/// Jsonnet numbers are finite f64, with NaNs disallowed406#[derive(Trace, Clone, Copy)]407#[repr(transparent)]408pub struct NumValue(f64);409impl NumValue {410 /// Creates a [`NumValue`], if value is finite and not NaN411 pub fn new(v: f64) -> Option<Self> {412 if !v.is_finite() {413 return None;414 }415 Some(Self(v))416 }417 #[inline]418 pub const fn get(&self) -> f64 {419 self.0420 }421 pub(crate) fn truncate_for_bitwise(&self) -> Result<i64> {422 if self.0 < MIN_SAFE_INTEGER || self.0 > dbg!(MAX_SAFE_INTEGER) {423 bail!("numberic value outside of safe integer range for bitwise operation");424 }425 Ok(self.0 as i64)426 }427}428impl PartialEq for NumValue {429 fn eq(&self, other: &Self) -> bool {430 self.0 == other.0431 }432}433impl Eq for NumValue {}434impl Ord for NumValue {435 #[inline]436 fn cmp(&self, other: &Self) -> Ordering {437 // Can't use `total_cmp`: its behavior for `-0` and `0`438 // is not following wanted.439 unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }440 }441}442impl PartialOrd for NumValue {443 #[inline]444 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {445 Some(self.cmp(other))446 }447}448impl Debug for NumValue {449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {450 Debug::fmt(&self.0, f)451 }452}453impl Display for NumValue {454 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {455 Display::fmt(&self.0, f)456 }457}458impl Deref for NumValue {459 type Target = f64;460461 #[inline]462 fn deref(&self) -> &Self::Target {463 &self.0464 }465}466macro_rules! impl_num {467 ($($ty:ty),+) => {$(468 impl From<$ty> for NumValue {469 #[inline]470 fn from(value: $ty) -> Self {471 Self(value.into())472 }473 }474 )+};475}476impl_num!(i8, u8, i16, u16, i32, u32);477478#[derive(Clone, Copy, Debug, Error, Trace)]479pub enum ConvertNumValueError {480 #[error("overflow")]481 Overflow,482 #[error("underflow")]483 Underflow,484 #[error("non-finite")]485 NonFinite,486}487impl From<ConvertNumValueError> for Error {488 fn from(e: ConvertNumValueError) -> Self {489 Self::new(e.into())490 }491}492493macro_rules! impl_try_num {494 ($($ty:ty),+) => {$(495 impl TryFrom<$ty> for NumValue {496 type Error = ConvertNumValueError;497 #[inline]498 fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {499 let value = value as f64;500 if value < MIN_SAFE_INTEGER {501 return Err(ConvertNumValueError::Underflow)502 } else if value > MAX_SAFE_INTEGER {503 return Err(ConvertNumValueError::Overflow)504 }505 // Number is finite.506 Ok(Self(value))507 }508 }509 )+};510}511impl_try_num!(usize, isize, i64, u64);512513impl TryFrom<f64> for NumValue {514 type Error = ConvertNumValueError;515516 #[inline]517 fn try_from(value: f64) -> Result<Self, Self::Error> {518 Self::new(value).ok_or(ConvertNumValueError::NonFinite)519 }520}521impl TryFrom<f32> for NumValue {522 type Error = ConvertNumValueError;523524 #[inline]525 fn try_from(value: f32) -> Result<Self, Self::Error> {526 Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)527 }528}529530/// Represents any valid Jsonnet value.531#[derive(Debug, Clone, Trace, Default)]532pub enum Val {533 /// Represents a Jsonnet boolean.534 Bool(bool),535 /// Represents a Jsonnet null value.536 #[default]537 Null,538 /// Represents a Jsonnet string.539 Str(StrValue),540 /// Represents a Jsonnet number.541 /// Should be finite, and not NaN542 /// This restriction isn't enforced by enum, as enum field can't be marked as private543 Num(NumValue),544 /// Experimental bigint545 #[cfg(feature = "exp-bigint")]546 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),547 /// Represents a Jsonnet array.548 Arr(ArrValue),549 /// Represents a Jsonnet object.550 Obj(ObjValue),551 /// Represents a Jsonnet function.552 Func(FuncVal),553}554555#[cfg(target_pointer_width = "64")]556static_assertions::assert_eq_size!(Val, [u8; 24]);557558impl From<IndexableVal> for Val {559 fn from(v: IndexableVal) -> Self {560 match v {561 IndexableVal::Str(s) => Self::string(s),562 IndexableVal::Arr(a) => Self::Arr(a),563 }564 }565}566567impl Val {568 pub const fn as_bool(&self) -> Option<bool> {569 match self {570 Self::Bool(v) => Some(*v),571 _ => None,572 }573 }574 pub const fn as_null(&self) -> Option<()> {575 match self {576 Self::Null => Some(()),577 _ => None,578 }579 }580 pub fn as_str(&self) -> Option<IStr> {581 match self {582 Self::Str(s) => Some(s.clone().into_flat()),583 _ => None,584 }585 }586 pub const fn as_num(&self) -> Option<f64> {587 match self {588 Self::Num(n) => Some(n.get()),589 _ => None,590 }591 }592 #[cfg(feature = "exp-bigint")]593 pub fn as_bigint(&self) -> Option<num_bigint::BigInt> {594 match self {595 Self::BigInt(n) => Some(*n.clone()),596 _ => None,597 }598 }599 pub fn as_arr(&self) -> Option<ArrValue> {600 match self {601 Self::Arr(a) => Some(a.clone()),602 _ => None,603 }604 }605 pub fn as_obj(&self) -> Option<ObjValue> {606 match self {607 Self::Obj(o) => Some(o.clone()),608 _ => None,609 }610 }611 pub fn as_func(&self) -> Option<FuncVal> {612 match self {613 Self::Func(f) => Some(f.clone()),614 _ => None,615 }616 }617618 pub const fn value_type(&self) -> ValType {619 match self {620 Self::Str(..) => ValType::Str,621 Self::Num(..) => ValType::Num,622 #[cfg(feature = "exp-bigint")]623 Self::BigInt(..) => ValType::BigInt,624 Self::Arr(..) => ValType::Arr,625 Self::Obj(..) => ValType::Obj,626 Self::Bool(_) => ValType::Bool,627 Self::Null => ValType::Null,628 Self::Func(..) => ValType::Func,629 }630 }631632 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {633 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {634 manifest.manifest(val.clone())635 }636 manifest_dyn(self, &format)637 }638639 pub fn to_string(&self) -> Result<IStr> {640 Ok(match self {641 Self::Bool(true) => "true".into(),642 Self::Bool(false) => "false".into(),643 Self::Null => "null".into(),644 Self::Str(s) => s.clone().into_flat(),645 _ => self.manifest(ToStringFormat).map(IStr::from)?,646 })647 }648649 pub fn into_indexable(self) -> Result<IndexableVal> {650 Ok(match self {651 Self::Str(s) => IndexableVal::Str(s.into_flat()),652 Self::Arr(arr) => IndexableVal::Arr(arr),653 _ => bail!(ValueIsNotIndexable(self.value_type())),654 })655 }656657 pub fn function(function: impl Into<FuncVal>) -> Self {658 Self::Func(function.into())659 }660 pub fn string(string: impl Into<StrValue>) -> Self {661 Self::Str(string.into())662 }663 pub fn num(num: impl Into<NumValue>) -> Self {664 Self::Num(num.into())665 }666 pub fn try_num<V, E>(num: V) -> Result<Self, E>667 where668 NumValue: TryFrom<V, Error = E>,669 {670 Ok(Self::Num(num.try_into()?))671 }672}673674impl From<IStr> for Val {675 fn from(value: IStr) -> Self {676 Self::string(value)677 }678}679impl From<String> for Val {680 fn from(value: String) -> Self {681 Self::string(value)682 }683}684impl From<&str> for Val {685 fn from(value: &str) -> Self {686 Self::string(value)687 }688}689impl From<ObjValue> for Val {690 fn from(value: ObjValue) -> Self {691 Self::Obj(value)692 }693}694695const fn is_function_like(val: &Val) -> bool {696 matches!(val, Val::Func(_))697}698699/// Native implementation of `std.primitiveEquals`700pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {701 Ok(match (val_a, val_b) {702 (Val::Bool(a), Val::Bool(b)) => a == b,703 (Val::Null, Val::Null) => true,704 (Val::Str(a), Val::Str(b)) => a == b,705 (Val::Num(a), Val::Num(b)) => (a.get() - b.get()).abs() <= f64::EPSILON,706 #[cfg(feature = "exp-bigint")]707 (Val::BigInt(a), Val::BigInt(b)) => a == b,708 (Val::Arr(_), Val::Arr(_)) => {709 bail!("primitiveEquals operates on primitive types, got array")710 }711 (Val::Obj(_), Val::Obj(_)) => {712 bail!("primitiveEquals operates on primitive types, got object")713 }714 (a, b) if is_function_like(a) && is_function_like(b) => {715 bail!("cannot test equality of functions")716 }717 (_, _) => false,718 })719}720721/// Native implementation of `std.equals`722pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {723 if val_a.value_type() != val_b.value_type() {724 return Ok(false);725 }726 match (val_a, val_b) {727 (Val::Arr(a), Val::Arr(b)) => {728 if ArrValue::ptr_eq(a, b) {729 return Ok(true);730 }731 if a.len() != b.len() {732 return Ok(false);733 }734 for (a, b) in a.iter().zip(b.iter()) {735 if !equals(&a?, &b?)? {736 return Ok(false);737 }738 }739 Ok(true)740 }741 (Val::Obj(a), Val::Obj(b)) => {742 if ObjValue::ptr_eq(a, b) {743 return Ok(true);744 }745 let fields = a.fields(746 #[cfg(feature = "exp-preserve-order")]747 false,748 );749 if fields750 != b.fields(751 #[cfg(feature = "exp-preserve-order")]752 false,753 ) {754 return Ok(false);755 }756 for field in fields {757 if !equals(758 &a.get(field.clone())?.expect("field exists"),759 &b.get(field)?.expect("field exists"),760 )? {761 return Ok(false);762 }763 }764 Ok(true)765 }766 (a, b) => Ok(primitive_equals(a, b)?),767 }768}1use std::{2 cell::RefCell,3 cmp::Ordering,4 fmt::{self, Debug, Display},5 mem::replace,6 num::NonZeroU32,7 ops::Deref,8 rc::Rc,9};1011use jrsonnet_gcmodule::{Acyclic, Cc, Trace, TraceBox};12use jrsonnet_interner::IStr;13pub use jrsonnet_macros::Thunk;14use jrsonnet_types::ValType;15use rustc_hash::FxHashMap;16use thiserror::Error;1718pub use crate::arr::{ArrValue, ArrayLike};19use crate::{20 bail,21 error::{Error, ErrorKind::*},22 function::FuncVal,23 gc::WithCapacityExt as _,24 manifest::{ManifestFormat, ToStringFormat},25 typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},26 ObjValue, Result, SupThis, Unbound, WeakSupThis,27};2829pub trait ThunkValue: Trace {30 type Output;31 fn get(self: Box<Self>) -> Result<Self::Output>;32}3334#[derive(Trace)]35pub struct ThunkValueClosure<D: Trace, O: 'static> {36 env: D,37 // Carries no data, as it is not a real closure, all the38 // captured environment is stored in `env` field.39 #[trace(skip)]40 closure: fn(D) -> Result<O>,41}42impl<D: Trace, O: 'static> ThunkValueClosure<D, O> {43 pub fn new(env: D, closure: fn(D) -> Result<O>) -> Self {44 Self { env, closure }45 }46}47impl<D: Trace, O: 'static> ThunkValue for ThunkValueClosure<D, O> {48 type Output = O;4950 fn get(self: Box<Self>) -> Result<Self::Output> {51 (self.closure)(self.env)52 }53}5455#[derive(Trace)]56enum ThunkInner<T: Trace> {57 Computed(T),58 Errored(Error),59 Waiting(TraceBox<dyn ThunkValue<Output = T>>),60 Pending,61}6263/// Lazily evaluated value64#[allow(clippy::module_name_repetitions)]65#[derive(Clone, Trace)]66pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);6768impl<T: Trace> Thunk<T> {69 pub fn evaluated(val: T) -> Self {70 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))71 }72 pub fn new(f: impl ThunkValue<Output = T> + 'static) -> Self {73 Self(Cc::new(RefCell::new(ThunkInner::Waiting(TraceBox(74 Box::new(f),75 )))))76 }77 pub fn errored(e: Error) -> Self {78 Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))79 }80 pub fn result(res: Result<T, Error>) -> Self {81 match res {82 Ok(o) => Self::evaluated(o),83 Err(e) => Self::errored(e),84 }85 }86}8788impl<T> Thunk<T>89where90 T: Clone + Trace,91{92 pub fn force(&self) -> Result<()> {93 self.evaluate()?;94 Ok(())95 }9697 /// Evaluate thunk, or return cached value98 ///99 /// # Errors100 ///101 /// - Lazy value evaluation returned error102 /// - This method was called during inner value evaluation103 pub fn evaluate(&self) -> Result<T> {104 match &*self.0.borrow() {105 ThunkInner::Computed(v) => return Ok(v.clone()),106 ThunkInner::Errored(e) => return Err(e.clone()),107 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),108 ThunkInner::Waiting(..) => (),109 };110 let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)111 else {112 unreachable!();113 };114 let new_value = match value.0.get() {115 Ok(v) => v,116 Err(e) => {117 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());118 return Err(e);119 }120 };121 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());122 Ok(new_value)123 }124}125126pub trait ThunkMapper<Input>: Trace {127 type Output;128 fn map(self, from: Input) -> Result<Self::Output>;129}130impl<Input> Thunk<Input>131where132 Input: Trace + Clone,133{134 pub fn map<M>(self, mapper: M) -> Thunk<M::Output>135 where136 M: ThunkMapper<Input>,137 M::Output: Trace,138 {139 let inner = self;140 Thunk!(move || {141 let value = inner.evaluate()?;142 let mapped = mapper.map(value)?;143 Ok(mapped)144 })145 }146}147148impl<T: Trace> From<Result<T>> for Thunk<T> {149 fn from(value: Result<T>) -> Self {150 match value {151 Ok(o) => Self::evaluated(o),152 Err(e) => Self::errored(e),153 }154 }155}156impl<T, V: Trace> From<T> for Thunk<V>157where158 T: ThunkValue<Output = V>,159{160 fn from(value: T) -> Self {161 Self::new(value)162 }163}164165impl<T: Trace + Default> Default for Thunk<T> {166 fn default() -> Self {167 Self::evaluated(T::default())168 }169}170171#[derive(Trace, Clone)]172pub struct CachedUnbound<I, T>173where174 I: Unbound<Bound = T>,175 T: Trace,176{177 cache: Cc<RefCell<FxHashMap<WeakSupThis, T>>>,178 value: I,179}180impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {181 pub fn new(value: I) -> Self {182 Self {183 cache: Cc::new(RefCell::new(FxHashMap::new())),184 value,185 }186 }187}188impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {189 type Bound = T;190 fn bind(&self, sup_this: SupThis) -> Result<T> {191 let cache_key = sup_this.clone().downgrade();192 {193 if let Some(t) = self.cache.borrow().get(&cache_key) {194 return Ok(t.clone());195 }196 }197 let bound = self.value.bind(sup_this)?;198199 {200 let mut cache = self.cache.borrow_mut();201 cache.insert(cache_key, bound.clone());202 }203204 Ok(bound)205 }206}207208impl<T: Debug + Trace> Debug for Thunk<T> {209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {210 write!(f, "Lazy")211 }212}213impl<T: Trace> PartialEq for Thunk<T> {214 fn eq(&self, other: &Self) -> bool {215 Cc::ptr_eq(&self.0, &other.0)216 }217}218219/// Represents a Jsonnet value, which can be sliced or indexed (string or array).220#[allow(clippy::module_name_repetitions)]221pub enum IndexableVal {222 /// String.223 Str(IStr),224 /// Array.225 Arr(ArrValue),226}227impl IndexableVal {228 pub fn is_empty(&self) -> bool {229 match self {230 Self::Str(s) => s.is_empty(),231 Self::Arr(s) => s.is_empty(),232 }233 }234235 pub fn to_array(self) -> ArrValue {236 match self {237 Self::Str(s) => ArrValue::chars(s.chars()),238 Self::Arr(arr) => arr,239 }240 }241 /// Slice the value.242 ///243 /// # Implementation244 ///245 /// For strings, will create a copy of specified interval.246 ///247 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.248 pub fn slice(249 self,250 index: Option<i32>,251 end: Option<i32>,252 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,253 ) -> Result<Self> {254 match &self {255 Self::Str(s) => {256 let mut computed_len = None;257 let mut get_len = || {258 computed_len.map_or_else(259 || {260 let len = s.chars().count();261 let _ = computed_len.insert(len);262 len263 },264 |len| len,265 )266 };267 let mut get_idx = |pos: Option<i32>, default| {268 match pos {269 Some(v) if v < 0 => get_len().saturating_sub((-v) as usize),270 // No need to clamp, as iterator interface is used271 Some(v) => v as usize,272 None => default,273 }274 };275276 let index = get_idx(index, 0);277 let end = get_idx(end, usize::MAX);278 let step = step.as_deref().copied().unwrap_or(1);279280 if index >= end {281 return Ok(Self::Str("".into()));282 }283284 Ok(Self::Str(285 (s.chars()286 .skip(index)287 .take(end - index)288 .step_by(step)289 .collect::<String>())290 .into(),291 ))292 }293 Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice(294 index,295 end,296 step.map(|v| NonZeroU32::new(v.value() as u32).expect("bounded != 0")),297 ))),298 }299 }300}301302#[derive(Debug, Clone, Acyclic)]303pub enum StrValue {304 Flat(IStr),305 Tree(Rc<(StrValue, StrValue, usize)>),306}307impl StrValue {308 pub fn concat(a: Self, b: Self) -> Self {309 // TODO: benchmark for an optimal value, currently just a arbitrary choice310 const STRING_EXTEND_THRESHOLD: usize = 100;311312 if a.is_empty() {313 b314 } else if b.is_empty() {315 a316 } else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {317 Self::Flat(format!("{a}{b}").into())318 } else {319 let len = a.len() + b.len();320 Self::Tree(Rc::new((a, b, len)))321 }322 }323 pub fn into_flat(self) -> IStr {324 #[cold]325 fn write_buf(s: &StrValue, out: &mut String) {326 match s {327 StrValue::Flat(f) => out.push_str(f),328 StrValue::Tree(t) => {329 write_buf(&t.0, out);330 write_buf(&t.1, out);331 }332 }333 }334 match self {335 Self::Flat(f) => f,336 Self::Tree(_) => {337 let mut buf = String::with_capacity(self.len());338 write_buf(&self, &mut buf);339 buf.into()340 }341 }342 }343 pub fn len(&self) -> usize {344 match self {345 Self::Flat(v) => v.len(),346 Self::Tree(t) => t.2,347 }348 }349 pub fn is_empty(&self) -> bool {350 match self {351 Self::Flat(v) => v.is_empty(),352 // Can't create non-flat empty string353 Self::Tree(_) => false,354 }355 }356}357impl<T> From<T> for StrValue358where359 IStr: From<T>,360{361 fn from(value: T) -> Self {362 Self::Flat(IStr::from(value))363 }364}365impl Display for StrValue {366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {367 match self {368 Self::Flat(v) => write!(f, "{v}"),369 Self::Tree(t) => {370 write!(f, "{}", t.0)?;371 write!(f, "{}", t.1)372 }373 }374 }375}376impl PartialEq for StrValue {377 // False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.378 #[allow(clippy::unconditional_recursion)]379 fn eq(&self, other: &Self) -> bool {380 let a = self.clone().into_flat();381 let b = other.clone().into_flat();382 a == b383 }384}385impl Eq for StrValue {}386impl PartialOrd for StrValue {387 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {388 Some(self.cmp(other))389 }390}391impl Ord for StrValue {392 fn cmp(&self, other: &Self) -> Ordering {393 let a = self.clone().into_flat();394 let b = other.clone().into_flat();395 a.cmp(&b)396 }397}398399/// Represents jsonnet number400/// Jsonnet numbers are finite f64, with NaNs disallowed401#[derive(Trace, Clone, Copy)]402#[repr(transparent)]403pub struct NumValue(f64);404impl NumValue {405 /// Creates a [`NumValue`], if value is finite and not NaN406 pub fn new(v: f64) -> Option<Self> {407 if !v.is_finite() {408 return None;409 }410 Some(Self(v))411 }412 #[inline]413 pub const fn get(&self) -> f64 {414 self.0415 }416 pub(crate) fn truncate_for_bitwise(&self) -> Result<i64> {417 if self.0 < MIN_SAFE_INTEGER || self.0 > dbg!(MAX_SAFE_INTEGER) {418 bail!("numberic value outside of safe integer range for bitwise operation");419 }420 Ok(self.0 as i64)421 }422}423impl PartialEq for NumValue {424 fn eq(&self, other: &Self) -> bool {425 self.0 == other.0426 }427}428impl Eq for NumValue {}429impl Ord for NumValue {430 #[inline]431 fn cmp(&self, other: &Self) -> Ordering {432 // Can't use `total_cmp`: its behavior for `-0` and `0`433 // is not following wanted.434 unsafe { self.0.partial_cmp(&other.0).unwrap_unchecked() }435 }436}437impl PartialOrd for NumValue {438 #[inline]439 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {440 Some(self.cmp(other))441 }442}443impl Debug for NumValue {444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {445 Debug::fmt(&self.0, f)446 }447}448impl Display for NumValue {449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {450 Display::fmt(&self.0, f)451 }452}453impl Deref for NumValue {454 type Target = f64;455456 #[inline]457 fn deref(&self) -> &Self::Target {458 &self.0459 }460}461macro_rules! impl_num {462 ($($ty:ty),+) => {$(463 impl From<$ty> for NumValue {464 #[inline]465 fn from(value: $ty) -> Self {466 Self(value.into())467 }468 }469 )+};470}471impl_num!(i8, u8, i16, u16, i32, u32);472473#[derive(Clone, Copy, Debug, Error, Trace)]474pub enum ConvertNumValueError {475 #[error("overflow")]476 Overflow,477 #[error("underflow")]478 Underflow,479 #[error("non-finite")]480 NonFinite,481}482impl From<ConvertNumValueError> for Error {483 fn from(e: ConvertNumValueError) -> Self {484 Self::new(e.into())485 }486}487488macro_rules! impl_try_num {489 ($($ty:ty),+) => {$(490 impl TryFrom<$ty> for NumValue {491 type Error = ConvertNumValueError;492 #[inline]493 fn try_from(value: $ty) -> Result<Self, ConvertNumValueError> {494 let value = value as f64;495 if value < MIN_SAFE_INTEGER {496 return Err(ConvertNumValueError::Underflow)497 } else if value > MAX_SAFE_INTEGER {498 return Err(ConvertNumValueError::Overflow)499 }500 // Number is finite.501 Ok(Self(value))502 }503 }504 )+};505}506impl_try_num!(usize, isize, i64, u64);507508impl TryFrom<f64> for NumValue {509 type Error = ConvertNumValueError;510511 #[inline]512 fn try_from(value: f64) -> Result<Self, Self::Error> {513 Self::new(value).ok_or(ConvertNumValueError::NonFinite)514 }515}516impl TryFrom<f32> for NumValue {517 type Error = ConvertNumValueError;518519 #[inline]520 fn try_from(value: f32) -> Result<Self, Self::Error> {521 Self::new(f64::from(value)).ok_or(ConvertNumValueError::NonFinite)522 }523}524525/// Represents any valid Jsonnet value.526#[derive(Debug, Clone, Trace, Default)]527pub enum Val {528 /// Represents a Jsonnet boolean.529 Bool(bool),530 /// Represents a Jsonnet null value.531 #[default]532 Null,533 /// Represents a Jsonnet string.534 Str(StrValue),535 /// Represents a Jsonnet number.536 /// Should be finite, and not NaN537 /// This restriction isn't enforced by enum, as enum field can't be marked as private538 Num(NumValue),539 /// Experimental bigint540 #[cfg(feature = "exp-bigint")]541 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),542 /// Represents a Jsonnet array.543 Arr(ArrValue),544 /// Represents a Jsonnet object.545 Obj(ObjValue),546 /// Represents a Jsonnet function.547 Func(FuncVal),548}549550#[cfg(target_pointer_width = "64")]551static_assertions::assert_eq_size!(Val, [u8; 24]);552553impl From<IndexableVal> for Val {554 fn from(v: IndexableVal) -> Self {555 match v {556 IndexableVal::Str(s) => Self::string(s),557 IndexableVal::Arr(a) => Self::Arr(a),558 }559 }560}561562impl Val {563 pub const fn as_bool(&self) -> Option<bool> {564 match self {565 Self::Bool(v) => Some(*v),566 _ => None,567 }568 }569 pub const fn as_null(&self) -> Option<()> {570 match self {571 Self::Null => Some(()),572 _ => None,573 }574 }575 pub fn as_str(&self) -> Option<IStr> {576 match self {577 Self::Str(s) => Some(s.clone().into_flat()),578 _ => None,579 }580 }581 pub const fn as_num(&self) -> Option<f64> {582 match self {583 Self::Num(n) => Some(n.get()),584 _ => None,585 }586 }587 #[cfg(feature = "exp-bigint")]588 pub fn as_bigint(&self) -> Option<num_bigint::BigInt> {589 match self {590 Self::BigInt(n) => Some(*n.clone()),591 _ => None,592 }593 }594 pub fn as_arr(&self) -> Option<ArrValue> {595 match self {596 Self::Arr(a) => Some(a.clone()),597 _ => None,598 }599 }600 pub fn as_obj(&self) -> Option<ObjValue> {601 match self {602 Self::Obj(o) => Some(o.clone()),603 _ => None,604 }605 }606 pub fn as_func(&self) -> Option<FuncVal> {607 match self {608 Self::Func(f) => Some(f.clone()),609 _ => None,610 }611 }612613 pub const fn value_type(&self) -> ValType {614 match self {615 Self::Str(..) => ValType::Str,616 Self::Num(..) => ValType::Num,617 #[cfg(feature = "exp-bigint")]618 Self::BigInt(..) => ValType::BigInt,619 Self::Arr(..) => ValType::Arr,620 Self::Obj(..) => ValType::Obj,621 Self::Bool(_) => ValType::Bool,622 Self::Null => ValType::Null,623 Self::Func(..) => ValType::Func,624 }625 }626627 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {628 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {629 manifest.manifest(val.clone())630 }631 manifest_dyn(self, &format)632 }633634 pub fn to_string(&self) -> Result<IStr> {635 Ok(match self {636 Self::Bool(true) => "true".into(),637 Self::Bool(false) => "false".into(),638 Self::Null => "null".into(),639 Self::Str(s) => s.clone().into_flat(),640 _ => self.manifest(ToStringFormat).map(IStr::from)?,641 })642 }643644 pub fn into_indexable(self) -> Result<IndexableVal> {645 Ok(match self {646 Self::Str(s) => IndexableVal::Str(s.into_flat()),647 Self::Arr(arr) => IndexableVal::Arr(arr),648 _ => bail!(ValueIsNotIndexable(self.value_type())),649 })650 }651652 pub fn function(function: impl Into<FuncVal>) -> Self {653 Self::Func(function.into())654 }655 pub fn string(string: impl Into<StrValue>) -> Self {656 Self::Str(string.into())657 }658 pub fn num(num: impl Into<NumValue>) -> Self {659 Self::Num(num.into())660 }661 pub fn try_num<V, E>(num: V) -> Result<Self, E>662 where663 NumValue: TryFrom<V, Error = E>,664 {665 Ok(Self::Num(num.try_into()?))666 }667}668669impl From<IStr> for Val {670 fn from(value: IStr) -> Self {671 Self::string(value)672 }673}674impl From<String> for Val {675 fn from(value: String) -> Self {676 Self::string(value)677 }678}679impl From<&str> for Val {680 fn from(value: &str) -> Self {681 Self::string(value)682 }683}684impl From<ObjValue> for Val {685 fn from(value: ObjValue) -> Self {686 Self::Obj(value)687 }688}689690const fn is_function_like(val: &Val) -> bool {691 matches!(val, Val::Func(_))692}693694/// Native implementation of `std.primitiveEquals`695pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {696 Ok(match (val_a, val_b) {697 (Val::Bool(a), Val::Bool(b)) => a == b,698 (Val::Null, Val::Null) => true,699 (Val::Str(a), Val::Str(b)) => a == b,700 (Val::Num(a), Val::Num(b)) => (a.get() - b.get()).abs() <= f64::EPSILON,701 #[cfg(feature = "exp-bigint")]702 (Val::BigInt(a), Val::BigInt(b)) => a == b,703 (Val::Arr(_), Val::Arr(_)) => {704 bail!("primitiveEquals operates on primitive types, got array")705 }706 (Val::Obj(_), Val::Obj(_)) => {707 bail!("primitiveEquals operates on primitive types, got object")708 }709 (a, b) if is_function_like(a) && is_function_like(b) => {710 bail!("cannot test equality of functions")711 }712 (_, _) => false,713 })714}715716/// Native implementation of `std.equals`717pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {718 if val_a.value_type() != val_b.value_type() {719 return Ok(false);720 }721 match (val_a, val_b) {722 (Val::Arr(a), Val::Arr(b)) => {723 if ArrValue::ptr_eq(a, b) {724 return Ok(true);725 }726 if a.len() != b.len() {727 return Ok(false);728 }729 for (a, b) in a.iter().zip(b.iter()) {730 if !equals(&a?, &b?)? {731 return Ok(false);732 }733 }734 Ok(true)735 }736 (Val::Obj(a), Val::Obj(b)) => {737 if ObjValue::ptr_eq(a, b) {738 return Ok(true);739 }740 let fields = a.fields(741 #[cfg(feature = "exp-preserve-order")]742 false,743 );744 if fields745 != b.fields(746 #[cfg(feature = "exp-preserve-order")]747 false,748 ) {749 return Ok(false);750 }751 for field in fields {752 if !equals(753 &a.get(field.clone())?.expect("field exists"),754 &b.get(field)?.expect("field exists"),755 )? {756 return Ok(false);757 }758 }759 Ok(true)760 }761 (a, b) => Ok(primitive_equals(a, b)?),762 }763}tests/cpp_test_suite_golden_override/error.static_error_self.jsonnet.goldendiffbeforeafterboth--- a/tests/cpp_test_suite_golden_override/error.static_error_self.jsonnet.golden
+++ b/tests/cpp_test_suite_golden_override/error.static_error_self.jsonnet.golden
@@ -1,2 +1,2 @@
-self is only usable inside objects
+self/super/$ are only usable inside objects
elem <0> evaluation
\ No newline at end of file
tests/cpp_test_suite_golden_override/error.static_error_super.jsonnet.goldendiffbeforeafterboth--- a/tests/cpp_test_suite_golden_override/error.static_error_super.jsonnet.golden
+++ b/tests/cpp_test_suite_golden_override/error.static_error_super.jsonnet.golden
@@ -1,2 +1,2 @@
-no super found
+self/super/$ are only usable inside objects
elem <0> evaluation
\ No newline at end of file
tests/golden/issue195.jsonnetdiffbeforeafterboth--- /dev/null
+++ b/tests/golden/issue195.jsonnet
@@ -0,0 +1 @@
+{ x: 42 } { y: { "false": "x" in super } }
tests/golden/issue195.jsonnet.goldendiffbeforeafterboth--- /dev/null
+++ b/tests/golden/issue195.jsonnet.golden
@@ -0,0 +1,6 @@
+{
+ "x": 42,
+ "y": {
+ "false": false
+ }
+}
\ No newline at end of file
tests/tests/cpp_test_suite.rsdiffbeforeafterboth--- a/tests/tests/cpp_test_suite.rs
+++ b/tests/tests/cpp_test_suite.rs
@@ -30,6 +30,8 @@
.import_resolver(FileImportResolver::default());
let s = s.build();
+ let _entered = s.enter();
+
let trace_format = CompactFormat {
resolver: PathResolver::FileName,
max_trace: 20,
@@ -61,7 +63,7 @@
Val::Obj(o.build())
}),
);
- v = apply_tla(s, &args, v).expect("failed to apply tla");
+ v = apply_tla(&args, v).expect("failed to apply tla");
}
match v.manifest(JsonFormat::default()) {
tests/tests/golden.rsdiffbeforeafterboth--- a/tests/tests/golden.rs
+++ b/tests/tests/golden.rs
@@ -21,6 +21,8 @@
.import_resolver(FileImportResolver::default());
let s = s.build();
+ let _entered = s.enter();
+
let trace_format = CompactFormat {
resolver: PathResolver::FileName,
max_trace: 20,