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.rsdiffbeforeafterboth1use std::{2 any::Any,3 cell::RefCell,4 fmt::Debug,5 hash::{Hash, Hasher},6 ptr::addr_of,7};89use jrsonnet_gcmodule::{cc_dyn, Cc, Trace, Weak};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{Span, Visibility};12use rustc_hash::{FxHashMap, FxHashSet};1314use crate::{15 arr::{PickObjectKeyValues, PickObjectValues},16 bail,17 error::{suggest_object_fields, Error, ErrorKind::*},18 function::{CallLocation, FuncVal},19 gc::WithCapacityExt as _,20 in_frame,21 operator::evaluate_add_op,22 val::ArrValue,23 CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,24};2526#[cfg(not(feature = "exp-preserve-order"))]27mod ordering {28 #![allow(29 // This module works as stub for preserve-order feature30 clippy::unused_self,31 )]3233 use jrsonnet_gcmodule::Trace;3435 #[derive(Clone, Copy, Default, Debug, Trace)]36 pub struct FieldIndex(());37 impl FieldIndex {38 pub const fn next(self) -> Self {39 Self(())40 }41 }4243 #[derive(Clone, Copy, Default, Debug, Trace)]44 pub struct SuperDepth(());45 impl SuperDepth {46 pub const fn deeper(self) -> Self {47 Self(())48 }49 }5051 #[derive(Clone, Copy)]52 pub struct FieldSortKey(());53 impl FieldSortKey {54 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {55 Self(())56 }57 }58}5960#[cfg(feature = "exp-preserve-order")]61mod ordering {62 use std::cmp::Reverse;6364 use jrsonnet_gcmodule::Trace;6566 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]67 pub struct FieldIndex(u32);68 impl FieldIndex {69 pub fn next(self) -> Self {70 Self(self.0 + 1)71 }72 }7374 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]75 pub struct SuperDepth(u32);76 impl SuperDepth {77 pub fn deeper(self) -> Self {78 Self(self.0 + 1)79 }80 }8182 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]83 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);84 impl FieldSortKey {85 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {86 Self(Reverse(depth), index)87 }88 }89}9091use ordering::{FieldIndex, FieldSortKey, SuperDepth};9293// 0 - add94// 12 - visibility95#[derive(Clone, Copy)]96pub struct ObjFieldFlags(u8);97impl ObjFieldFlags {98 fn new(add: bool, visibility: Visibility) -> Self {99 let mut v = 0;100 if add {101 v |= 1;102 }103 v |= match visibility {104 Visibility::Normal => 0b000,105 Visibility::Hidden => 0b010,106 Visibility::Unhide => 0b100,107 };108 Self(v)109 }110 pub fn add(&self) -> bool {111 self.0 & 1 != 0112 }113 pub fn visibility(&self) -> Visibility {114 match (self.0 & 0b110) >> 1 {115 0b00 => Visibility::Normal,116 0b01 => Visibility::Hidden,117 0b10 => Visibility::Unhide,118 _ => unreachable!(),119 }120 }121}122impl Debug for ObjFieldFlags {123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {124 f.debug_struct("ObjFieldFlags")125 .field("add", &self.add())126 .field("visibility", &self.visibility())127 .finish()128 }129}130131#[allow(clippy::module_name_repetitions)]132#[derive(Debug, Trace)]133pub struct ObjMember {134 #[trace(skip)]135 flags: ObjFieldFlags,136 original_index: FieldIndex,137 pub invoke: MaybeUnbound,138 pub location: Option<Span>,139}140141cc_dyn!(CcObjectAssertion, ObjectAssertion);142pub trait ObjectAssertion: Trace {143 fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;144}145146// Field => This147148#[derive(Trace)]149enum CacheValue {150 Cached(Val),151 NotFound,152 Pending,153 Errored(Error),154}155156#[allow(clippy::module_name_repetitions)]157#[derive(Trace)]158#[trace(tracking(force))]159pub struct OopObject {160 sup: Option<ObjValue>,161 // this: Option<ObjValue>,162 assertions: Cc<Vec<CcObjectAssertion>>,163 assertions_ran: RefCell<FxHashSet<ObjValue>>,164 this_entries: Cc<FxHashMap<IStr, ObjMember>>,165 value_cache: RefCell<FxHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,166}167impl Debug for OopObject {168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {169 f.debug_struct("OopObject")170 .field("sup", &self.sup)171 // .field("assertions", &self.assertions)172 // .field("assertions_ran", &self.assertions_ran)173 .field("this_entries", &self.this_entries)174 // .field("value_cache", &self.value_cache)175 .finish_non_exhaustive()176 }177}178179type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;180181pub trait ObjectLike: Trace + Any + Debug {182 fn extend_from(&self, sup: ObjValue) -> ObjValue;183 /// When using standalone super in object, `this.super_obj.with_this(this)` is executed184 fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {185 ObjValue::new(ThisOverride { inner: me, this })186 }187 fn this(&self) -> Option<ObjValue> {188 None189 }190 fn len(&self) -> usize;191 fn is_empty(&self) -> bool;192 // If callback returns false, iteration stops193 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;194195 fn has_field_include_hidden(&self, name: IStr) -> bool;196 fn has_field(&self, name: IStr) -> bool;197198 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;199 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;200 fn field_visibility(&self, field: IStr) -> Option<Visibility>;201202 fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;203}204205#[derive(Clone, Trace)]206pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<dyn ObjectLike>);207208impl PartialEq for WeakObjValue {209 fn eq(&self, other: &Self) -> bool {210 Weak::ptr_eq(&self.0, &other.0)211 }212}213214impl Eq for WeakObjValue {}215impl Hash for WeakObjValue {216 fn hash<H: Hasher>(&self, hasher: &mut H) {217 // Safety: usize is POD218 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };219 hasher.write_usize(addr);220 }221}222223cc_dyn!(224 #[derive(Clone, Debug)]225 ObjValue, ObjectLike,226 pub fn new() {...}227);228229#[derive(Debug, Trace)]230struct EmptyObject;231impl ObjectLike for EmptyObject {232 fn extend_from(&self, sup: ObjValue) -> ObjValue {233 // obj + {} == obj234 sup235 }236237 fn this(&self) -> Option<ObjValue> {238 None239 }240241 fn len(&self) -> usize {242 0243 }244245 fn is_empty(&self) -> bool {246 true247 }248249 fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {250 false251 }252253 fn has_field_include_hidden(&self, _name: IStr) -> bool {254 false255 }256257 fn has_field(&self, _name: IStr) -> bool {258 false259 }260261 fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {262 Ok(None)263 }264 fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {265 Ok(None)266 }267268 fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {269 Ok(())270 }271272 fn field_visibility(&self, _field: IStr) -> Option<Visibility> {273 None274 }275}276277#[derive(Trace, Debug)]278struct ThisOverride {279 inner: ObjValue,280 this: ObjValue,281}282impl ObjectLike for ThisOverride {283 fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {284 ObjValue::new(Self {285 inner: self.inner.clone(),286 this,287 })288 }289290 fn extend_from(&self, sup: ObjValue) -> ObjValue {291 self.inner.extend_from(sup).with_this(self.this.clone())292 }293294 fn this(&self) -> Option<ObjValue> {295 Some(self.this.clone())296 }297298 fn len(&self) -> usize {299 self.inner.len()300 }301302 fn is_empty(&self) -> bool {303 self.inner.is_empty()304 }305306 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {307 self.inner.enum_fields(depth, handler)308 }309310 fn has_field_include_hidden(&self, name: IStr) -> bool {311 self.inner.has_field_include_hidden(name)312 }313314 fn has_field(&self, name: IStr) -> bool {315 self.inner.has_field(name)316 }317318 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {319 self.inner.get_for(key, this)320 }321322 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {323 self.inner.get_raw(key, this)324 }325326 fn field_visibility(&self, field: IStr) -> Option<Visibility> {327 self.inner.field_visibility(field)328 }329330 fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {331 self.inner.run_assertions_raw(this)332 }333}334335impl ObjValue {336 pub fn new_empty() -> Self {337 Self::new(EmptyObject)338 }339 pub fn builder() -> ObjValueBuilder {340 ObjValueBuilder::new()341 }342 pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {343 ObjValueBuilder::with_capacity(capacity)344 }345 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {346 let mut out = ObjValueBuilder::with_capacity(1);347 out.with_super(self);348 let mut member = out.field(key);349 if value.flags.add() {350 member = member.add();351 }352 if let Some(loc) = value.location {353 member = member.with_location(loc);354 }355 let _ = member356 .with_visibility(value.flags.visibility())357 .binding(value.invoke);358 out.build()359 }360 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {361 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())362 }363364 #[must_use]365 pub fn extend_from(&self, sup: Self) -> Self {366 self.0.extend_from(sup)367 }368 #[must_use]369 pub fn with_this(&self, this: Self) -> Self {370 self.0.with_this(self.clone(), this)371 }372 pub fn len(&self) -> usize {373 self.0.len()374 }375 pub fn is_empty(&self) -> bool {376 self.0.is_empty()377 }378 pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {379 self.0.enum_fields(depth, handler)380 }381382 pub fn has_field_include_hidden(&self, name: IStr) -> bool {383 self.0.has_field_include_hidden(name)384 }385 pub fn has_field(&self, name: IStr) -> bool {386 self.0.has_field(name)387 }388 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {389 if include_hidden {390 self.has_field_include_hidden(name)391 } else {392 self.has_field(name)393 }394 }395396 pub fn get(&self, key: IStr) -> Result<Option<Val>> {397 self.run_assertions()?;398 self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))399 }400401 pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {402 self.0.get_for(key, this)403 }404405 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {406 let Some(value) = self.get(key.clone())? else {407 let suggestions = suggest_object_fields(self, key.clone());408 bail!(NoSuchField(key, suggestions))409 };410 Ok(value)411 }412413 fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {414 self.0.get_for_uncached(key, this)415 }416417 fn field_visibility(&self, field: IStr) -> Option<Visibility> {418 self.0.field_visibility(field)419 }420421 pub fn run_assertions(&self) -> Result<()> {422 // FIXME: Should it use `self.0.this()` in case of standalone super?423 self.run_assertions_raw(self.clone())424 }425 fn run_assertions_raw(&self, this: Self) -> Result<()> {426 self.0.run_assertions_raw(this)427 }428429 pub fn iter(430 &self,431 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,432 ) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {433 let fields = self.fields(434 #[cfg(feature = "exp-preserve-order")]435 preserve_order,436 );437 fields.into_iter().map(|field| {438 (439 field.clone(),440 self.get(field)441 .map(|opt| opt.expect("iterating over keys, field exists")),442 )443 })444 }445 pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {446 if !self.has_field_ex(key.clone(), true) {447 return None;448 }449 let obj = self.clone();450451 Some(Thunk!(move || Ok(obj.get(key)?.expect("field exists"))))452 }453 pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {454 let obj = self.clone();455 Thunk!(move || obj.get_or_bail(key))456 }457 pub fn ptr_eq(a: &Self, b: &Self) -> bool {458 Cc::ptr_eq(&a.0, &b.0)459 }460 pub fn downgrade(self) -> WeakObjValue {461 WeakObjValue(self.0.downgrade())462 }463 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {464 let mut out = FxHashMap::default();465 self.enum_fields(466 SuperDepth::default(),467 &mut |depth, index, name, visibility| {468 let new_sort_key = FieldSortKey::new(depth, index);469 let entry = out.entry(name);470 let (visible, _) = entry.or_insert((true, new_sort_key));471 match visibility {472 Visibility::Normal => {}473 Visibility::Hidden => {474 *visible = false;475 }476 Visibility::Unhide => {477 *visible = true;478 }479 };480 false481 },482 );483 out484 }485 pub fn fields_ex(486 &self,487 include_hidden: bool,488 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,489 ) -> Vec<IStr> {490 #[cfg(feature = "exp-preserve-order")]491 if preserve_order {492 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self493 .fields_visibility()494 .into_iter()495 .filter(|(_, (visible, _))| include_hidden || *visible)496 .enumerate()497 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))498 .unzip();499 keys.sort_unstable_by_key(|v| v.0);500 // Reorder in-place by resulting indexes501 for i in 0..fields.len() {502 let x = fields[i].clone();503 let mut j = i;504 loop {505 let k = keys[j].1;506 keys[j].1 = j;507 if k == i {508 break;509 }510 fields[j] = fields[k].clone();511 j = k;512 }513 fields[j] = x;514 }515 return fields;516 }517518 let mut fields: Vec<_> = self519 .fields_visibility()520 .into_iter()521 .filter(|(_, (visible, _))| include_hidden || *visible)522 .map(|(k, _)| k)523 .collect();524 fields.sort_unstable();525 fields526 }527 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {528 self.fields_ex(529 false,530 #[cfg(feature = "exp-preserve-order")]531 preserve_order,532 )533 }534 pub fn values_ex(535 &self,536 include_hidden: bool,537 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,538 ) -> ArrValue {539 ArrValue::new(PickObjectValues::new(540 self.clone(),541 self.fields_ex(542 include_hidden,543 #[cfg(feature = "exp-preserve-order")]544 preserve_order,545 ),546 ))547 }548 pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {549 self.values_ex(550 false,551 #[cfg(feature = "exp-preserve-order")]552 preserve_order,553 )554 }555 pub fn key_values_ex(556 &self,557 include_hidden: bool,558 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,559 ) -> ArrValue {560 ArrValue::new(PickObjectKeyValues::new(561 self.clone(),562 self.fields_ex(563 include_hidden,564 #[cfg(feature = "exp-preserve-order")]565 preserve_order,566 ),567 ))568 }569 pub fn key_values(570 &self,571 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,572 ) -> ArrValue {573 self.key_values_ex(574 false,575 #[cfg(feature = "exp-preserve-order")]576 preserve_order,577 )578 }579}580581impl OopObject {582 pub fn new(583 sup: Option<ObjValue>,584 this_entries: Cc<FxHashMap<IStr, ObjMember>>,585 assertions: Cc<Vec<CcObjectAssertion>>,586 ) -> Self {587 Self {588 sup,589 // this: None,590 assertions,591 assertions_ran: RefCell::new(FxHashSet::new()),592 this_entries,593 value_cache: RefCell::new(FxHashMap::new()),594 }595 }596597 fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {598 v.invoke.evaluate(self.sup.clone(), Some(real_this))599 }600601 // FIXME: Duplication between ObjValue and OopObject602 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {603 let mut out = FxHashMap::default();604 self.enum_fields(605 SuperDepth::default(),606 &mut |depth, index, name, visibility| {607 let new_sort_key = FieldSortKey::new(depth, index);608 let entry = out.entry(name);609 let (visible, _) = entry.or_insert((true, new_sort_key));610 match visibility {611 Visibility::Normal => {}612 Visibility::Hidden => {613 *visible = false;614 }615 Visibility::Unhide => {616 *visible = true;617 }618 };619 false620 },621 );622 out623 }624}625626impl ObjectLike for OopObject {627 fn extend_from(&self, sup: ObjValue) -> ObjValue {628 ObjValue::new(match &self.sup {629 None => Self::new(630 Some(sup),631 self.this_entries.clone(),632 self.assertions.clone(),633 ),634 Some(v) => Self::new(635 Some(v.extend_from(sup)),636 self.this_entries.clone(),637 self.assertions.clone(),638 ),639 })640 }641642 fn len(&self) -> usize {643 // Maybe it will be better to not compute sort key here?644 self.fields_visibility()645 .into_iter()646 .filter(|(_, (visible, _))| *visible)647 .count()648 }649650 /// Returns false only if there is any visible entry.651 ///652 /// Note that object with hidden fields `{a:: 1}` will be reported as empty here.653 fn is_empty(&self) -> bool {654 self.len() == 0655 }656657 /// Run callback for every field found in object658 ///659 /// Returns true if ended prematurely660 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {661 if let Some(s) = &self.sup {662 if s.enum_fields(depth.deeper(), handler) {663 return true;664 }665 }666 for (name, member) in self.this_entries.iter() {667 if handler(668 depth,669 member.original_index,670 name.clone(),671 member.flags.visibility(),672 ) {673 return true;674 }675 }676 false677 }678679 fn has_field_include_hidden(&self, name: IStr) -> bool {680 if self.this_entries.contains_key(&name) {681 true682 } else if let Some(super_obj) = &self.sup {683 super_obj.has_field_include_hidden(name)684 } else {685 false686 }687 }688 fn has_field(&self, name: IStr) -> bool {689 self.field_visibility(name)690 .map_or(false, |v| v.is_visible())691 }692693 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {694 let cache_key = (key.clone(), Some(this.clone().downgrade()));695 if let Some(v) = self.value_cache.borrow().get(&cache_key) {696 return Ok(match v {697 CacheValue::Cached(v) => Some(v.clone()),698 CacheValue::NotFound => None,699 CacheValue::Pending => bail!(InfiniteRecursionDetected),700 CacheValue::Errored(e) => return Err(e.clone()),701 });702 }703 self.value_cache704 .borrow_mut()705 .insert(cache_key.clone(), CacheValue::Pending);706 let value = self.get_for_uncached(key, this).inspect_err(|e| {707 self.value_cache708 .borrow_mut()709 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));710 })?;711 self.value_cache.borrow_mut().insert(712 cache_key,713 value714 .as_ref()715 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),716 );717 Ok(value)718 }719 fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {720 match (self.this_entries.get(&key), &self.sup) {721 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),722 (Some(k), Some(super_obj)) => {723 let our = self.evaluate_this(k, real_this.clone())?;724 if k.flags.add() {725 super_obj726 .get_raw(key, real_this)?727 .map_or(Ok(Some(our.clone())), |v| {728 Ok(Some(evaluate_add_op(&v, &our)?))729 })730 } else {731 Ok(Some(our))732 }733 }734 (None, Some(super_obj)) => super_obj.get_raw(key, real_this),735 (None, None) => Ok(None),736 }737 }738 fn field_visibility(&self, name: IStr) -> Option<Visibility> {739 if let Some(m) = self.this_entries.get(&name) {740 Some(match &m.flags.visibility() {741 Visibility::Normal => self742 .sup743 .as_ref()744 .and_then(|super_obj| super_obj.field_visibility(name))745 .unwrap_or(Visibility::Normal),746 v => *v,747 })748 } else if let Some(super_obj) = &self.sup {749 super_obj.field_visibility(name)750 } else {751 None752 }753 }754755 fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {756 if self.assertions.is_empty() {757 if let Some(super_obj) = &self.sup {758 super_obj.run_assertions_raw(real_this)?;759 }760 return Ok(());761 }762 if self.assertions_ran.borrow_mut().insert(real_this.clone()) {763 for assertion in self.assertions.iter() {764 if let Err(e) = assertion.0.run(self.sup.clone(), Some(real_this.clone())) {765 self.assertions_ran.borrow_mut().remove(&real_this);766 return Err(e);767 }768 }769 if let Some(super_obj) = &self.sup {770 super_obj.run_assertions_raw(real_this)?;771 }772 }773 Ok(())774 }775}776777impl PartialEq for ObjValue {778 fn eq(&self, other: &Self) -> bool {779 Cc::ptr_eq(&self.0, &other.0)780 }781}782783impl Eq for ObjValue {}784impl Hash for ObjValue {785 fn hash<H: Hasher>(&self, hasher: &mut H) {786 hasher.write_usize(addr_of!(*self.0).expose_provenance() as usize);787 }788}789790#[allow(clippy::module_name_repetitions)]791pub struct ObjValueBuilder {792 sup: Option<ObjValue>,793 map: FxHashMap<IStr, ObjMember>,794 assertions: Vec<CcObjectAssertion>,795 next_field_index: FieldIndex,796}797impl ObjValueBuilder {798 pub fn new() -> Self {799 Self::with_capacity(0)800 }801 pub fn with_capacity(capacity: usize) -> Self {802 Self {803 sup: None,804 map: FxHashMap::with_capacity(capacity),805 assertions: Vec::new(),806 next_field_index: FieldIndex::default(),807 }808 }809 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {810 self.assertions.reserve_exact(capacity);811 self812 }813 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {814 self.sup = Some(super_obj);815 self816 }817818 pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {819 self.assertions.push(CcObjectAssertion::new(assertion));820 self821 }822 pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {823 let field_index = self.next_field_index;824 self.next_field_index = self.next_field_index.next();825 ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)826 }827 /// Preset for common method definiton pattern:828 /// Create a hidden field with the function value.829 ///830 /// `.field(name).hide().value(Val::function(value))`831 pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {832 self.field(name).hide().value(Val::Func(value.into()));833 self834 }835 pub fn try_method(836 &mut self,837 name: impl Into<IStr>,838 value: impl Into<FuncVal>,839 ) -> Result<&mut Self> {840 self.field(name).hide().try_value(Val::Func(value.into()))?;841 Ok(self)842 }843844 pub fn build(self) -> ObjValue {845 if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {846 return ObjValue::new_empty();847 }848 ObjValue::new(OopObject::new(849 self.sup,850 Cc::new(self.map),851 Cc::new(self.assertions),852 ))853 }854}855impl Default for ObjValueBuilder {856 fn default() -> Self {857 Self::with_capacity(0)858 }859}860861#[allow(clippy::module_name_repetitions)]862#[must_use = "value not added unless binding() was called"]863pub struct ObjMemberBuilder<Kind> {864 kind: Kind,865 name: IStr,866 add: bool,867 visibility: Visibility,868 original_index: FieldIndex,869 location: Option<Span>,870}871872#[allow(clippy::missing_const_for_fn)]873impl<Kind> ObjMemberBuilder<Kind> {874 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {875 Self {876 kind,877 name,878 original_index,879 add: false,880 visibility: Visibility::Normal,881 location: None,882 }883 }884885 pub const fn with_add(mut self, add: bool) -> Self {886 self.add = add;887 self888 }889 pub fn add(self) -> Self {890 self.with_add(true)891 }892 pub fn with_visibility(mut self, visibility: Visibility) -> Self {893 self.visibility = visibility;894 self895 }896 pub fn hide(self) -> Self {897 self.with_visibility(Visibility::Hidden)898 }899 pub fn with_location(mut self, location: Span) -> Self {900 self.location = Some(location);901 self902 }903 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {904 (905 self.kind,906 self.name,907 ObjMember {908 flags: ObjFieldFlags::new(self.add, self.visibility),909 original_index: self.original_index,910 invoke: binding,911 location: self.location,912 },913 )914 }915}916917pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);918impl ObjMemberBuilder<ValueBuilder<'_>> {919 /// Inserts value, replacing if it is already defined920 pub fn value(self, value: impl Into<Val>) {921 let (receiver, name, member) =922 self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));923 let entry = receiver.0.map.entry(name);924 entry.insert_entry(member);925 }926927 /// Tries to insert value, returns an error if it was already defined928 pub fn try_value(self, value: impl Into<Val>) -> Result<()> {929 self.try_thunk(Thunk::evaluated(value.into()))930 }931 pub fn try_thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {932 self.binding(MaybeUnbound::Bound(value.into()))933 }934 pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {935 self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)))936 }937 pub fn binding(self, binding: MaybeUnbound) -> Result<()> {938 let (receiver, name, member) = self.build_member(binding);939 let location = member.location.clone();940 let old = receiver.0.map.insert(name.clone(), member);941 if old.is_some() {942 in_frame(943 CallLocation(location.as_ref()),944 || format!("field <{}> initializtion", name.clone()),945 || bail!(DuplicateFieldName(name.clone())),946 )?;947 }948 Ok(())949 }950}951952pub struct ExtendBuilder<'v>(&'v mut ObjValue);953impl ObjMemberBuilder<ExtendBuilder<'_>> {954 pub fn value(self, value: impl Into<Val>) {955 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));956 }957 pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {958 self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));959 }960 pub fn binding(self, binding: MaybeUnbound) {961 let (receiver, name, member) = self.build_member(binding);962 let new = receiver.0.clone();963 *receiver.0 = new.extend_with_raw_member(name, member);964 }965}crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -23,7 +23,7 @@
gc::WithCapacityExt as _,
manifest::{ManifestFormat, ToStringFormat},
typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},
- ObjValue, Result, Unbound, WeakObjValue,
+ ObjValue, Result, SupThis, Unbound, WeakSupThis,
};
pub trait ThunkValue: Trace {
@@ -167,8 +167,6 @@
Self::evaluated(T::default())
}
}
-
-type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);
#[derive(Trace, Clone)]
pub struct CachedUnbound<I, T>
@@ -176,7 +174,7 @@
I: Unbound<Bound = T>,
T: Trace,
{
- cache: Cc<RefCell<FxHashMap<CacheKey, T>>>,
+ cache: Cc<RefCell<FxHashMap<WeakSupThis, T>>>,
value: I,
}
impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {
@@ -189,17 +187,14 @@
}
impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {
type Bound = T;
- fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {
- let cache_key = (
- sup.as_ref().map(|s| s.clone().downgrade()),
- this.as_ref().map(|t| t.clone().downgrade()),
- );
+ fn bind(&self, sup_this: SupThis) -> Result<T> {
+ let cache_key = sup_this.clone().downgrade();
{
if let Some(t) = self.cache.borrow().get(&cache_key) {
return Ok(t.clone());
}
}
- let bound = self.value.bind(sup, this)?;
+ let bound = self.value.bind(sup_this)?;
{
let mut cache = self.cache.borrow_mut();
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,