git.delta.rocks / jrsonnet / refs/commits / faca88a40d97

difftreelog

refactor greately simplify object self/super implementation

xvonlxkpYaroslav Bolyukin2026-02-08parent: #1c69f1a.patch.diff
in: master

18 files changed

modifiedCargo.lockdiffbeforeafterboth
309source = "registry+https://github.com/rust-lang/crates.io-index"309source = "registry+https://github.com/rust-lang/crates.io-index"
310checksum = "9bda8e21c04aca2ae33ffc2fd8c23134f3cac46db123ba97bd9d3f3b8a4a85e1"310checksum = "9bda8e21c04aca2ae33ffc2fd8c23134f3cac46db123ba97bd9d3f3b8a4a85e1"
311
312[[package]]
313name = "educe"
314version = "0.6.0"
315source = "registry+https://github.com/rust-lang/crates.io-index"
316checksum = "1d7bc049e1bd8cdeb31b68bbd586a9464ecf9f3944af3958a7a9d0f8b9799417"
317dependencies = [
318 "enum-ordinalize",
319 "proc-macro2",
320 "quote",
321 "syn",
322]
311323
312[[package]]324[[package]]
313name = "either"325name = "either"
339 "encoding_rs",351 "encoding_rs",
340]352]
353
354[[package]]
355name = "enum-ordinalize"
356version = "4.3.2"
357source = "registry+https://github.com/rust-lang/crates.io-index"
358checksum = "4a1091a7bb1f8f2c4b28f1fe2cef4980ca2d410a3d727d67ecc3178c9b0800f0"
359dependencies = [
360 "enum-ordinalize-derive",
361]
362
363[[package]]
364name = "enum-ordinalize-derive"
365version = "4.3.2"
366source = "registry+https://github.com/rust-lang/crates.io-index"
367checksum = "8ca9601fb2d62598ee17836250842873a413586e5d7ed88b356e38ddbb0ec631"
368dependencies = [
369 "proc-macro2",
370 "quote",
371 "syn",
372]
341373
342[[package]]374[[package]]
343name = "equivalent"375name = "equivalent"
576dependencies = [608dependencies = [
577 "annotate-snippets",609 "annotate-snippets",
578 "anyhow",610 "anyhow",
611 "educe",
579 "hi-doc",612 "hi-doc",
580 "jrsonnet-gcmodule",613 "jrsonnet-gcmodule",
581 "jrsonnet-interner",614 "jrsonnet-interner",
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
57num-bigint = { workspace = true, features = ["serde"], optional = true }57num-bigint = { workspace = true, features = ["serde"], optional = true }
5858
59stacker = "0.1.23"59stacker = "0.1.23"
60educe = { version = "0.6.0", default-features = false, features = ["Clone", "Debug", "Eq", "Hash", "PartialEq"] }
6061
61[build-dependencies]62[build-dependencies]
62rustversion = "1.0.22"63rustversion = "1.0.22"
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
1use std::fmt::Debug;1use std::fmt::Debug;
22
3use educe::Educe;
3use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_gcmodule::{Cc, Trace};
4use jrsonnet_interner::IStr;5use jrsonnet_interner::IStr;
5use rustc_hash::FxHashMap;6use rustc_hash::FxHashMap;
67
7use crate::{8use crate::{
8 error::ErrorKind::*, gc::WithCapacityExt as _, map::LayeredHashMap, ObjValue, Pending, Result,9 error::ErrorKind::*, gc::WithCapacityExt as _, map::LayeredHashMap, ObjValue, Pending, Result,
9 Thunk, Val,10 SupThis, Thunk, Val,
10};11};
12/// Context keeps information about current lexical code location
13///
14/// This information includes local variables, top-level object (`$`), current object (`this`), and super object (`super`)
15#[derive(Debug, Trace, Clone, Educe)]
16#[educe(PartialEq)]
17pub struct Context(#[educe(PartialEq(method = Cc::ptr_eq))] Cc<ContextInternal>);
1118
12#[derive(Trace)]19#[derive(Debug, Trace)]
13struct ContextInternals {20struct ContextInternal {
14 dollar: Option<ObjValue>,21 dollar: Option<ObjValue>,
15 sup: Option<ObjValue>,22 sup_this: Option<SupThis>,
16 this: Option<ObjValue>,
17 bindings: LayeredHashMap,23 bindings: LayeredHashMap,
18}24}
19impl Debug for ContextInternals {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 f.debug_struct("Context").finish()
22 }
23}
24
25/// Context keeps information about current lexical code location
26///
27/// This information includes local variables, top-level object (`$`), current object (`this`), and super object (`super`)
28#[derive(Debug, Clone, Trace)]
29pub struct Context(Cc<ContextInternals>);
30impl Context {25impl Context {
31 pub fn new_future() -> Pending<Self> {26 pub fn new_future() -> Pending<Self> {
32 Pending::new()27 Pending::new()
36 self.0.dollar.as_ref()31 self.0.dollar.as_ref()
37 }32 }
33
34 pub fn try_dollar(&self) -> Result<ObjValue> {
35 self.0
36 .dollar
37 .clone()
38 .ok_or_else(|| CantUseSelfSupOutsideOfObject.into())
39 }
3840
39 pub fn this(&self) -> Option<&ObjValue> {41 pub fn this(&self) -> Option<&ObjValue> {
40 self.0.this.as_ref()42 self.0.sup_this.as_ref().map(SupThis::this)
41 }43 }
44
45 pub fn try_this(&self) -> Result<ObjValue> {
46 self.0
47 .sup_this
48 .as_ref()
49 .ok_or_else(|| CantUseSelfSupOutsideOfObject.into())
50 .map(SupThis::this)
51 .cloned()
52 }
4253
43 pub fn super_obj(&self) -> Option<&ObjValue> {54 pub fn sup_this(&self) -> Option<&SupThis> {
44 self.0.sup.as_ref()55 self.0.sup_this.as_ref()
45 }56 }
57
58 pub fn try_sup_this(&self) -> Result<SupThis> {
59 self.0
60 .sup_this
61 .clone()
62 .ok_or_else(|| CantUseSelfSupOutsideOfObject.into())
63 }
4664
47 pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {65 pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {
48 use std::cmp::Ordering;66 use std::cmp::Ordering;
83 pub fn with_var(self, name: impl Into<IStr>, value: Val) -> Self {101 pub fn with_var(self, name: impl Into<IStr>, value: Val) -> Self {
84 let mut new_bindings = FxHashMap::with_capacity(1);102 let mut new_bindings = FxHashMap::with_capacity(1);
85 new_bindings.insert(name.into(), Thunk::evaluated(value));103 new_bindings.insert(name.into(), Thunk::evaluated(value));
86 self.extend(new_bindings, None, None, None)104 self.extend_bindings(new_bindings)
87 }105 }
88106
89 #[must_use]107 #[must_use]
90 pub fn extend(108 pub fn extend_bindings_sup_this(
91 self,109 self,
92 new_bindings: FxHashMap<IStr, Thunk<Val>>,110 new_bindings: FxHashMap<IStr, Thunk<Val>>,
93 new_dollar: Option<ObjValue>,111 sup_this: SupThis,
94 new_sup: Option<ObjValue>,
95 new_this: Option<ObjValue>,
96 ) -> Self {112 ) -> Self {
97 let ctx = &self.0;113 let ctx = &self;
98 let dollar = new_dollar.or_else(|| ctx.dollar.clone());114 let dollar = ctx
99 let this = new_this.or_else(|| ctx.this.clone());115 .0
100 let sup = new_sup.or_else(|| ctx.sup.clone());116 .dollar
117 .clone()
118 .or_else(|| Some(sup_this.this().clone()));
101 let bindings = if new_bindings.is_empty() {119 let bindings = if new_bindings.is_empty() {
102 ctx.bindings.clone()120 ctx.0.bindings.clone()
103 } else {121 } else {
104 ctx.bindings.clone().extend(new_bindings)122 ctx.0.bindings.clone().extend(new_bindings)
105 };123 };
106 Self(Cc::new(ContextInternals {124 Self(Cc::new(ContextInternal {
107 dollar,125 dollar,
108 sup,126 sup_this: Some(sup_this),
109 this,
110 bindings,127 bindings,
111 }))128 }))
112 }129 }
130 #[must_use]
131 pub fn extend_bindings(self, new_bindings: FxHashMap<IStr, Thunk<Val>>) -> Self {
132 if new_bindings.is_empty() {
133 return self;
134 }
135 let ctx = &self;
136 let bindings = if new_bindings.is_empty() {
137 ctx.0.bindings.clone()
138 } else {
139 ctx.0.bindings.clone().extend(new_bindings)
140 };
141 Self(Cc::new(ContextInternal {
142 dollar: ctx.0.dollar.clone(),
143 sup_this: ctx.0.sup_this.clone(),
144 bindings,
145 }))
146 }
113}147}
114148
115impl PartialEq for Context {149#[derive(Default)]
116 fn eq(&self, other: &Self) -> bool {
117 Cc::ptr_eq(&self.0, &other.0)
118 }
119}
120
121pub struct ContextBuilder {150pub struct ContextBuilder {
122 bindings: FxHashMap<IStr, Thunk<Val>>,151 bindings: FxHashMap<IStr, Thunk<Val>>,
141 }172 }
173
142 /// # Panics174 /// # Panics
175 ///
143 /// If `name` is already bound176 /// If `name` is already bound. Makes no sense to bind same local multiple times,
177 /// unless it is separate context layers.
144 pub fn bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) -> &mut Self {178 pub fn bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) -> &mut Self {
145 let old = self.bindings.insert(name.into(), value);179 let old = self.bindings.insert(name.into(), value);
146 assert!(old.is_none(), "variable bound twice in single context call");180 assert!(old.is_none(), "variable bound twice in single context call");
147 self181 self
148 }182 }
149 pub fn build(self) -> Context {183 pub fn build(self) -> Context {
150 if let Some(parent) = self.extend {184 if let Some(parent) = self.extend {
151 // TODO: replace self.extend with Result<Context, State>, and remove `state` field
152 parent.extend(self.bindings, None, None, None)185 parent.extend_bindings(self.bindings)
153 } else {186 } else {
154 Context(Cc::new(ContextInternals {187 Context(Cc::new(ContextInternal {
155 bindings: LayeredHashMap::new(self.bindings),188 bindings: LayeredHashMap::new(self.bindings),
156 dollar: None,189 dollar: None,
157 sup: None,190 sup_this: None,
158 this: None,
159 }))191 }))
160 }192 }
161 }193 }
modifiedcrates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth
1use std::ptr::addr_of;
1use std::cell::OnceCell;2use std::{cell::OnceCell, hash::Hasher};
23
4use educe::Educe;
3use jrsonnet_gcmodule::{Cc, Trace};5use jrsonnet_gcmodule::{Cc, Trace};
46
5use crate::{bail, error::ErrorKind::InfiniteRecursionDetected, val::ThunkValue, Result};7use crate::{bail, error::ErrorKind::InfiniteRecursionDetected, val::ThunkValue, Result};
68
7// TODO: Replace with OnceCell once in std
8#[derive(Clone, Trace)]9#[derive(Trace, Educe)]
10#[educe(Clone)]
9pub struct Pending<V: Trace + 'static>(pub Cc<OnceCell<V>>);11pub struct Pending<V: Trace + 'static>(pub Cc<OnceCell<V>>);
10impl<T: Trace + 'static> Pending<T> {12impl<T: Trace + 'static> Pending<T> {
11 pub fn new() -> Self {13 pub fn new() -> Self {
25 .expect("wrapper is filled already");27 .expect("wrapper is filled already");
26 }28 }
27}29}
28impl<T: Clone + Trace + 'static> Pending<T> {30impl<T: Trace + 'static + Clone> Pending<T> {
29 /// # Panics31 /// # Panics
30 /// If wrapper is not yet filled32 /// If wrapper is not yet filled
31 pub fn unwrap(&self) -> T {33 pub fn unwrap(&self) -> T {
53 }55 }
54}56}
57
58pub fn identity_hash<T, H: Hasher>(v: &Cc<T>, hasher: &mut H) {
59 hasher.write_usize(addr_of!(**v) as usize);
60}
5561
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
119 #[error("binary operation {1} {0} {2} is not implemented")]119 #[error("binary operation {1} {0} {2} is not implemented")]
120 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),120 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),
121121
122 #[error("no top level object in this context")]
123 NoTopLevelObjectFound,
124 #[error("self is only usable inside objects")]122 #[error("self/super/$ are only usable inside objects")]
125 CantUseSelfOutsideOfObject,123 CantUseSelfSupOutsideOfObject,
126 #[error("no super found")]124 #[error("no super found")]
127 NoSuperFound,125 NoSuperFound,
128126
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
1111
12use self::destructure::destruct;12use self::destructure::destruct;
13use crate::{13use crate::{
14 arr::ArrValue,14 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
15 bail,
16 destructure::evaluate_dest,
17 error::{suggest_object_fields, ErrorKind::*},
18 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
19 function::{CallLocation, FuncDesc, FuncVal},
20 gc::WithCapacityExt as _,
21 in_frame,
22 typed::Typed,
23 val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
24 Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt,
25 Unbound, Val,
26};15};
27pub mod destructure;16pub mod destructure;
28pub mod operator;17pub mod operator;
126 let fctx = Pending::new();115 let fctx = Pending::new();
127 let mut new_bindings = FxHashMap::with_capacity(var.capacity_hint());116 let mut new_bindings = FxHashMap::with_capacity(var.capacity_hint());
128 destruct(var, item, fctx.clone(), &mut new_bindings)?;117 destruct(var, item, fctx.clone(), &mut new_bindings)?;
129 let ctx = ctx118 let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);
130 .clone()
131 .extend(new_bindings, None, None, None)
132 .into_future(fctx);
133119
134 evaluate_comp(ctx, &specs[1..], callback)?;120 evaluate_comp(ctx, &specs[1..], callback)?;
169impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}155impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}
170156
171fn evaluate_object_locals(157fn evaluate_object_locals(
172 fctx: Pending<Context>,158 fctx: Context,
173 locals: Rc<Vec<BindSpec>>,159 locals: Rc<Vec<BindSpec>>,
174) -> impl CloneableUnbound<Context> {160) -> impl CloneableUnbound<Context> {
175 #[derive(Trace, Clone)]161 #[derive(Trace, Clone)]
176 struct UnboundLocals {162 struct UnboundLocals {
177 fctx: Pending<Context>,163 fctx: Context,
178 locals: Rc<Vec<BindSpec>>,164 locals: Rc<Vec<BindSpec>>,
179 }165 }
180 impl Unbound for UnboundLocals {166 impl Unbound for UnboundLocals {
181 type Bound = Context;167 type Bound = Context;
182168
183 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {169 fn bind(&self, sup_this: SupThis) -> Result<Context> {
184 let fctx = Context::new_future();170 let fctx = Context::new_future();
185 let mut new_bindings =171 let mut new_bindings =
186 FxHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());172 FxHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());
187 for b in self.locals.iter() {173 for b in self.locals.iter() {
188 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;174 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
189 }175 }
190176
191 let ctx = self.fctx.unwrap();177 let ctx = self.fctx.clone();
192 let new_dollar = ctx.dollar().cloned().or_else(|| this.clone());
193178
194 let ctx = ctx179 let ctx = ctx
195 .extend(new_bindings, new_dollar, sup, this)180 .extend_bindings_sup_this(new_bindings, sup_this)
196 .into_future(fctx);181 .into_future(fctx);
197182
198 Ok(ctx)183 Ok(ctx)
229 }214 }
230 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {215 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {
231 type Bound = Val;216 type Bound = Val;
232 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {217 fn bind(&self, sup_this: SupThis) -> Result<Val> {
233 evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())218 evaluate_named(self.uctx.bind(sup_this)?, &self.value, self.name.clone())
234 }219 }
235 }220 }
236221
260 }245 }
261 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {246 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {
262 type Bound = Val;247 type Bound = Val;
263 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {248 fn bind(&self, sup_this: SupThis) -> Result<Val> {
264 Ok(evaluate_method(249 Ok(evaluate_method(
265 self.uctx.bind(sup, this)?,250 self.uctx.bind(sup_this)?,
266 self.name.clone(),251 self.name.clone(),
267 self.params.clone(),252 self.params.clone(),
268 self.value.clone(),253 self.value.clone(),
298 .collect::<Vec<_>>(),283 .collect::<Vec<_>>(),
299 );284 );
300
301 let fctx = Context::new_future();
302285
303 // We have single context for all fields, so we can cache binds286 // We have single context for all fields, so we can cache binds
304 let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));287 let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));
305288
306 for member in members {289 for member in members {
307 match member {290 match member {
315 assert: AssertStmt,298 assert: AssertStmt,
316 }299 }
317 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {300 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {
318 fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {301 fn run(&self, sup_this: SupThis) -> Result<()> {
319 let ctx = self.uctx.bind(sup, this)?;302 let ctx = self.uctx.bind(sup_this)?;
320 evaluate_assert(ctx, &self.assert)303 evaluate_assert(ctx, &self.assert)
321 }304 }
322 }305 }
330 }313 }
331 }314 }
332 }315 }
333 let this = builder.build();316 Ok(builder.build())
334 fctx.fill(ctx.extend(FxHashMap::new(), None, None, Some(this.clone())));
335 Ok(this)
336}317}
337318
338pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {319pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {
347 .cloned()328 .cloned()
348 .collect::<Vec<_>>(),329 .collect::<Vec<_>>(),
349 );330 );
350 let mut ctxs = vec![];
351 evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {331 evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {
352 let fctx = Context::new_future();332 let uctx = evaluate_object_locals(ctx.clone(), locals.clone());
353 ctxs.push((ctx.clone(), fctx.clone()));
354 let uctx = evaluate_object_locals(fctx, locals.clone());
355333
356 evaluate_field_member(&mut builder, ctx, uctx, &obj.field)334 evaluate_field_member(&mut builder, ctx, uctx, &obj.field)
357 })?;335 })?;
358336
359 let this = builder.build();337 builder.build()
360 for (ctx, fctx) in ctxs {
361 let _ctx = ctx
362 .extend(FxHashMap::new(), None, None, Some(this.clone()))
363 .into_future(fctx);
364 }
365 this
366 }338 }
367 })339 })
368}340}
428 }400 }
429 let loc = expr.span();401 let loc = expr.span();
430 Ok(match expr.expr() {402 Ok(match expr.expr() {
431 Literal(LiteralType::This) => {403 Literal(LiteralType::This) => Val::Obj(ctx.try_this()?),
432 Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())
433 }
434 Literal(LiteralType::Super) => Val::Obj(404 Literal(LiteralType::Super) => Val::Obj(ctx.try_sup_this()?.standalone_super()?),
435 ctx.super_obj().ok_or(NoSuperFound)?.with_this(
436 ctx.this()
437 .expect("if super exists - then this should too")
438 .clone(),
439 ),
440 ),
441 Literal(LiteralType::Dollar) => {405 Literal(LiteralType::Dollar) => Val::Obj(ctx.try_dollar()?),
442 Val::Obj(ctx.dollar().ok_or(NoTopLevelObjectFound)?.clone())
443 }
444 Literal(LiteralType::True) => Val::Bool(true),406 Literal(LiteralType::True) => Val::Bool(true),
445 Literal(LiteralType::False) => Val::Bool(false),407 Literal(LiteralType::False) => Val::Bool(false),
446 Literal(LiteralType::Null) => Val::Null,408 Literal(LiteralType::Null) => Val::Null,
452 //414 //
453 // Note that other jsonnet implementations will fail on `if value in (super)` expression,415 // Note that other jsonnet implementations will fail on `if value in (super)` expression,
454 // because the standalone super literal is not supported, that is because in other416 // because the standalone super literal is not supported, that is because in other
455 // implementations `in super` treated differently from in `smth_else`.417 // implementations `in super` treated differently from `in smth_else`.
456 BinaryOp(field, BinaryOpType::In, e)418 BinaryOp(field, BinaryOpType::In, e)
457 if matches!(e.expr(), Expr::Literal(LiteralType::Super)) =>419 if matches!(e.expr(), Expr::Literal(LiteralType::Super)) =>
458 {420 {
459 let Some(super_obj) = ctx.super_obj() else {421 let sup_this = ctx.try_sup_this()?;
422 // In jsonnet, "field" in e is eager, LHS expression is always executed regardless of super existence.
423 // In jrsonnet, however, this wasn't true, this was kept here for compatibility.
424 if !sup_this.has_super() {
460 return Ok(Val::Bool(false));425 return Ok(Val::Bool(false));
461 };426 }
462 let field = evaluate(ctx.clone(), field)?;427 let field = evaluate(ctx, field)?;
463 Val::Bool(super_obj.has_field_ex(field.to_string()?, true))428 Val::Bool(sup_this.field_in_super(field.to_string()?))
464 }429 }
465 BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,430 BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
466 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,431 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
473 let mut parts = parts.iter();438 let mut parts = parts.iter();
474 let mut indexable = if matches!(indexable.expr(), Expr::Literal(LiteralType::Super)) {439 let mut indexable = if matches!(indexable.expr(), Expr::Literal(LiteralType::Super)) {
475 let part = parts.next().expect("at least part should exist");440 let part = parts.next().expect("at least part should exist");
441 // sup_this existence check might also be skipped here for null-coalesce...
442 // But I believe this might cause errors.
476 let Some(super_obj) = ctx.super_obj() else {443 let sup_this = ctx.try_sup_this()?;
444 if !sup_this.has_super() {
477 #[cfg(feature = "exp-null-coaelse")]445 #[cfg(feature = "exp-null-coaelse")]
478 if part.null_coaelse {446 if part.null_coaelse {
479 return Ok(Val::Null);447 return Ok(Val::Null);
480 }448 }
481 bail!(NoSuperFound)449 bail!(NoSuperFound)
482 };450 }
483 let name = evaluate(ctx.clone(), &part.value)?;451 let name = evaluate(ctx.clone(), &part.value)?;
484452
485 let Val::Str(name) = name else {453 let Val::Str(name) = name else {
490 ))458 ))
491 };459 };
492460
493 let this = ctx
494 .this()
495 .expect("no this found, while super present, should not happen");
496 let name = name.into_flat();461 let name = name.into_flat();
497 match super_obj462 match sup_this
498 .get_for(name.clone(), this.clone())463 .get_super(name.clone())
499 .with_description_src(&part.value, || format!("field <{name}> access"))?464 .with_description_src(&part.value, || format!("field <{name}> access"))?
500 {465 {
501 Some(v) => v,466 Some(v) => v,
502 #[cfg(feature = "exp-null-coaelse")]467 #[cfg(feature = "exp-null-coaelse")]
503 None if part.null_coaelse => return Ok(Val::Null),468 None if part.null_coaelse => return Ok(Val::Null),
504 None => {469 None => {
505 let suggestions = suggest_object_fields(super_obj, name.clone());470 let suggestions = suggest_object_fields(
471 &sup_this.standalone_super().expect("super exists"),
472 name.clone(),
473 );
506474
507 bail!(NoSuchField(name, suggestions))475 bail!(NoSuchField(name, suggestions))
589 for b in bindings {557 for b in bindings {
590 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;558 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
591 }559 }
592 let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);560 let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);
593 evaluate(ctx, &returned.clone())?561 evaluate(ctx, &returned.clone())?
594 }562 }
595 Arr(items) => {563 Arr(items) => {
652 Slice(value, desc) => {620 Slice(value, desc) => {
653 fn parse_idx<T: Typed>(621 fn parse_idx<T: Typed>(
654 loc: CallLocation<'_>,622 loc: CallLocation<'_>,
655 ctx: &Context,623 ctx: Context,
656 expr: Option<&LocExpr>,624 expr: Option<&LocExpr>,
657 desc: &'static str,625 desc: &'static str,
658 ) -> Result<Option<T>> {626 ) -> Result<Option<T>> {
659 if let Some(value) = expr {627 if let Some(value) = expr {
660 Ok(in_frame(628 Ok(in_frame(
661 loc,629 loc,
662 || format!("slice {desc}"),630 || format!("slice {desc}"),
663 || <Option<T>>::from_untyped(evaluate(ctx.clone(), value)?),631 || <Option<T>>::from_untyped(evaluate(ctx, value)?),
664 )?)632 )?)
665 } else {633 } else {
666 Ok(None)634 Ok(None)
670 let indexable = evaluate(ctx.clone(), value)?;638 let indexable = evaluate(ctx.clone(), value)?;
671 let loc = CallLocation::new(&loc);639 let loc = CallLocation::new(&loc);
672640
673 let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;641 let start = parse_idx(loc, ctx.clone(), desc.start.as_ref(), "start")?;
674 let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;642 let end = parse_idx(loc, ctx.clone(), desc.end.as_ref(), "end")?;
675 let step = parse_idx(loc, &ctx, desc.step.as_ref(), "step")?;643 let step = parse_idx(loc, ctx, desc.step.as_ref(), "step")?;
676644
677 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?645 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?
678 }646 }
681 bail!("computed imports are not supported")649 bail!("computed imports are not supported")
682 };650 };
683 let tmp = loc.clone().0;651 let tmp = loc.clone().0;
684 let s = ctx.state();652 with_state(|s| {
685 let resolved_path = s.resolve_from(tmp.source_path(), path)?;653 let resolved_path = s.resolve_from(tmp.source_path(), path)?;
686 match i {654 Ok(match i {
687 Import(_) => in_frame(655 Import(_) => in_frame(
688 CallLocation::new(&loc),656 CallLocation::new(&loc),
689 || format!("import {:?}", path.clone()),657 || format!("import {:?}", path.clone()),
690 || s.import_resolved(resolved_path),658 || s.import_resolved(resolved_path),
691 )?,659 )?,
692 ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),660 ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),
693 ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),661 ImportBin(_) => {
662 Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?))
663 }
694 _ => unreachable!(),664 _ => unreachable!(),
695 }665 }) as Result<Val>
666 })?
696 }667 }
697 })668 })
698}669}
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
40}40}
4141
42/// Represents Jsonnet function defined in code.42/// Represents Jsonnet function defined in code.
43#[derive(Debug, PartialEq, Trace)]43#[derive(Debug, Trace, PartialEq)]
44pub struct FuncDesc {44pub struct FuncDesc {
45 /// # Example45 /// # Example
46 ///46 ///
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
129 }129 }
130130
131 Ok(body_ctx131 Ok(body_ctx
132 .extend(passed_args, None, None, None)132 .extend_bindings(passed_args)
133 .extend(defaults, None, None, None)133 .extend_bindings(defaults)
134 .into_future(fctx))134 .into_future(fctx))
135 } else {135 } else {
136 let body_ctx = body_ctx.extend(passed_args, None, None, None);136 let body_ctx = body_ctx.extend_bindings(passed_args);
137 Ok(body_ctx)137 Ok(body_ctx)
138 }138 }
139}139}
257 }257 }
258 }258 }
259259
260 Ok(body_ctx260 Ok(body_ctx.extend_bindings(bindings).into_future(fctx))
261 .extend(bindings, None, None, None)
262 .into_future(fctx))
263}261}
264262
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
28 any::Any,28 any::Any,
29 cell::{RefCell, RefMut},29 cell::{RefCell, RefMut},
30 collections::hash_map::Entry,30 collections::hash_map::Entry,
31 clone::Clone,
31 fmt::{self, Debug},32 fmt::{self, Debug},
32 rc::Rc,33 rc::Rc,
34 marker::PhantomData,
33};35};
3436
35pub use ctx::*;37pub use ctx::*;
65 /// Type of value after object context is bound67 /// Type of value after object context is bound
66 type Bound;68 type Bound;
67 /// Create value bound to specified object context69 /// Create value bound to specified object context
68 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;70 fn bind(&self, sup_this: SupThis) -> Result<Self::Bound>;
69}71}
7072
71/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code73/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code
85}87}
86impl MaybeUnbound {88impl MaybeUnbound {
87 /// Attach object context to value, if required89 /// Attach object context to value, if required
88 pub fn evaluate(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {90 pub fn evaluate(&self, sup_this: SupThis) -> Result<Val> {
89 match self {91 match self {
90 Self::Unbound(v) => v.0.bind(sup, this),92 Self::Unbound(v) => v.0.bind(sup_this),
91 Self::Bound(v) => Ok(v.evaluate()?),93 Self::Bound(v) => Ok(v.evaluate()?),
92 }94 }
93 }95 }
105 /// Initialize default file context.107 /// Initialize default file context.
106 /// Has default implementation, which calls `populate`.108 /// Has default implementation, which calls `populate`.
107 /// Prefer to always implement `populate` instead.109 /// Prefer to always implement `populate` instead.
108 fn initialize(&self, state: State, for_file: Source) -> Context {110 fn initialize(&self, for_file: Source) -> Context {
109 let mut builder = ContextBuilder::with_capacity(state, self.reserve_vars());111 let mut builder = ContextBuilder::with_capacity(self.reserve_vars());
110 self.populate(for_file, &mut builder);112 self.populate(for_file, &mut builder);
111 builder.build()113 builder.build()
112 }114 }
130where132where
131 T: ContextInitializer,133 T: ContextInitializer,
132{134{
133 fn initialize(&self, state: State, for_file: Source) -> Context {135 fn initialize(&self, for_file: Source) -> Context {
134 if let Some(ctx) = self {136 if let Some(ctx) = self {
135 ctx.initialize(state, for_file)137 ctx.initialize(for_file)
136 } else {138 } else {
137 ().initialize(state, for_file)139 ().initialize(for_file)
138 }140 }
139 }141 }
140142
237#[derive(Clone, Trace)]239#[derive(Clone, Trace)]
238pub struct State(Cc<EvaluationStateInternals>);240pub struct State(Cc<EvaluationStateInternals>);
241
242thread_local! {
243 pub static DEFAULT_STATE: State = State::builder().build();
244 pub static STATE: RefCell<Option<State>> = const {RefCell::new(None)};
245}
246pub struct StateEnterGuard(PhantomData<()>);
247impl Drop for StateEnterGuard {
248 fn drop(&mut self) {
249 STATE.with_borrow_mut(|v| *v = None);
250 }
251}
252
253pub fn with_state<V>(v: impl FnOnce(State) -> V) -> V {
254 if let Some(state) = STATE.with_borrow(Clone::clone) {
255 v(state)
256 } else {
257 let s = DEFAULT_STATE.with(Clone::clone);
258 v(s)
259 }
260}
239261
240impl State {262impl State {
263 pub fn enter(&self) -> StateEnterGuard {
264 self.try_enter().expect("entered state already exists")
265 }
266 pub fn try_enter(&self) -> Option<StateEnterGuard> {
267 STATE.with_borrow_mut(|v| {
268 if v.is_none() {
269 *v = Some(self.clone());
270 Some(StateEnterGuard(PhantomData))
271 } else {
272 None
273 }
274 })
275 }
241 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise276 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise
242 pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {277 pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {
243 let mut file_cache = self.file_cache();278 let mut file_cache = self.file_cache();
359394
360 /// Creates context with all passed global variables395 /// Creates context with all passed global variables
361 pub fn create_default_context(&self, source: Source) -> Context {396 pub fn create_default_context(&self, source: Source) -> Context {
362 self.context_initializer().initialize(self.clone(), source)397 self.context_initializer().initialize(source)
363 }398 }
364399
365 /// Creates context with all passed global variables, calling custom modifier400 /// Creates context with all passed global variables, calling custom modifier
370 ) -> Context {405 ) -> Context {
371 let default_initializer = self.context_initializer();406 let default_initializer = self.context_initializer();
372 let mut builder = ContextBuilder::with_capacity(407 let mut builder = ContextBuilder::with_capacity(
373 self.clone(),
374 default_initializer.reserve_vars() + context_initializer.reserve_vars(),408 default_initializer.reserve_vars() + context_initializer.reserve_vars(),
375 );409 );
376 default_initializer.populate(source.clone(), &mut builder);410 default_initializer.populate(source.clone(), &mut builder);
modifiedcrates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth
44
5use crate::{gc::WithCapacityExt as _, Thunk, Val};5use crate::{gc::WithCapacityExt as _, Thunk, Val};
66
7#[derive(Trace)]7#[derive(Trace, Debug)]
8#[trace(tracking(force))]8#[trace(tracking(force))]
9pub struct LayeredHashMapInternals {9pub struct LayeredHashMapInternals {
10 parent: Option<LayeredHashMap>,10 parent: Option<LayeredHashMap>,
11 current: FxHashMap<IStr, Thunk<Val>>,11 current: FxHashMap<IStr, Thunk<Val>>,
12}12}
1313
14#[derive(Trace)]14#[derive(Trace, Debug)]
15pub struct LayeredHashMap(Cc<LayeredHashMapInternals>);15pub struct LayeredHashMap(Cc<LayeredHashMapInternals>);
1616
17impl LayeredHashMap {17impl LayeredHashMap {
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
1use std::{1use std::{
2 any::Any,2 any::Any, cell::{Cell, RefCell}, collections::hash_map::Entry, fmt::{self, Debug}, hash::{Hash, Hasher}
3 cell::RefCell,
4 fmt::Debug,
5 hash::{Hash, Hasher},
6 ptr::addr_of,
7};3};
84
9use jrsonnet_gcmodule::{cc_dyn, Cc, Trace, Weak};5use jrsonnet_gcmodule::{cc_dyn, Cc, Trace, Weak};
6use educe::Educe;
10use jrsonnet_interner::IStr;7use jrsonnet_interner::IStr;
11use jrsonnet_parser::{Span, Visibility};8use jrsonnet_parser::{Span, Visibility};
12use rustc_hash::{FxHashMap, FxHashSet};9use rustc_hash::{FxHashMap, FxHashSet};
1310
14use crate::{11use crate::{
15 arr::{PickObjectKeyValues, PickObjectValues},12 arr::{PickObjectKeyValues, PickObjectValues},
16 bail,13 bail,
17 error::{suggest_object_fields, Error, ErrorKind::*},14 error::{suggest_object_fields, ErrorKind::*},
18 function::{CallLocation, FuncVal},15 function::{CallLocation, FuncVal},
19 gc::WithCapacityExt as _,16 gc::WithCapacityExt as _,
20 in_frame,17 in_frame,
18 identity_hash,
21 operator::evaluate_add_op,19 operator::evaluate_add_op,
22 val::ArrValue,20 val::ArrValue,
23 CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,21 CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
43 #[derive(Clone, Copy, Default, Debug, Trace)]41 #[derive(Clone, Copy, Default, Debug, Trace)]
44 pub struct SuperDepth(());42 pub struct SuperDepth(());
45 impl SuperDepth {43 impl SuperDepth {
46 pub const fn deeper(self) -> Self {44 pub(super) fn deepen(self) {}
47 Self(())
48 }
49 }45 }
5046
51 #[derive(Clone, Copy)]47 #[derive(Clone, Copy, Debug)]
52 pub struct FieldSortKey(());48 pub struct FieldSortKey(());
53 impl FieldSortKey {49 impl FieldSortKey {
54 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {50 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {
74 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]70 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]
75 pub struct SuperDepth(u32);71 pub struct SuperDepth(u32);
76 impl SuperDepth {72 impl SuperDepth {
77 pub fn deeper(self) -> Self {73 pub(super) fn deepen(&mut self) {
78 Self(self.0 + 1)74 *self.0 += 1
79 }75 }
80 }76 }
8177
120 }116 }
121}117}
122impl Debug for ObjFieldFlags {118impl Debug for ObjFieldFlags {
123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.debug_struct("ObjFieldFlags")120 f.debug_struct("ObjFieldFlags")
125 .field("add", &self.add())121 .field("add", &self.add())
126 .field("visibility", &self.visibility())122 .field("visibility", &self.visibility())
140136
141cc_dyn!(CcObjectAssertion, ObjectAssertion);137cc_dyn!(CcObjectAssertion, ObjectAssertion);
142pub trait ObjectAssertion: Trace {138pub trait ObjectAssertion: Trace {
143 fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;139 fn run(&self, sup_this: SupThis) -> Result<()>;
144}140}
145141
146// Field => This142// Field => This
147143
148#[derive(Trace)]144#[derive(Trace, Debug)]
149enum CacheValue {145enum CacheValue {
150 Cached(Val),146 Cached(Result<Option<Val>>),
151 NotFound,
152 Pending,147 Pending,
153 Errored(Error),
154}148}
155149
156#[allow(clippy::module_name_repetitions)]150#[allow(clippy::module_name_repetitions)]
157#[derive(Trace)]151#[derive(Trace)]
158#[trace(tracking(force))]152#[trace(tracking(force))]
159pub struct OopObject {153pub struct OopObject {
160 sup: Option<ObjValue>,
161 // this: Option<ObjValue>,154 // this: Option<ObjValue>,
162 assertions: Cc<Vec<CcObjectAssertion>>,155 assertions: Cc<Vec<CcObjectAssertion>>,
163 assertions_ran: RefCell<FxHashSet<ObjValue>>,
164 this_entries: Cc<FxHashMap<IStr, ObjMember>>,156 this_entries: Cc<FxHashMap<IStr, ObjMember>>,
165 value_cache: RefCell<FxHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,157 value_cache: RefCell<FxHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,
166}158}
167impl Debug for OopObject {159impl Debug for OopObject {
168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {160 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169 f.debug_struct("OopObject")161 f.debug_struct("OopObject")
170 .field("sup", &self.sup)
171 // .field("assertions", &self.assertions)162 // .field("assertions", &self.assertions)
172 // .field("assertions_ran", &self.assertions_ran)163 // .field("assertions_ran", &self.assertions_ran)
173 .field("this_entries", &self.this_entries)164 .field("this_entries", &self.this_entries)
178169
179type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;170type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;
180171
181pub trait ObjectLike: Trace + Any + Debug {
182 fn extend_from(&self, sup: ObjValue) -> ObjValue;172#[derive(Trace, Clone)]
183 /// When using standalone super in object, `this.super_obj.with_this(this)` is executed173pub enum ValueProcess {
184 fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {
185 ObjValue::new(ThisOverride { inner: me, this })174 None,
186 }
187 fn this(&self) -> Option<ObjValue> {
188 None
189 }
190 fn len(&self) -> usize;
191 fn is_empty(&self) -> bool;
192 // If callback returns false, iteration stops
193 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;175 SuperPlus,
176}
194177
178pub trait ObjectCore: Trace + Any + Debug {
179 // If callback returns false, iteration stops, and this call returns false.
180 fn enum_fields_core(
181 &self,
182 super_depth: &mut SuperDepth,
183 handler: &mut EnumFieldsHandler<'_>,
184 ) -> bool;
185
195 fn has_field_include_hidden(&self, name: IStr) -> bool;186 fn has_field_include_hidden(&self, name: IStr) -> bool;
196 fn has_field(&self, name: IStr) -> bool;
197187
198 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;188 fn get_for(&self, key: IStr, sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>>;
199 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;189 // fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<(Val, ValueProcess)>>;
200 fn field_visibility(&self, field: IStr) -> Option<Visibility>;190 fn field_visibility(&self, field: IStr) -> Option<Visibility>;
201191
202 fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;192 fn run_assertions_raw(&self, sup_this: SupThis) -> Result<()>;
203}193}
204194
205#[derive(Clone, Trace)]195#[derive(Clone, Trace)]
206pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<dyn ObjectLike>);196pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);
197impl Debug for WeakObjValue {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 f.debug_tuple("WeakObjValue").finish()
200 }
201}
207202
208impl PartialEq for WeakObjValue {203impl PartialEq for WeakObjValue {
209 fn eq(&self, other: &Self) -> bool {204 fn eq(&self, other: &Self) -> bool {
222217
223cc_dyn!(218cc_dyn!(
224 #[derive(Clone, Debug)]219 #[derive(Clone, Debug)]
225 ObjValue, ObjectLike,220 ObjCore, ObjectCore,
226 pub fn new() {...}221 pub fn new() {...}
227);222);
223#[derive(Trace, Educe)]
224#[educe(Debug)]
225struct ObjValueInner {
226 cores: Vec<ObjCore>,
227 assertions_ran: Cell<bool>,
228 value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,
229}
228230
231thread_local! {
232 static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();
233}
234fn is_asserting(obj: &ObjValue) -> bool {
235 RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))
236}
237/// Returns false if already asserting
238fn start_asserting(obj: &ObjValue) -> bool {
239 RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))
240}
241fn finish_asserting(obj: &ObjValue) {
242 RUNNING_ASSERTIONS.with_borrow_mut(|v| {
243 let r = v.remove(obj);
244 debug_assert!(
245 r,
246 "finish_asserting was called before start_asserting or twice"
247 );
248 });
249}
250
229#[derive(Debug, Trace)]251#[allow(clippy::module_name_repetitions)]
252#[derive(Clone, Trace, Debug, Educe)]
253#[educe(PartialEq, Hash, Eq)]
230struct EmptyObject;254pub struct ObjValue(
255 #[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,
256);
257
258#[derive(Trace, Debug)]
259struct StandaloneSuperCore {
260 sup: CoreIdx,
261 this: ObjValue,
262}
231impl ObjectLike for EmptyObject {263impl ObjectCore for StandaloneSuperCore {
232 fn extend_from(&self, sup: ObjValue) -> ObjValue {264 fn enum_fields_core(
265 &self,
266 super_depth: &mut SuperDepth,
267 handler: &mut EnumFieldsHandler<'_>,
268 ) -> bool {
233 // obj + {} == obj269 self.this
234 sup270 .enum_fields_internal(super_depth, handler, self.sup)
235 }271 }
236272
237 fn this(&self) -> Option<ObjValue> {273 fn has_field_include_hidden(&self, name: IStr) -> bool {
238 None274 self.this.has_field_include_hidden_idx(name, self.sup)
239 }275 }
240276
241 fn len(&self) -> usize {277 fn get_for(&self, key: IStr, _sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
242 0278 let v = self.this.get_idx(key, self.sup)?;
279 Ok(v.map(|v| (v, ValueProcess::None)))
243 }280 }
244281
245 fn is_empty(&self) -> bool {282 fn field_visibility(&self, field: IStr) -> Option<Visibility> {
246 true283 self.this.field_visibility_idx(field, self.sup)
247 }284 }
248285
249 fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {286 fn run_assertions_raw(&self, _sup_this: SupThis) -> Result<()> {
250 false287 self.this.run_assertions()
251 }288 }
289}
252290
291#[derive(Debug, Trace)]
292struct EmptyObject;
293impl ObjectCore for EmptyObject {
253 fn has_field_include_hidden(&self, _name: IStr) -> bool {294 fn enum_fields_core(
295 &self,
296 _super_depth: &mut SuperDepth,
297 _handler: &mut EnumFieldsHandler<'_>,
298 ) -> bool {
254 false299 true
255 }300 }
256301
257 fn has_field(&self, _name: IStr) -> bool {302 fn has_field_include_hidden(&self, _name: IStr) -> bool {
258 false303 false
259 }304 }
260305
261 fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {306 fn get_for(&self, _key: IStr, _sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
262 Ok(None)307 Ok(None)
263 }308 }
264 fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {
265 Ok(None)
266 }
267309
268 fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {310 fn run_assertions_raw(&self, _sup_this: SupThis) -> Result<()> {
269 Ok(())311 Ok(())
270 }312 }
271313
274 }316 }
275}317}
276318
277#[derive(Trace, Debug)]319#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]
320struct CoreIdx {
321 idx: usize,
322}
323impl CoreIdx {
324 fn super_exists(self) -> bool {
325 self.idx != 0
326 }
327}
328#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]
278struct ThisOverride {329pub struct SupThis {
279 inner: ObjValue,330 sup: CoreIdx,
280 this: ObjValue,331 this: ObjValue,
281}332}
282impl ObjectLike for ThisOverride {333impl SupThis {
283 fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {334 pub fn has_super(&self) -> bool {
284 ObjValue::new(Self {335 self.sup.super_exists()
285 inner: self.inner.clone(),
286 this,
287 })
288 }336 }
289337 /// Implementation of `"field" in super` operation,
290 fn extend_from(&self, sup: ObjValue) -> ObjValue {338 /// works faster than standalone super path.
339 ///
340 /// In case of no `super` existence, returns false.
341 pub fn field_in_super(&self, field: IStr) -> bool {
291 self.inner.extend_from(sup).with_this(self.this.clone())342 self.this.has_field_include_hidden_idx(field, self.sup)
292 }343 }
293344 /// Implementation of `super.field` operation,
294 fn this(&self) -> Option<ObjValue> {345 /// works faster than standalone super path.
346 ///
347 /// In case of no `super` existence, returns `NoSuperFound`
348 pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {
295 Some(self.this.clone())349 if !self.sup.super_exists() {
350 bail!(NoSuperFound);
351 }
352 self.this.get_idx(field, self.sup)
296 }353 }
297354 /// `super` with `self` overriden for top-level lookups.
298 fn len(&self) -> usize {355 /// Exists when super appears outside of `super.field`/`"field" in super` expressions
356 /// Exclusive to jrsonnet.
357 ///
358 /// Might return `NoSuperFound` error.
359 pub fn standalone_super(&self) -> Result<ObjValue> {
299 self.inner.len()360 if !self.sup.super_exists() {
361 bail!(NoSuperFound)
362 }
363 Ok(ObjValue::new(StandaloneSuperCore {
364 sup: self.sup,
365 this: self.this.clone(),
366 }))
300 }367 }
301
302 fn is_empty(&self) -> bool {368 pub fn this(&self) -> &ObjValue {
303 self.inner.is_empty()369 &self.this
304 }370 }
305
306 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {371 pub fn downgrade(self) -> WeakSupThis {
307 self.inner.enum_fields(depth, handler)372 WeakSupThis {
373 sup: self.sup,
374 this: self.this.downgrade(),
375 }
308 }376 }
309
310 fn has_field_include_hidden(&self, name: IStr) -> bool {
311 self.inner.has_field_include_hidden(name)
312 }
313
314 fn has_field(&self, name: IStr) -> bool {
315 self.inner.has_field(name)
316 }
317
318 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
319 self.inner.get_for(key, this)
320 }
321
322 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
323 self.inner.get_raw(key, this)
324 }
325
326 fn field_visibility(&self, field: IStr) -> Option<Visibility> {
327 self.inner.field_visibility(field)
328 }
329
330 fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {
331 self.inner.run_assertions_raw(this)
332 }
333}377}
378#[derive(Trace, PartialEq, Eq, Hash, Debug)]
379pub struct WeakSupThis {
380 sup: CoreIdx,
381 this: WeakObjValue,
382}
334383
335impl ObjValue {384impl ObjValue {
385 pub fn new(v: impl ObjectCore) -> Self {
386 Self(Cc::new(ObjValueInner {
387 cores: vec![ObjCore::new(v)],
388 assertions_ran: Cell::new(false),
389 value_cache: RefCell::new(FxHashMap::new()),
390 }))
391 }
336 pub fn new_empty() -> Self {392 pub fn new_empty() -> Self {
337 Self::new(EmptyObject)393 Self::new(EmptyObject)
338 }394 }
363419
364 #[must_use]420 #[must_use]
365 pub fn extend_from(&self, sup: Self) -> Self {421 pub fn extend_from(&self, sup: Self) -> Self {
366 self.0.extend_from(sup)422 let mut cores = sup.0.cores.clone();
423 cores.extend(self.0.cores.iter().cloned());
424 ObjValue(Cc::new(ObjValueInner {
425 cores,
426 value_cache: RefCell::default(),
427 assertions_ran: Cell::new(false),
428 }))
367 }429 }
368 #[must_use]430 // #[must_use]
369 pub fn with_this(&self, this: Self) -> Self {431 // pub fn with_this(&self, this: Self) -> Self {
370 self.0.with_this(self.clone(), this)432 // self.0.with_this(self.clone(), this)
371 }433 // }
434 /// Returns amount of visible object fields
435 /// If object only contains hidden fields - may return zero.
372 pub fn len(&self) -> usize {436 pub fn len(&self) -> usize {
373 self.0.len()437 self.fields_visibility()
438 .iter()
439 .filter(|(_, (visible, _))| *visible)
440 .count()
374 }441 }
375 pub fn is_empty(&self) -> bool {442 pub fn is_empty(&self) -> bool {
376 self.0.is_empty()443 self.len() == 0
377 }444 }
378 pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {445 /// For each field, calls callback.
446 /// If callback returns false - ends iteration prematurely.
447 ///
448 /// Returns false if ended prematurely
449 pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {
379 self.0.enum_fields(depth, handler)450 let mut super_depth = SuperDepth::default();
451 self.enum_fields_internal(
452 &mut super_depth,
453 handler,
454 CoreIdx {
455 idx: self.0.cores.len(),
456 },
457 )
380 }458 }
459 fn enum_fields_internal(
460 &self,
461 super_depth: &mut SuperDepth,
462 handler: &mut EnumFieldsHandler<'_>,
463 idx: CoreIdx,
464 ) -> bool {
465 for core in self.0.cores[..idx.idx].iter() {
466 if !core.0.enum_fields_core(super_depth, handler) {
467 return false;
468 }
469 super_depth.deepen();
470 }
471 true
472 }
381473
382 pub fn has_field_include_hidden(&self, name: IStr) -> bool {474 pub fn has_field_include_hidden(&self, name: IStr) -> bool {
383 self.0.has_field_include_hidden(name)475 self.has_field_include_hidden_idx(
476 name,
477 CoreIdx {
478 idx: self.0.cores.len(),
479 },
480 )
384 }481 }
482 fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {
483 self.0.cores[..core.idx]
484 .iter()
485 .rev()
486 .any(|v| v.0.has_field_include_hidden(name.clone()))
487 }
385 pub fn has_field(&self, name: IStr) -> bool {488 pub fn has_field(&self, name: IStr) -> bool {
386 self.0.has_field(name)489 match self.field_visibility(name) {
490 Some(Visibility::Unhide | Visibility::Normal) => true,
491 Some(Visibility::Hidden) | None => false,
492 }
387 }493 }
388 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {494 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {
389 if include_hidden {495 if include_hidden {
392 self.has_field(name)498 self.has_field(name)
393 }499 }
394 }500 }
395
396 pub fn get(&self, key: IStr) -> Result<Option<Val>> {501 pub fn get(&self, key: IStr) -> Result<Option<Val>> {
397 self.run_assertions()?;502 self.get_idx(
398 self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))503 key,
504 CoreIdx {
505 idx: self.0.cores.len(),
506 },
507 )
399 }508 }
400509
401 pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {510 fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {
402 self.0.get_for(key, this)511 let cache_key = (key.clone(), core);
512 {
513 let mut cache = self.0.value_cache.borrow_mut();
514 // entry_ref candidate?
515 match cache.entry(cache_key.clone()) {
516 Entry::Occupied(v) => match v.get() {
517 CacheValue::Cached(v) => return v.clone(),
518 CacheValue::Pending => {
519 if !is_asserting(self) {
520 bail!(InfiniteRecursionDetected);
521 }
522 }
523 },
524 Entry::Vacant(v) => {
525 v.insert(CacheValue::Pending);
526 }
527 };
528 }
529 let result = self.get_idx_uncached(key, core);
530 {
531 let mut cache = self.0.value_cache.borrow_mut();
532 cache.insert(cache_key, CacheValue::Cached(result.clone()));
533 }
534 result
403 }535 }
536 fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {
537 self.run_assertions()?;
538 let mut add_stack = Vec::with_capacity(2);
539 for (sup, core) in self.0.cores[..core.idx].iter().enumerate().rev() {
540 let sup_this = SupThis {
541 sup: CoreIdx { idx: sup },
542 this: self.clone(),
543 };
544 if let Some((val, proc)) = core.0.get_for(key.clone(), sup_this)? {
545 match proc {
546 ValueProcess::None if add_stack.is_empty() => return Ok(Some(val)),
547 ValueProcess::None => {
548 add_stack.push(val);
549 break;
550 }
551 ValueProcess::SuperPlus => {
552 add_stack.push(val);
553 }
554 }
555 }
556 }
557 if add_stack.is_empty() {
558 // None of layers had this field
559 return Ok(None);
560 } else if add_stack.len() == 1 {
561 // A layer had this field, but it wanted this field to be added with super.
562 // However, no super had this field, fail-safe
563 return Ok(Some(add_stack.pop().expect("single element on stack")));
564 }
565 let mut values = add_stack.into_iter().rev();
566 let init = values.next().expect("at least 2 elements");
404567
568 values
569 .try_fold(init, |a, b| evaluate_add_op(&a, &b))
570 .map(Some)
571
572 // self.0.get_raw(key, this)
573 }
574
405 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {575 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {
406 let Some(value) = self.get(key.clone())? else {576 let Some(value) = self.get(key.clone())? else {
407 let suggestions = suggest_object_fields(self, key.clone());577 let suggestions = suggest_object_fields(self, key.clone());
410 Ok(value)580 Ok(value)
411 }581 }
412582
413 fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {
414 self.0.get_for_uncached(key, this)
415 }
416
417 fn field_visibility(&self, field: IStr) -> Option<Visibility> {583 fn field_visibility(&self, field: IStr) -> Option<Visibility> {
418 self.0.field_visibility(field)584 self.field_visibility_idx(
585 field,
586 CoreIdx {
587 idx: self.0.cores.len(),
588 },
589 )
419 }590 }
591 fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {
592 let mut exists = false;
593 for ele in self.0.cores[..core.idx].iter().rev() {
594 let vis = ele.0.field_visibility(field.clone());
595 match vis {
596 Some(Visibility::Unhide | Visibility::Hidden) => return vis,
597 Some(Visibility::Normal) => exists = true,
598 None => {}
599 }
600 }
601 exists.then_some(Visibility::Normal)
602 }
420603
421 pub fn run_assertions(&self) -> Result<()> {604 pub fn run_assertions(&self) -> Result<()> {
422 // FIXME: Should it use `self.0.this()` in case of standalone super?605 if self.0.assertions_ran.get() {
606 return Ok(());
607 }
608 if !start_asserting(self) {
609 return Ok(());
610 }
611 for (idx, ele) in self.0.cores.iter().enumerate() {
612 let sup_this = SupThis {
423 self.run_assertions_raw(self.clone())613 sup: CoreIdx { idx },
614 this: self.clone(),
615 };
616 ele.0.run_assertions_raw(sup_this).inspect_err(|_e| {
617 finish_asserting(self);
618 })?;
619 }
620 finish_asserting(self);
621 self.0.assertions_ran.set(true);
622 Ok(())
424 }623 }
425 fn run_assertions_raw(&self, this: Self) -> Result<()> {
426 self.0.run_assertions_raw(this)
427 }
428624
429 pub fn iter(625 pub fn iter(
430 &self,626 &self,
462 }658 }
463 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {659 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {
464 let mut out = FxHashMap::default();660 let mut out = FxHashMap::default();
465 self.enum_fields(661 self.enum_fields(&mut |depth, index, name, visibility| {
466 SuperDepth::default(),
467 &mut |depth, index, name, visibility| {
468 let new_sort_key = FieldSortKey::new(depth, index);662 dbg!(&name, visibility);
663 let new_sort_key = FieldSortKey::new(depth, index);
469 let entry = out.entry(name);664 let entry = out.entry(name);
470 let (visible, _) = entry.or_insert((true, new_sort_key));665 let (visible, _) = entry.or_insert((true, new_sort_key));
471 match visibility {666 match visibility {
472 Visibility::Normal => {}667 Visibility::Normal => {}
473 Visibility::Hidden => {668 Visibility::Hidden => {
474 *visible = false;669 *visible = false;
475 }670 }
476 Visibility::Unhide => {671 Visibility::Unhide => {
477 *visible = true;672 *visible = true;
478 }673 }
479 };674 };
480 false675 false
481 },676 });
482 );
483 out677 out
484 }678 }
485 pub fn fields_ex(679 pub fn fields_ex(
515 return fields;709 return fields;
516 }710 }
517711
518 let mut fields: Vec<_> = self712 let mut fields: Vec<_> = dbg!(self
519 .fields_visibility()713 .fields_visibility())
520 .into_iter()714 .into_iter()
521 .filter(|(_, (visible, _))| include_hidden || *visible)715 .filter(|(_, (visible, _))| include_hidden || *visible)
522 .map(|(k, _)| k)716 .map(|(k, _)| k)
580774
581impl OopObject {775impl OopObject {
582 pub fn new(776 pub fn new(
583 sup: Option<ObjValue>,
584 this_entries: Cc<FxHashMap<IStr, ObjMember>>,777 this_entries: Cc<FxHashMap<IStr, ObjMember>>,
585 assertions: Cc<Vec<CcObjectAssertion>>,778 assertions: Cc<Vec<CcObjectAssertion>>,
586 ) -> Self {779 ) -> Self {
587 Self {780 Self {
588 sup,
589 // this: None,
590 assertions,
591 assertions_ran: RefCell::new(FxHashSet::new()),
592 this_entries,781 this_entries,
593 value_cache: RefCell::new(FxHashMap::new()),782 value_cache: RefCell::new(FxHashMap::new()),
783 assertions,
594 }784 }
595 }785 }
596
597 fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {
598 v.invoke.evaluate(self.sup.clone(), Some(real_this))
599 }
600
601 // FIXME: Duplication between ObjValue and OopObject
602 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 false
620 },
621 );
622 out
623 }
624}786}
625787
626impl ObjectLike for OopObject {788impl ObjectCore for OopObject {
627 fn extend_from(&self, sup: ObjValue) -> ObjValue {789 fn enum_fields_core(
628 ObjValue::new(match &self.sup {790 &self,
629 None => Self::new(
630 Some(sup),
631 self.this_entries.clone(),791 super_depth: &mut SuperDepth,
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 }
641
642 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()792 handler: &mut EnumFieldsHandler<'_>,
648 }
649
650 /// 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() == 0
655 }
656
657 /// Run callback for every field found in object
658 ///
659 /// Returns true if ended prematurely
660 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {793 ) -> 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() {794 for (name, member) in self.this_entries.iter() {
667 if handler(795 if handler(
668 depth,796 *super_depth,
669 member.original_index,797 member.original_index,
670 name.clone(),798 name.clone(),
671 member.flags.visibility(),799 member.flags.visibility(),
672 ) {800 ) {
673 return true;801 return false;
674 }802 }
675 }803 }
676 false804 true
677 }805 }
678806
679 fn has_field_include_hidden(&self, name: IStr) -> bool {807 fn has_field_include_hidden(&self, name: IStr) -> bool {
680 if self.this_entries.contains_key(&name) {808 self.this_entries.contains_key(&name)
681 true
682 } else if let Some(super_obj) = &self.sup {
683 super_obj.has_field_include_hidden(name)
684 } else {
685 false
686 }
687 }809 }
688 fn has_field(&self, name: IStr) -> bool {
689 self.field_visibility(name)
690 .map_or(false, |v| v.is_visible())
691 }
692810
693 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {811 fn get_for(&self, key: IStr, sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
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_cache
704 .borrow_mut()
705 .insert(cache_key.clone(), CacheValue::Pending);
706 let value = self.get_for_uncached(key, this).inspect_err(|e| {
707 self.value_cache812 match self.this_entries.get(&key) {
708 .borrow_mut()
709 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));
710 })?;
711 self.value_cache.borrow_mut().insert(
712 cache_key,
713 value
714 .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)?)),813 Some(k) => Ok(Some((
722 (Some(k), Some(super_obj)) => {814 k.invoke.evaluate(sup_this)?,
723 let our = self.evaluate_this(k, real_this.clone())?;
724 if k.flags.add() {815 if k.flags.add() {
725 super_obj816 ValueProcess::SuperPlus
726 .get_raw(key, real_this)?
727 .map_or(Ok(Some(our.clone())), |v| {
728 Ok(Some(evaluate_add_op(&v, &our)?))
729 })
730 } else {817 } else {
731 Ok(Some(our))818 ValueProcess::None
732 }819 },
733 }820 ))),
734 (None, Some(super_obj)) => super_obj.get_raw(key, real_this),
735 (None, None) => Ok(None),821 None => Ok(None),
736 }822 }
737 }823 }
738 fn field_visibility(&self, name: IStr) -> Option<Visibility> {824 fn field_visibility(&self, name: IStr) -> Option<Visibility> {
739 if let Some(m) = self.this_entries.get(&name) {825 Some(self.this_entries.get(&name)?.flags.visibility())
740 Some(match &m.flags.visibility() {
741 Visibility::Normal => self
742 .sup
743 .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 None
752 }
753 }826 }
754827
755 fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {828 fn run_assertions_raw(&self, sup_this: SupThis) -> Result<()> {
756 if self.assertions.is_empty() {829 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(());830 return Ok(());
761 }831 }
762 if self.assertions_ran.borrow_mut().insert(real_this.clone()) {832 for assertion in self.assertions.iter() {
763 for assertion in self.assertions.iter() {
764 if let Err(e) = assertion.0.run(self.sup.clone(), Some(real_this.clone())) {833 assertion.0.run(sup_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 }834 }
773 Ok(())835 Ok(())
774 }836 }
775}837}
776838
777impl PartialEq for ObjValue {
778 fn eq(&self, other: &Self) -> bool {
779 Cc::ptr_eq(&self.0, &other.0)
780 }
781}
782
783impl 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}
789
790#[allow(clippy::module_name_repetitions)]839#[allow(clippy::module_name_repetitions)]
791pub struct ObjValueBuilder {840pub struct ObjValueBuilder {
792 sup: Option<ObjValue>,841 sup: Option<ObjValue>,
845 if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {894 if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {
846 return ObjValue::new_empty();895 return ObjValue::new_empty();
847 }896 }
848 ObjValue::new(OopObject::new(897 let res = ObjValue::new(OopObject::new(Cc::new(self.map), Cc::new(self.assertions)));
849 self.sup,
850 Cc::new(self.map),
851 Cc::new(self.assertions),
852 ))898 self.sup.map(|sup| res.extend_from(sup)).unwrap_or(res)
853 }899 }
854}900}
855impl Default for ObjValueBuilder {901impl Default for ObjValueBuilder {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
23 gc::WithCapacityExt as _,23 gc::WithCapacityExt as _,
24 manifest::{ManifestFormat, ToStringFormat},24 manifest::{ManifestFormat, ToStringFormat},
25 typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},25 typed::{BoundedUsize, MAX_SAFE_INTEGER, MIN_SAFE_INTEGER},
26 ObjValue, Result, Unbound, WeakObjValue,26 ObjValue, Result, SupThis, Unbound, WeakSupThis,
27};27};
2828
29pub trait ThunkValue: Trace {29pub trait ThunkValue: Trace {
168 }168 }
169}169}
170
171type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);
172170
173#[derive(Trace, Clone)]171#[derive(Trace, Clone)]
174pub struct CachedUnbound<I, T>172pub struct CachedUnbound<I, T>
175where173where
176 I: Unbound<Bound = T>,174 I: Unbound<Bound = T>,
177 T: Trace,175 T: Trace,
178{176{
179 cache: Cc<RefCell<FxHashMap<CacheKey, T>>>,177 cache: Cc<RefCell<FxHashMap<WeakSupThis, T>>>,
180 value: I,178 value: I,
181}179}
182impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {180impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {
189}187}
190impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {188impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {
191 type Bound = T;189 type Bound = T;
192 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {190 fn bind(&self, sup_this: SupThis) -> Result<T> {
193 let cache_key = (191 let cache_key = sup_this.clone().downgrade();
194 sup.as_ref().map(|s| s.clone().downgrade()),
195 this.as_ref().map(|t| t.clone().downgrade()),
196 );
197 {192 {
198 if let Some(t) = self.cache.borrow().get(&cache_key) {193 if let Some(t) = self.cache.borrow().get(&cache_key) {
199 return Ok(t.clone());194 return Ok(t.clone());
200 }195 }
201 }196 }
202 let bound = self.value.bind(sup, this)?;197 let bound = self.value.bind(sup_this)?;
203198
204 {199 {
205 let mut cache = self.cache.borrow_mut();200 let mut cache = self.cache.borrow_mut();
modifiedtests/cpp_test_suite_golden_override/error.static_error_self.jsonnet.goldendiffbeforeafterboth
1self is only usable inside objects1self/super/$ are only usable inside objects
2 elem <0> evaluation2 elem <0> evaluation
modifiedtests/cpp_test_suite_golden_override/error.static_error_super.jsonnet.goldendiffbeforeafterboth
1no super found1self/super/$ are only usable inside objects
2 elem <0> evaluation2 elem <0> evaluation
addedtests/golden/issue195.jsonnetdiffbeforeafterboth

no changes

addedtests/golden/issue195.jsonnet.goldendiffbeforeafterboth

no changes

modifiedtests/tests/cpp_test_suite.rsdiffbeforeafterboth
30 .import_resolver(FileImportResolver::default());30 .import_resolver(FileImportResolver::default());
31 let s = s.build();31 let s = s.build();
32
33 let _entered = s.enter();
3234
33 let trace_format = CompactFormat {35 let trace_format = CompactFormat {
34 resolver: PathResolver::FileName,36 resolver: PathResolver::FileName,
61 Val::Obj(o.build())63 Val::Obj(o.build())
62 }),64 }),
63 );65 );
64 v = apply_tla(s, &args, v).expect("failed to apply tla");66 v = apply_tla(&args, v).expect("failed to apply tla");
65 }67 }
6668
67 match v.manifest(JsonFormat::default()) {69 match v.manifest(JsonFormat::default()) {
modifiedtests/tests/golden.rsdiffbeforeafterboth
21 .import_resolver(FileImportResolver::default());21 .import_resolver(FileImportResolver::default());
22 let s = s.build();22 let s = s.build();
23
24 let _entered = s.enter();
2325
24 let trace_format = CompactFormat {26 let trace_format = CompactFormat {
25 resolver: PathResolver::FileName,27 resolver: PathResolver::FileName,