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

difftreelog

refactor split OopObject into different file

lzyssmtoYaroslav Bolyukin2026-03-21parent: #b3f009b.patch.diff
in: master

4 files changed

modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -1,8 +1,4 @@
-use std::{
-	cmp::Ordering,
-	convert::Infallible,
-	fmt::{self, Debug, Display},
-};
+use std::{cmp::Ordering, convert::Infallible, fmt};
 
 use jrsonnet_gcmodule::{Acyclic, Trace};
 use jrsonnet_interner::IStr;
@@ -11,7 +7,7 @@
 use thiserror::Error;
 
 use crate::{
-	function::{CallLocation, FunctionSignature, ParamDefault, ParamName},
+	function::{CallLocation, FunctionSignature, ParamName},
 	stdlib::format::FormatError,
 	typed::TypeLocError,
 	val::ConvertNumValueError,
@@ -268,8 +264,8 @@
 		&mut (self.0).1
 	}
 }
-impl Display for Error {
-	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+impl fmt::Display for Error {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 		writeln!(f, "{}", self.0 .0)?;
 		for el in &self.0 .1 .0 {
 			write!(f, "\t{}", el.desc)?;
@@ -282,8 +278,8 @@
 		Ok(())
 	}
 }
-impl Debug for Error {
-	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+impl fmt::Debug for Error {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 		f.debug_tuple("LocError").field(&self.0).finish()
 	}
 }
deletedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ /dev/null
@@ -1,1260 +0,0 @@
-use std::{
-	any::Any,
-	cell::{Cell, RefCell},
-	collections::hash_map::Entry,
-	fmt::{self, Debug},
-	hash::{Hash, Hasher},
-	mem,
-	num::Saturating,
-	ops::ControlFlow,
-};
-
-use educe::Educe;
-use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace, Weak};
-use jrsonnet_interner::IStr;
-use jrsonnet_parser::{Span, Visibility};
-use rustc_hash::{FxHashMap, FxHashSet};
-
-use crate::{
-	arr::{PickObjectKeyValues, PickObjectValues},
-	bail,
-	error::{suggest_object_fields, ErrorKind::*},
-	function::{CallLocation, FuncVal},
-	gc::WithCapacityExt as _,
-	identity_hash, in_frame,
-	operator::evaluate_add_op,
-	val::{ArrValue, ThunkValue},
-	CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
-};
-
-#[cfg(not(feature = "exp-preserve-order"))]
-mod ordering {
-	#![allow(
-		// This module works as stub for preserve-order feature
-		clippy::unused_self,
-	)]
-
-	use jrsonnet_gcmodule::Trace;
-
-	#[derive(Clone, Copy, Default, Debug, Trace)]
-	pub struct FieldIndex(());
-	impl FieldIndex {
-		pub const fn next(self) -> Self {
-			Self(())
-		}
-	}
-
-	#[derive(Clone, Copy, Default, Debug, Trace)]
-	pub struct SuperDepth(());
-	impl SuperDepth {
-		pub(super) fn deepen(self) {}
-	}
-}
-
-#[cfg(feature = "exp-preserve-order")]
-mod ordering {
-	use std::cmp::Reverse;
-
-	use jrsonnet_gcmodule::Trace;
-
-	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]
-	pub struct FieldIndex(u32);
-	impl FieldIndex {
-		pub fn next(self) -> Self {
-			Self(self.0 + 1)
-		}
-	}
-
-	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]
-	pub struct SuperDepth(u32);
-	impl SuperDepth {
-		pub(super) fn deepen(&mut self) {
-			self.0 += 1
-		}
-	}
-
-	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
-	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);
-	impl FieldSortKey {
-		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {
-			Self(Reverse(depth), index)
-		}
-	}
-}
-
-#[cfg(feature = "exp-preserve-order")]
-use ordering::FieldSortKey;
-use ordering::{FieldIndex, SuperDepth};
-
-// 0 - add
-//  12 - visibility
-#[derive(Clone, Copy)]
-pub struct ObjFieldFlags(u8);
-impl ObjFieldFlags {
-	fn new(add: bool, visibility: Visibility) -> Self {
-		let mut v = 0;
-		if add {
-			v |= 1;
-		}
-		v |= match visibility {
-			Visibility::Normal => 0b000,
-			Visibility::Hidden => 0b010,
-			Visibility::Unhide => 0b100,
-		};
-		Self(v)
-	}
-	pub fn add(&self) -> bool {
-		self.0 & 1 != 0
-	}
-	pub fn visibility(&self) -> Visibility {
-		match (self.0 & 0b110) >> 1 {
-			0b00 => Visibility::Normal,
-			0b01 => Visibility::Hidden,
-			0b10 => Visibility::Unhide,
-			_ => unreachable!(),
-		}
-	}
-}
-impl Debug for ObjFieldFlags {
-	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-		f.debug_struct("ObjFieldFlags")
-			.field("add", &self.add())
-			.field("visibility", &self.visibility())
-			.finish()
-	}
-}
-
-#[allow(clippy::module_name_repetitions)]
-#[derive(Debug, Trace)]
-pub struct ObjMember {
-	#[trace(skip)]
-	flags: ObjFieldFlags,
-	original_index: FieldIndex,
-	pub invoke: MaybeUnbound,
-	pub location: Option<Span>,
-}
-
-cc_dyn!(CcObjectAssertion, ObjectAssertion);
-pub trait ObjectAssertion: Trace {
-	fn run(&self, sup_this: SupThis) -> Result<()>;
-}
-
-// Field => This
-
-#[derive(Trace, Debug)]
-enum CacheValue {
-	Cached(Result<Option<Val>>),
-	Pending,
-}
-
-#[allow(clippy::module_name_repetitions)]
-#[derive(Trace, Default)]
-#[trace(tracking(force))]
-pub struct OopObject {
-	assertion: Option<CcObjectAssertion>,
-	this_entries: FxHashMap<IStr, ObjMember>,
-}
-impl Debug for OopObject {
-	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-		f.debug_struct("OopObject")
-			.field("this_entries", &self.this_entries)
-			.finish_non_exhaustive()
-	}
-}
-impl OopObject {
-	fn is_empty(&self) -> bool {
-		self.assertion.is_none() && self.this_entries.is_empty()
-	}
-}
-
-type EnumFieldsHandler<'a> =
-	dyn FnMut(SuperDepth, FieldIndex, IStr, EnumFields) -> ControlFlow<()> + 'a;
-
-pub enum EnumFields {
-	Normal(Visibility),
-	Omit(Skip),
-}
-
-#[derive(Trace, Clone)]
-pub enum GetFor {
-	// Return value
-	Final(Val),
-	// Continue iterating over cores, add current value to sum stack
-	SuperPlus(Val),
-	// Ignore the field value, stop at this layer instead
-	Omit(#[trace(skip)] Skip),
-	NotFound,
-}
-
-#[derive(Acyclic, Clone)]
-pub enum FieldVisibility {
-	Found(Visibility),
-	Omit(Skip),
-	NotFound,
-}
-
-#[derive(Acyclic, Clone)]
-pub enum HasFieldIncludeHidden {
-	Exists,
-	NotFound,
-	Omit(Skip),
-}
-
-type Skip = Saturating<usize>;
-
-pub trait ObjectCore: Trace + Any + Debug {
-	// If callback returns false, iteration stops, and this call returns false.
-	fn enum_fields_core(
-		&self,
-		super_depth: &mut SuperDepth,
-		handler: &mut EnumFieldsHandler<'_>,
-	) -> bool;
-
-	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden;
-
-	fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor>;
-	fn field_visibility_core(&self, field: IStr) -> FieldVisibility;
-
-	fn run_assertions_core(&self, sup_this: SupThis) -> Result<()>;
-}
-
-#[derive(Clone, Trace)]
-pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);
-impl Debug for WeakObjValue {
-	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-		f.debug_tuple("WeakObjValue").finish()
-	}
-}
-
-impl PartialEq for WeakObjValue {
-	fn eq(&self, other: &Self) -> bool {
-		Weak::ptr_eq(&self.0, &other.0)
-	}
-}
-
-impl Eq for WeakObjValue {}
-impl Hash for WeakObjValue {
-	fn hash<H: Hasher>(&self, hasher: &mut H) {
-		// Safety: usize is POD
-		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };
-		hasher.write_usize(addr);
-	}
-}
-
-cc_dyn!(
-	#[derive(Clone, Debug)]
-	CcObjectCore, ObjectCore,
-	pub fn new() {...}
-);
-#[derive(Trace, Educe)]
-#[educe(Debug)]
-struct ObjValueInner {
-	cores: Vec<CcObjectCore>,
-	assertions_ran: Cell<bool>,
-	value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,
-}
-
-thread_local! {
-	static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();
-}
-fn is_asserting(obj: &ObjValue) -> bool {
-	RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))
-}
-/// Returns false if already asserting
-fn start_asserting(obj: &ObjValue) -> bool {
-	RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))
-}
-fn finish_asserting(obj: &ObjValue) {
-	RUNNING_ASSERTIONS.with_borrow_mut(|v| {
-		let r = v.remove(obj);
-		debug_assert!(
-			r,
-			"finish_asserting was called before start_asserting or twice"
-		);
-	});
-}
-
-thread_local! {
-	static EMPTY_OBJ: ObjValue = ObjValue(Cc::new(ObjValueInner {
-		cores: vec![],
-		assertions_ran: Cell::new(true),
-		value_cache: Default::default(),
-	}))
-}
-
-#[allow(clippy::module_name_repetitions)]
-#[derive(Clone, Trace, Debug, Educe)]
-#[educe(PartialEq, Hash, Eq)]
-pub struct ObjValue(
-	#[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,
-);
-
-impl ObjValue {
-	pub fn empty() -> Self {
-		EMPTY_OBJ.with(|v| v.clone())
-	}
-	pub fn is_empty(&self) -> bool {
-		self.0.cores.is_empty() || self.len() == 0
-	}
-}
-
-#[derive(Trace, Debug)]
-struct StandaloneSuperCore {
-	sup: CoreIdx,
-	this: ObjValue,
-}
-impl ObjectCore for StandaloneSuperCore {
-	fn enum_fields_core(
-		&self,
-		super_depth: &mut SuperDepth,
-		handler: &mut EnumFieldsHandler<'_>,
-	) -> bool {
-		self.this.enum_fields_idx(super_depth, handler, self.sup)
-	}
-
-	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {
-		if self.this.has_field_include_hidden_idx(name, self.sup) {
-			HasFieldIncludeHidden::Exists
-		} else {
-			HasFieldIncludeHidden::NotFound
-		}
-	}
-
-	fn get_for_core(&self, key: IStr, _sup_this: SupThis, omit_only: bool) -> Result<GetFor> {
-		if omit_only {
-			return Ok(GetFor::NotFound);
-		}
-		let v = self.this.get_idx(key, self.sup)?;
-		Ok(v.map_or(GetFor::NotFound, |v| GetFor::Final(v)))
-	}
-
-	fn field_visibility_core(&self, field: IStr) -> FieldVisibility {
-		match self.this.field_visibility_idx(field, self.sup) {
-			Some(c) => FieldVisibility::Found(c),
-			None => FieldVisibility::NotFound,
-		}
-	}
-
-	fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {
-		self.this.run_assertions()
-	}
-}
-
-#[derive(Debug, Acyclic)]
-struct OmitFieldsCore {
-	omit: FxHashSet<IStr>,
-	prev_layers: usize,
-}
-impl ObjectCore for OmitFieldsCore {
-	fn enum_fields_core(
-		&self,
-		super_depth: &mut SuperDepth,
-		handler: &mut EnumFieldsHandler<'_>,
-	) -> bool {
-		let mut fi = FieldIndex::default();
-		for f in &self.omit {
-			if let ControlFlow::Break(()) = handler(
-				*super_depth,
-				fi,
-				f.clone(),
-				EnumFields::Omit(Saturating(self.prev_layers)),
-			) {
-				return false;
-			}
-			fi = fi.next();
-		}
-		true
-	}
-
-	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {
-		if self.omit.contains(&name) {
-			return HasFieldIncludeHidden::Omit(Saturating(self.prev_layers));
-		}
-		HasFieldIncludeHidden::NotFound
-	}
-
-	fn get_for_core(&self, key: IStr, _sup_this: SupThis, _omit_only: bool) -> Result<GetFor> {
-		if self.omit.contains(&key) {
-			return Ok(GetFor::Omit(Saturating(self.prev_layers)));
-		}
-		Ok(GetFor::NotFound)
-	}
-
-	fn field_visibility_core(&self, field: IStr) -> FieldVisibility {
-		if self.omit.contains(&field) {
-			return FieldVisibility::Omit(Saturating(self.prev_layers));
-		}
-		FieldVisibility::NotFound
-	}
-
-	fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {
-		Ok(())
-	}
-}
-
-#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]
-struct CoreIdx {
-	idx: usize,
-}
-impl CoreIdx {
-	fn super_exists(self) -> bool {
-		self.idx != 0
-	}
-}
-#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]
-pub struct SupThis {
-	sup: CoreIdx,
-	this: ObjValue,
-}
-impl SupThis {
-	pub fn has_super(&self) -> bool {
-		self.sup.super_exists()
-	}
-	/// Implementation of `"field" in super` operation,
-	/// works faster than standalone super path.
-	///
-	/// In case of no `super` existence, returns false.
-	pub fn field_in_super(&self, field: IStr) -> bool {
-		self.this.has_field_include_hidden_idx(field, self.sup)
-	}
-	/// Implementation of `super.field` operation,
-	/// works faster than standalone super path.
-	///
-	/// In case of no `super` existence, returns `NoSuperFound`
-	pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {
-		if !self.sup.super_exists() {
-			bail!(NoSuperFound);
-		}
-		self.this.get_idx(field, self.sup)
-	}
-	/// `super` with `self` overriden for top-level lookups.
-	/// Exists when super appears outside of `super.field`/`"field" in super` expressions
-	/// Exclusive to jrsonnet.
-	///
-	/// Might return `NoSuperFound` error.
-	pub fn standalone_super(&self) -> Result<ObjValue> {
-		if !self.sup.super_exists() {
-			bail!(NoSuperFound)
-		}
-		let mut out = ObjValue::builder();
-		out.reserve_cores(1).extend_with_core(StandaloneSuperCore {
-			sup: self.sup,
-			this: self.this.clone(),
-		});
-		Ok(out.build())
-	}
-	pub fn this(&self) -> &ObjValue {
-		&self.this
-	}
-	pub fn downgrade(self) -> WeakSupThis {
-		WeakSupThis {
-			sup: self.sup,
-			this: self.this.downgrade(),
-		}
-	}
-}
-#[derive(Trace, PartialEq, Eq, Hash, Debug)]
-pub struct WeakSupThis {
-	sup: CoreIdx,
-	this: WeakObjValue,
-}
-
-impl ObjValue {
-	pub fn builder() -> ObjValueBuilder {
-		ObjValueBuilder::new()
-	}
-	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {
-		ObjValueBuilder::with_capacity(capacity)
-	}
-	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {
-		let mut out = ObjValueBuilder::with_capacity(1);
-		out.with_super(self);
-		let mut member = out.field(key);
-		if value.flags.add() {
-			member = member.add();
-		}
-		if let Some(loc) = value.location {
-			member = member.with_location(loc);
-		}
-		let _ = member
-			.with_visibility(value.flags.visibility())
-			.binding(value.invoke);
-		out.build()
-	}
-	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {
-		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())
-	}
-
-	pub fn extend(&mut self) -> ObjValueBuilder {
-		let mut out = ObjValueBuilder::new();
-		out.with_super(self.clone());
-		out
-	}
-
-	#[must_use]
-	pub fn extend_from(&self, sup: Self) -> Self {
-		let mut cores = sup.0.cores.clone();
-		cores.extend(self.0.cores.iter().cloned());
-		ObjValue(Cc::new(ObjValueInner {
-			cores,
-			value_cache: RefCell::default(),
-			assertions_ran: Cell::new(false),
-		}))
-	}
-	// #[must_use]
-	// pub fn with_this(&self, this: Self) -> Self {
-	// 	self.0.with_this(self.clone(), this)
-	// }
-	/// Returns amount of visible object fields
-	/// If object only contains hidden fields - may return zero.
-	pub fn len(&self) -> usize {
-		self.fields_visibility()
-			.values()
-			.filter(|d| d.visible())
-			.count()
-	}
-	/// For each field, calls callback.
-	/// If callback returns false - ends iteration prematurely.
-	///
-	/// Returns false if ended prematurely
-	pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {
-		let mut super_depth = SuperDepth::default();
-		self.enum_fields_idx(
-			&mut super_depth,
-			handler,
-			CoreIdx {
-				idx: self.0.cores.len(),
-			},
-		)
-	}
-	fn enum_fields_idx(
-		&self,
-		super_depth: &mut SuperDepth,
-		handler: &mut EnumFieldsHandler<'_>,
-		idx: CoreIdx,
-	) -> bool {
-		for core in self.0.cores[..idx.idx].iter().rev() {
-			if !core.0.enum_fields_core(super_depth, handler) {
-				return false;
-			}
-			super_depth.deepen();
-		}
-		true
-	}
-
-	pub fn has_field_include_hidden(&self, name: IStr) -> bool {
-		self.has_field_include_hidden_idx(
-			name,
-			CoreIdx {
-				idx: self.0.cores.len(),
-			},
-		)
-	}
-	fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {
-		let mut skip = Saturating(0usize);
-		for ele in self.0.cores[..core.idx].iter().rev() {
-			match ele.0.has_field_include_hidden_core(name.clone()) {
-				HasFieldIncludeHidden::Exists => {
-					if skip.0 == 0 {
-						return true;
-					}
-				}
-				HasFieldIncludeHidden::Omit(new_skip) => {
-					// +1 including this core
-					skip = skip.max(new_skip + Saturating(1));
-				}
-				HasFieldIncludeHidden::NotFound => {}
-			}
-			skip -= 1;
-		}
-		false
-	}
-	pub fn has_field(&self, name: IStr) -> bool {
-		match self.field_visibility(name) {
-			Some(Visibility::Unhide | Visibility::Normal) => true,
-			Some(Visibility::Hidden) | None => false,
-		}
-	}
-	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {
-		if include_hidden {
-			self.has_field_include_hidden(name)
-		} else {
-			self.has_field(name)
-		}
-	}
-	pub fn get(&self, key: IStr) -> Result<Option<Val>> {
-		self.get_idx(
-			key,
-			CoreIdx {
-				idx: self.0.cores.len(),
-			},
-		)
-	}
-
-	fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {
-		let cache_key = (key.clone(), core);
-		{
-			let mut cache = self.0.value_cache.borrow_mut();
-			// entry_ref candidate?
-			match cache.entry(cache_key.clone()) {
-				Entry::Occupied(v) => match v.get() {
-					CacheValue::Cached(v) => return v.clone(),
-					CacheValue::Pending => {
-						if !is_asserting(self) {
-							bail!(InfiniteRecursionDetected);
-						}
-					}
-				},
-				Entry::Vacant(v) => {
-					v.insert(CacheValue::Pending);
-				}
-			};
-		}
-		let result = self.get_idx_uncached(key, core);
-		{
-			let mut cache = self.0.value_cache.borrow_mut();
-			cache.insert(cache_key, CacheValue::Cached(result.clone()));
-		}
-		result
-	}
-	fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {
-		self.run_assertions()?;
-		let mut add_stack = Vec::with_capacity(2);
-		let mut skip = Saturating(0);
-		for (sup, core) in self.0.cores[..core.idx].iter().enumerate().rev() {
-			let sup_this = SupThis {
-				sup: CoreIdx { idx: sup },
-				this: self.clone(),
-			};
-			match core.0.get_for_core(key.clone(), sup_this, skip.0 != 0)? {
-				GetFor::Final(val) if add_stack.is_empty() => {
-					if skip.0 == 0 {
-						return Ok(Some(val));
-					}
-				}
-				GetFor::Final(val) => {
-					if skip.0 == 0 {
-						add_stack.push(val);
-						break;
-					}
-				}
-				GetFor::SuperPlus(val) => {
-					if skip.0 == 0 {
-						add_stack.push(val);
-					}
-				}
-				GetFor::Omit(new_skip) => {
-					// +1 including this core
-					skip = skip.max(new_skip + Saturating(1));
-				}
-				GetFor::NotFound => {}
-			}
-			skip -= 1;
-		}
-		if add_stack.is_empty() {
-			// None of layers had this field
-			return Ok(None);
-		} else if add_stack.len() == 1 {
-			// A layer had this field, but it wanted this field to be added with super.
-			// However, no super had this field, fail-safe
-			return Ok(Some(add_stack.pop().expect("single element on stack")));
-		}
-		let mut values = add_stack.into_iter().rev();
-		let init = values.next().expect("at least 2 elements");
-
-		values
-			.try_fold(init, |a, b| evaluate_add_op(&a, &b))
-			.map(Some)
-
-		// self.0.get_raw(key, this)
-	}
-
-	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {
-		let Some(value) = self.get(key.clone())? else {
-			let suggestions = suggest_object_fields(self, key.clone());
-			bail!(NoSuchField(key, suggestions))
-		};
-		Ok(value)
-	}
-
-	fn field_visibility(&self, field: IStr) -> Option<Visibility> {
-		self.field_visibility_idx(
-			field,
-			CoreIdx {
-				idx: self.0.cores.len(),
-			},
-		)
-	}
-	fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {
-		let mut exists = false;
-		let mut skip = Saturating(0usize);
-		for ele in self.0.cores[..core.idx].iter().rev() {
-			let vis = ele.0.field_visibility_core(field.clone());
-			match vis {
-				FieldVisibility::Found(vis @ (Visibility::Unhide | Visibility::Hidden)) => {
-					if skip.0 == 0 {
-						return Some(vis);
-					}
-				}
-				FieldVisibility::Found(Visibility::Normal) => {
-					if skip.0 == 0 {
-						exists = true
-					}
-				}
-				FieldVisibility::NotFound => {}
-				FieldVisibility::Omit(new_skip) => {
-					// +1 including this core
-					skip = skip.max(new_skip + Saturating(1));
-				}
-			}
-			skip -= 1;
-		}
-		exists.then_some(Visibility::Normal)
-	}
-
-	pub fn run_assertions(&self) -> Result<()> {
-		if self.0.assertions_ran.get() {
-			return Ok(());
-		}
-		if !start_asserting(self) {
-			return Ok(());
-		}
-		for (idx, ele) in self.0.cores.iter().enumerate() {
-			let sup_this = SupThis {
-				sup: CoreIdx { idx },
-				this: self.clone(),
-			};
-			ele.0.run_assertions_core(sup_this).inspect_err(|_e| {
-				finish_asserting(self);
-			})?;
-		}
-		finish_asserting(self);
-		self.0.assertions_ran.set(true);
-		Ok(())
-	}
-
-	pub fn iter(
-		&self,
-		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
-	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {
-		let fields = self.fields(
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order,
-		);
-		fields.into_iter().map(|field| {
-			(
-				field.clone(),
-				self.get(field)
-					.map(|opt| opt.expect("iterating over keys, field exists")),
-			)
-		})
-	}
-	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {
-		if !self.has_field_ex(key.clone(), true) {
-			return None;
-		}
-		#[derive(Trace)]
-		struct ObjFieldThunk {
-			obj: ObjValue,
-			key: IStr,
-		}
-		impl ThunkValue for ObjFieldThunk {
-			type Output = Val;
-
-			fn get(&self) -> Result<Self::Output> {
-				self.obj
-					.get(self.key.clone())
-					.transpose()
-					.expect("field existence checked")
-			}
-		}
-
-		Some(Thunk::new(ObjFieldThunk {
-			obj: self.clone(),
-			key,
-		}))
-	}
-	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {
-		#[derive(Trace)]
-		struct ObjFieldThunk {
-			obj: ObjValue,
-			key: IStr,
-		}
-		impl ThunkValue for ObjFieldThunk {
-			type Output = Val;
-
-			fn get(&self) -> Result<Self::Output> {
-				self.obj.get_or_bail(self.key.clone())
-			}
-		}
-
-		Thunk::new(ObjFieldThunk {
-			obj: self.clone(),
-			key,
-		})
-	}
-	pub fn ptr_eq(a: &Self, b: &Self) -> bool {
-		Cc::ptr_eq(&a.0, &b.0)
-	}
-	pub fn downgrade(self) -> WeakObjValue {
-		WeakObjValue(self.0.downgrade())
-	}
-}
-
-#[derive(Debug)]
-struct FieldVisibilityData {
-	omitted_until: Saturating<usize>,
-	exists_visible: Option<Visibility>,
-	#[cfg(feature = "exp-preserve-order")]
-	key: FieldSortKey,
-}
-impl FieldVisibilityData {
-	fn visible(&self) -> bool {
-		self.exists_visible
-			.expect("non-existing fields shall be dropped at the end of fn fields_visibility()")
-			.is_visible()
-	}
-	#[cfg(feature = "exp-preserve-order")]
-	fn sort_key(&self) -> FieldSortKey {
-		self.key
-	}
-}
-
-impl ObjValue {
-	fn fields_visibility(&self) -> FxHashMap<IStr, FieldVisibilityData> {
-		let mut out = FxHashMap::default();
-
-		let mut super_depth = SuperDepth::default();
-		let mut omit_index = Saturating(0);
-		for core in self.0.cores.iter().rev() {
-			core.0
-				.enum_fields_core(&mut super_depth, &mut |_depth, _index, name, visibility| {
-					let entry = out.entry(name);
-					let data = entry.or_insert(FieldVisibilityData {
-						exists_visible: None,
-						#[cfg(feature = "exp-preserve-order")]
-						key: FieldSortKey::new(_depth, _index),
-						omitted_until: omit_index,
-					});
-					match visibility {
-						EnumFields::Omit(new_skip) => {
-							// +1 including this core
-							data.omitted_until = data
-								.omitted_until
-								.max(omit_index + new_skip + Saturating(1));
-						}
-						EnumFields::Normal(Visibility::Normal) => {
-							if data.omitted_until <= omit_index {
-								if data.exists_visible.is_none() {
-									data.exists_visible = Some(Visibility::Normal);
-								}
-							}
-						}
-						EnumFields::Normal(Visibility::Hidden) => {
-							if data.omitted_until <= omit_index {
-								data.exists_visible = Some(match data.exists_visible {
-									// We're iterating in reverse, later unhide is preserved
-									Some(Visibility::Unhide) => Visibility::Unhide,
-									_ => Visibility::Hidden,
-								});
-							}
-						}
-						EnumFields::Normal(Visibility::Unhide) => {
-							if data.omitted_until <= omit_index {
-								data.exists_visible = Some(match data.exists_visible {
-									// We're iterating in reverse, later hide is preserved
-									Some(Visibility::Hidden) => Visibility::Hidden,
-									_ => Visibility::Unhide,
-								});
-							}
-						}
-					};
-					return ControlFlow::Continue(());
-				});
-
-			super_depth.deepen();
-			omit_index += 1;
-		}
-
-		out.retain(|_, v| v.exists_visible.is_some());
-
-		out
-	}
-	pub fn fields_ex(
-		&self,
-		include_hidden: bool,
-		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
-	) -> Vec<IStr> {
-		#[cfg(feature = "exp-preserve-order")]
-		if preserve_order {
-			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self
-				.fields_visibility()
-				.into_iter()
-				.filter(|(_, d)| include_hidden || d.visible())
-				.enumerate()
-				.map(|(idx, (k, d))| (k, (d.sort_key(), idx)))
-				.unzip();
-			keys.sort_unstable_by_key(|v| v.0);
-			// Reorder in-place by resulting indexes
-			for i in 0..fields.len() {
-				let x = fields[i].clone();
-				let mut j = i;
-				loop {
-					let k = keys[j].1;
-					keys[j].1 = j;
-					if k == i {
-						break;
-					}
-					fields[j] = fields[k].clone();
-					j = k;
-				}
-				fields[j] = x;
-			}
-			return fields;
-		}
-
-		let mut fields: Vec<_> = self
-			.fields_visibility()
-			.into_iter()
-			.filter(|(_, d)| include_hidden || d.visible())
-			.map(|(k, _)| k)
-			.collect();
-		fields.sort_unstable();
-		fields
-	}
-	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {
-		self.fields_ex(
-			false,
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order,
-		)
-	}
-	pub fn values_ex(
-		&self,
-		include_hidden: bool,
-		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
-	) -> ArrValue {
-		ArrValue::new(PickObjectValues::new(
-			self.clone(),
-			self.fields_ex(
-				include_hidden,
-				#[cfg(feature = "exp-preserve-order")]
-				preserve_order,
-			),
-		))
-	}
-	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {
-		self.values_ex(
-			false,
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order,
-		)
-	}
-	pub fn key_values_ex(
-		&self,
-		include_hidden: bool,
-		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
-	) -> ArrValue {
-		ArrValue::new(PickObjectKeyValues::new(
-			self.clone(),
-			self.fields_ex(
-				include_hidden,
-				#[cfg(feature = "exp-preserve-order")]
-				preserve_order,
-			),
-		))
-	}
-	pub fn key_values(
-		&self,
-		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
-	) -> ArrValue {
-		self.key_values_ex(
-			false,
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order,
-		)
-	}
-}
-
-impl OopObject {
-	pub fn new(
-		this_entries: FxHashMap<IStr, ObjMember>,
-		assertion: Option<CcObjectAssertion>,
-	) -> Self {
-		Self {
-			this_entries,
-			assertion,
-		}
-	}
-}
-
-impl ObjectCore for OopObject {
-	fn enum_fields_core(
-		&self,
-		super_depth: &mut SuperDepth,
-		handler: &mut EnumFieldsHandler<'_>,
-	) -> bool {
-		for (name, member) in self.this_entries.iter() {
-			if matches!(
-				handler(
-					*super_depth,
-					member.original_index,
-					name.clone(),
-					EnumFields::Normal(member.flags.visibility()),
-				),
-				ControlFlow::Break(())
-			) {
-				return false;
-			}
-		}
-		true
-	}
-
-	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {
-		if self.this_entries.contains_key(&name) {
-			HasFieldIncludeHidden::Exists
-		} else {
-			HasFieldIncludeHidden::NotFound
-		}
-	}
-
-	fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor> {
-		if omit_only {
-			return Ok(GetFor::NotFound);
-		}
-		match self.this_entries.get(&key) {
-			Some(k) => {
-				let v = k.invoke.evaluate(sup_this)?;
-				Ok(if k.flags.add() {
-					GetFor::SuperPlus(v)
-				} else {
-					GetFor::Final(v)
-				})
-			}
-			None => Ok(GetFor::NotFound),
-		}
-	}
-	fn field_visibility_core(&self, name: IStr) -> FieldVisibility {
-		match self.this_entries.get(&name) {
-			Some(f) => FieldVisibility::Found(f.flags.visibility()),
-			None => FieldVisibility::NotFound,
-		}
-	}
-
-	fn run_assertions_core(&self, sup_this: SupThis) -> Result<()> {
-		if let Some(assertion) = &self.assertion {
-			assertion.0.run(sup_this.clone())?;
-		}
-		Ok(())
-	}
-}
-
-#[allow(clippy::module_name_repetitions)]
-pub struct ObjValueBuilder {
-	sup: Vec<CcObjectCore>,
-
-	new: OopObject,
-	next_field_index: FieldIndex,
-}
-impl ObjValueBuilder {
-	pub fn new() -> Self {
-		Self::with_capacity(0)
-	}
-	pub fn with_capacity(capacity: usize) -> Self {
-		Self {
-			sup: vec![],
-			new: OopObject {
-				assertion: None,
-				this_entries: FxHashMap::with_capacity(capacity),
-			},
-			next_field_index: FieldIndex::default(),
-		}
-	}
-	pub fn reserve_cores(&mut self, capacity: usize) -> &mut Self {
-		self.sup.reserve_exact(capacity);
-		self
-	}
-	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {
-		self.sup = super_obj.0.cores.clone();
-		self
-	}
-
-	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {
-		assert!(
-			self.new.assertion.is_none(),
-			"one OopObject can only have one assertion"
-		);
-		self.new.assertion = Some(CcObjectAssertion::new(assertion));
-		self
-	}
-	pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {
-		let field_index = self.next_field_index;
-		self.next_field_index = self.next_field_index.next();
-		ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)
-	}
-	/// Preset for common method definiton pattern:
-	/// Create a hidden field with the function value.
-	///
-	/// `.field(name).hide().value(Val::function(value))`
-	pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {
-		self.field(name).hide().value(Val::Func(value.into()));
-		self
-	}
-	pub fn try_method(
-		&mut self,
-		name: impl Into<IStr>,
-		value: impl Into<FuncVal>,
-	) -> Result<&mut Self> {
-		self.field(name).hide().try_value(Val::Func(value.into()))?;
-		Ok(self)
-	}
-
-	pub fn extend_with_core(&mut self, core: impl ObjectCore) {
-		self.commit();
-		self.sup.push(CcObjectCore::new(core));
-	}
-
-	fn commit(&mut self) {
-		if !self.new.is_empty() {
-			self.sup.push(CcObjectCore::new(mem::take(&mut self.new)));
-		}
-		self.next_field_index = FieldIndex::default();
-	}
-
-	pub fn with_fields_omitted(&mut self, omit: FxHashSet<IStr>) {
-		self.commit();
-		self.sup.push(CcObjectCore::new(OmitFieldsCore {
-			omit,
-			prev_layers: self.sup.len(),
-		}));
-	}
-
-	pub fn build(mut self) -> ObjValue {
-		self.commit();
-		if self.sup.is_empty() {
-			return ObjValue::empty();
-		}
-		ObjValue(Cc::new(ObjValueInner {
-			cores: self.sup,
-			assertions_ran: Cell::new(false),
-			value_cache: Default::default(),
-		}))
-	}
-}
-impl Default for ObjValueBuilder {
-	fn default() -> Self {
-		Self::with_capacity(0)
-	}
-}
-
-#[allow(clippy::module_name_repetitions)]
-#[must_use = "value not added unless binding() was called"]
-pub struct ObjMemberBuilder<Kind> {
-	kind: Kind,
-	name: IStr,
-	add: bool,
-	visibility: Visibility,
-	original_index: FieldIndex,
-	location: Option<Span>,
-}
-
-#[allow(clippy::missing_const_for_fn)]
-impl<Kind> ObjMemberBuilder<Kind> {
-	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {
-		Self {
-			kind,
-			name,
-			original_index,
-			add: false,
-			visibility: Visibility::Normal,
-			location: None,
-		}
-	}
-
-	pub const fn with_add(mut self, add: bool) -> Self {
-		self.add = add;
-		self
-	}
-	pub fn add(self) -> Self {
-		self.with_add(true)
-	}
-	pub fn with_visibility(mut self, visibility: Visibility) -> Self {
-		self.visibility = visibility;
-		self
-	}
-	pub fn hide(self) -> Self {
-		self.with_visibility(Visibility::Hidden)
-	}
-	pub fn with_location(mut self, location: Span) -> Self {
-		self.location = Some(location);
-		self
-	}
-	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {
-		(
-			self.kind,
-			self.name,
-			ObjMember {
-				flags: ObjFieldFlags::new(self.add, self.visibility),
-				original_index: self.original_index,
-				invoke: binding,
-				location: self.location,
-			},
-		)
-	}
-}
-
-pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
-impl ObjMemberBuilder<ValueBuilder<'_>> {
-	/// Inserts value, replacing if it is already defined
-	pub fn value(self, value: impl Into<Val>) {
-		let (receiver, name, member) =
-			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));
-		let entry = receiver.0.new.this_entries.entry(name);
-		entry.insert_entry(member);
-	}
-	/// Inserts thunk, replacing if it is already defined
-	pub fn thunk(self, value: impl Into<Thunk<Val>>) {
-		let (receiver, name, member) = self.build_member(MaybeUnbound::Bound(value.into()));
-		let entry = receiver.0.new.this_entries.entry(name);
-		entry.insert_entry(member);
-	}
-
-	/// Tries to insert value, returns an error if it was already defined
-	pub fn try_value(self, value: impl Into<Val>) -> Result<()> {
-		self.try_thunk(Thunk::evaluated(value.into()))
-	}
-	pub fn try_thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {
-		self.binding(MaybeUnbound::Bound(value.into()))
-	}
-	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {
-		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)))
-	}
-	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {
-		let (receiver, name, member) = self.build_member(binding);
-		let location = member.location.clone();
-		let old = receiver.0.new.this_entries.insert(name.clone(), member);
-		if old.is_some() {
-			in_frame(
-				CallLocation(location.as_ref()),
-				|| format!("field <{}> initializtion", name.clone()),
-				|| bail!(DuplicateFieldName(name.clone())),
-			)?;
-		}
-		Ok(())
-	}
-}
-
-pub struct ExtendBuilder<'v>(&'v mut ObjValue);
-impl ObjMemberBuilder<ExtendBuilder<'_>> {
-	pub fn value(self, value: impl Into<Val>) {
-		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));
-	}
-	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {
-		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));
-	}
-	pub fn binding(self, binding: MaybeUnbound) {
-		let (receiver, name, member) = self.build_member(binding);
-		let new = receiver.0.clone();
-		*receiver.0 = new.extend_with_raw_member(name, member);
-	}
-}
addedcrates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth
after · crates/jrsonnet-evaluator/src/obj/mod.rs
1use std::{2	any::Any,3	cell::{Cell, RefCell},4	collections::hash_map::Entry,5	fmt::{self, Debug},6	hash::{Hash, Hasher},7	num::Saturating,8	ops::ControlFlow,9};1011use educe::Educe;12use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace, Weak};13use jrsonnet_interner::IStr;14use jrsonnet_parser::{Span, Visibility};15use rustc_hash::{FxHashMap, FxHashSet};1617mod oop;1819pub use oop::ObjValueBuilder;2021use crate::{22	arr::{PickObjectKeyValues, PickObjectValues},23	bail,24	error::{suggest_object_fields, ErrorKind::*},25	identity_hash,26	operator::evaluate_add_op,27	val::{ArrValue, ThunkValue},28	CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,29};3031#[cfg(not(feature = "exp-preserve-order"))]32mod ordering {33	#![allow(34		// This module works as stub for preserve-order feature35		clippy::unused_self,36	)]3738	use jrsonnet_gcmodule::Trace;3940	#[derive(Clone, Copy, Default, Debug, Trace)]41	pub struct FieldIndex(());42	impl FieldIndex {43		pub const fn next(self) -> Self {44			Self(())45		}46	}4748	#[derive(Clone, Copy, Default, Debug, Trace)]49	pub struct SuperDepth(());50	impl SuperDepth {51		pub(super) fn deepen(self) {}52	}53}5455#[cfg(feature = "exp-preserve-order")]56mod ordering {57	use std::cmp::Reverse;5859	use jrsonnet_gcmodule::Trace;6061	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]62	pub struct FieldIndex(u32);63	impl FieldIndex {64		pub fn next(self) -> Self {65			Self(self.0 + 1)66		}67	}6869	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]70	pub struct SuperDepth(u32);71	impl SuperDepth {72		pub(super) fn deepen(&mut self) {73			self.0 += 174		}75	}7677	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]78	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);79	impl FieldSortKey {80		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {81			Self(Reverse(depth), index)82		}83	}84}8586#[cfg(feature = "exp-preserve-order")]87use ordering::FieldSortKey;88use ordering::{FieldIndex, SuperDepth};8990// 0 - add91//  12 - visibility92#[derive(Clone, Copy)]93pub struct ObjFieldFlags(u8);94impl ObjFieldFlags {95	fn new(add: bool, visibility: Visibility) -> Self {96		let mut v = 0;97		if add {98			v |= 1;99		}100		v |= match visibility {101			Visibility::Normal => 0b000,102			Visibility::Hidden => 0b010,103			Visibility::Unhide => 0b100,104		};105		Self(v)106	}107	pub fn add(&self) -> bool {108		self.0 & 1 != 0109	}110	pub fn visibility(&self) -> Visibility {111		match (self.0 & 0b110) >> 1 {112			0b00 => Visibility::Normal,113			0b01 => Visibility::Hidden,114			0b10 => Visibility::Unhide,115			_ => unreachable!(),116		}117	}118}119impl Debug for ObjFieldFlags {120	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {121		f.debug_struct("ObjFieldFlags")122			.field("add", &self.add())123			.field("visibility", &self.visibility())124			.finish()125	}126}127128#[allow(clippy::module_name_repetitions)]129#[derive(Debug, Trace)]130pub struct ObjMember {131	#[trace(skip)]132	flags: ObjFieldFlags,133	original_index: FieldIndex,134	pub invoke: MaybeUnbound,135	pub location: Option<Span>,136}137138cc_dyn!(CcObjectAssertion, ObjectAssertion);139pub trait ObjectAssertion: Trace {140	fn run(&self, sup_this: SupThis) -> Result<()>;141}142143// Field => This144145#[derive(Trace, Debug)]146enum CacheValue {147	Cached(Result<Option<Val>>),148	Pending,149}150151type EnumFieldsHandler<'a> =152	dyn FnMut(SuperDepth, FieldIndex, IStr, EnumFields) -> ControlFlow<()> + 'a;153154pub enum EnumFields {155	Normal(Visibility),156	Omit(Skip),157}158159#[derive(Trace, Clone)]160pub enum GetFor {161	// Return value162	Final(Val),163	// Continue iterating over cores, add current value to sum stack164	SuperPlus(Val),165	// Ignore the field value, stop at this layer instead166	Omit(#[trace(skip)] Skip),167	NotFound,168}169170#[derive(Acyclic, Clone)]171pub enum FieldVisibility {172	Found(Visibility),173	Omit(Skip),174	NotFound,175}176177#[derive(Acyclic, Clone)]178pub enum HasFieldIncludeHidden {179	Exists,180	NotFound,181	Omit(Skip),182}183184type Skip = Saturating<usize>;185186pub trait ObjectCore: Trace + Any + Debug {187	// If callback returns false, iteration stops, and this call returns false.188	fn enum_fields_core(189		&self,190		super_depth: &mut SuperDepth,191		handler: &mut EnumFieldsHandler<'_>,192	) -> bool;193194	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden;195196	fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor>;197	fn field_visibility_core(&self, field: IStr) -> FieldVisibility;198199	fn run_assertions_core(&self, sup_this: SupThis) -> Result<()>;200}201202#[derive(Clone, Trace)]203pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);204impl Debug for WeakObjValue {205	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {206		f.debug_tuple("WeakObjValue").finish()207	}208}209210impl PartialEq for WeakObjValue {211	fn eq(&self, other: &Self) -> bool {212		Weak::ptr_eq(&self.0, &other.0)213	}214}215216impl Eq for WeakObjValue {}217impl Hash for WeakObjValue {218	fn hash<H: Hasher>(&self, hasher: &mut H) {219		// Safety: usize is POD220		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };221		hasher.write_usize(addr);222	}223}224225cc_dyn!(226	#[derive(Clone, Debug)]227	CcObjectCore, ObjectCore,228	pub fn new() {...}229);230#[derive(Trace, Educe)]231#[educe(Debug)]232struct ObjValueInner {233	cores: Vec<CcObjectCore>,234	assertions_ran: Cell<bool>,235	value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,236}237238thread_local! {239	static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();240}241fn is_asserting(obj: &ObjValue) -> bool {242	RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))243}244/// Returns false if already asserting245fn start_asserting(obj: &ObjValue) -> bool {246	RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))247}248fn finish_asserting(obj: &ObjValue) {249	RUNNING_ASSERTIONS.with_borrow_mut(|v| {250		let r = v.remove(obj);251		debug_assert!(252			r,253			"finish_asserting was called before start_asserting or twice"254		);255	});256}257258thread_local! {259	static EMPTY_OBJ: ObjValue = ObjValue(Cc::new(ObjValueInner {260		cores: vec![],261		assertions_ran: Cell::new(true),262		value_cache: RefCell::default(),263	}))264}265266#[allow(clippy::module_name_repetitions)]267#[derive(Clone, Trace, Debug, Educe)]268#[educe(PartialEq, Hash, Eq)]269pub struct ObjValue(270	#[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,271);272273impl ObjValue {274	pub fn empty() -> Self {275		EMPTY_OBJ.with(|v| v.clone())276	}277	pub fn is_empty(&self) -> bool {278		self.0.cores.is_empty() || self.len() == 0279	}280}281282#[derive(Trace, Debug)]283struct StandaloneSuperCore {284	sup: CoreIdx,285	this: ObjValue,286}287impl ObjectCore for StandaloneSuperCore {288	fn enum_fields_core(289		&self,290		super_depth: &mut SuperDepth,291		handler: &mut EnumFieldsHandler<'_>,292	) -> bool {293		self.this.enum_fields_idx(super_depth, handler, self.sup)294	}295296	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {297		if self.this.has_field_include_hidden_idx(name, self.sup) {298			HasFieldIncludeHidden::Exists299		} else {300			HasFieldIncludeHidden::NotFound301		}302	}303304	fn get_for_core(&self, key: IStr, _sup_this: SupThis, omit_only: bool) -> Result<GetFor> {305		if omit_only {306			return Ok(GetFor::NotFound);307		}308		let v = self.this.get_idx(key, self.sup)?;309		Ok(v.map_or(GetFor::NotFound, |v| GetFor::Final(v)))310	}311312	fn field_visibility_core(&self, field: IStr) -> FieldVisibility {313		match self.this.field_visibility_idx(field, self.sup) {314			Some(c) => FieldVisibility::Found(c),315			None => FieldVisibility::NotFound,316		}317	}318319	fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {320		self.this.run_assertions()321	}322}323324#[derive(Debug, Acyclic)]325struct OmitFieldsCore {326	omit: FxHashSet<IStr>,327	prev_layers: usize,328}329impl ObjectCore for OmitFieldsCore {330	fn enum_fields_core(331		&self,332		super_depth: &mut SuperDepth,333		handler: &mut EnumFieldsHandler<'_>,334	) -> bool {335		let mut fi = FieldIndex::default();336		for f in &self.omit {337			if handler(338				*super_depth,339				fi,340				f.clone(),341				EnumFields::Omit(Saturating(self.prev_layers)),342			) == ControlFlow::Break(())343			{344				return false;345			}346			fi = fi.next();347		}348		true349	}350351	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {352		if self.omit.contains(&name) {353			return HasFieldIncludeHidden::Omit(Saturating(self.prev_layers));354		}355		HasFieldIncludeHidden::NotFound356	}357358	fn get_for_core(&self, key: IStr, _sup_this: SupThis, _omit_only: bool) -> Result<GetFor> {359		if self.omit.contains(&key) {360			return Ok(GetFor::Omit(Saturating(self.prev_layers)));361		}362		Ok(GetFor::NotFound)363	}364365	fn field_visibility_core(&self, field: IStr) -> FieldVisibility {366		if self.omit.contains(&field) {367			return FieldVisibility::Omit(Saturating(self.prev_layers));368		}369		FieldVisibility::NotFound370	}371372	fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {373		Ok(())374	}375}376377#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]378struct CoreIdx {379	idx: usize,380}381impl CoreIdx {382	fn super_exists(self) -> bool {383		self.idx != 0384	}385}386#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]387pub struct SupThis {388	sup: CoreIdx,389	this: ObjValue,390}391impl SupThis {392	pub fn has_super(&self) -> bool {393		self.sup.super_exists()394	}395	/// Implementation of `"field" in super` operation,396	/// works faster than standalone super path.397	///398	/// In case of no `super` existence, returns false.399	pub fn field_in_super(&self, field: IStr) -> bool {400		self.this.has_field_include_hidden_idx(field, self.sup)401	}402	/// Implementation of `super.field` operation,403	/// works faster than standalone super path.404	///405	/// In case of no `super` existence, returns `NoSuperFound`406	pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {407		if !self.sup.super_exists() {408			bail!(NoSuperFound);409		}410		self.this.get_idx(field, self.sup)411	}412	/// `super` with `self` overriden for top-level lookups.413	/// Exists when super appears outside of `super.field`/`"field" in super` expressions414	/// Exclusive to jrsonnet.415	///416	/// Might return `NoSuperFound` error.417	pub fn standalone_super(&self) -> Result<ObjValue> {418		if !self.sup.super_exists() {419			bail!(NoSuperFound)420		}421		let mut out = ObjValue::builder();422		out.reserve_cores(1).extend_with_core(StandaloneSuperCore {423			sup: self.sup,424			this: self.this.clone(),425		});426		Ok(out.build())427	}428	pub fn this(&self) -> &ObjValue {429		&self.this430	}431	pub fn downgrade(self) -> WeakSupThis {432		WeakSupThis {433			sup: self.sup,434			this: self.this.downgrade(),435		}436	}437}438#[derive(Trace, PartialEq, Eq, Hash, Debug)]439pub struct WeakSupThis {440	sup: CoreIdx,441	this: WeakObjValue,442}443444impl ObjValue {445	pub fn builder() -> ObjValueBuilder {446		ObjValueBuilder::new()447	}448	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {449		ObjValueBuilder::with_capacity(capacity)450	}451	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {452		let mut out = ObjValueBuilder::with_capacity(1);453		out.with_super(self);454		let mut member = out.field(key);455		if value.flags.add() {456			member = member.add();457		}458		if let Some(loc) = value.location {459			member = member.with_location(loc);460		}461		let _ = member462			.with_visibility(value.flags.visibility())463			.binding(value.invoke);464		out.build()465	}466	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {467		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())468	}469470	pub fn extend(&mut self) -> ObjValueBuilder {471		let mut out = ObjValueBuilder::new();472		out.with_super(self.clone());473		out474	}475476	#[must_use]477	pub fn extend_from(&self, sup: Self) -> Self {478		let mut cores = sup.0.cores.clone();479		cores.extend(self.0.cores.iter().cloned());480		ObjValue(Cc::new(ObjValueInner {481			cores,482			value_cache: RefCell::default(),483			assertions_ran: Cell::new(false),484		}))485	}486	// #[must_use]487	// pub fn with_this(&self, this: Self) -> Self {488	// 	self.0.with_this(self.clone(), this)489	// }490	/// Returns amount of visible object fields491	/// If object only contains hidden fields - may return zero.492	pub fn len(&self) -> usize {493		self.fields_visibility()494			.values()495			.filter(|d| d.visible())496			.count()497	}498	/// For each field, calls callback.499	/// If callback returns false - ends iteration prematurely.500	///501	/// Returns false if ended prematurely502	pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {503		let mut super_depth = SuperDepth::default();504		self.enum_fields_idx(505			&mut super_depth,506			handler,507			CoreIdx {508				idx: self.0.cores.len(),509			},510		)511	}512	fn enum_fields_idx(513		&self,514		super_depth: &mut SuperDepth,515		handler: &mut EnumFieldsHandler<'_>,516		idx: CoreIdx,517	) -> bool {518		for core in self.0.cores[..idx.idx].iter().rev() {519			if !core.0.enum_fields_core(super_depth, handler) {520				return false;521			}522			super_depth.deepen();523		}524		true525	}526527	pub fn has_field_include_hidden(&self, name: IStr) -> bool {528		self.has_field_include_hidden_idx(529			name,530			CoreIdx {531				idx: self.0.cores.len(),532			},533		)534	}535	fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {536		let mut skip = Saturating(0usize);537		for ele in self.0.cores[..core.idx].iter().rev() {538			match ele.0.has_field_include_hidden_core(name.clone()) {539				HasFieldIncludeHidden::Exists => {540					if skip.0 == 0 {541						return true;542					}543				}544				HasFieldIncludeHidden::Omit(new_skip) => {545					// +1 including this core546					skip = skip.max(new_skip + Saturating(1));547				}548				HasFieldIncludeHidden::NotFound => {}549			}550			skip -= 1;551		}552		false553	}554	pub fn has_field(&self, name: IStr) -> bool {555		match self.field_visibility(name) {556			Some(Visibility::Unhide | Visibility::Normal) => true,557			Some(Visibility::Hidden) | None => false,558		}559	}560	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {561		if include_hidden {562			self.has_field_include_hidden(name)563		} else {564			self.has_field(name)565		}566	}567	pub fn get(&self, key: IStr) -> Result<Option<Val>> {568		self.get_idx(569			key,570			CoreIdx {571				idx: self.0.cores.len(),572			},573		)574	}575576	fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {577		let cache_key = (key.clone(), core);578		{579			let mut cache = self.0.value_cache.borrow_mut();580			// entry_ref candidate?581			match cache.entry(cache_key.clone()) {582				Entry::Occupied(v) => match v.get() {583					CacheValue::Cached(v) => return v.clone(),584					CacheValue::Pending => {585						if !is_asserting(self) {586							bail!(InfiniteRecursionDetected);587						}588					}589				},590				Entry::Vacant(v) => {591					v.insert(CacheValue::Pending);592				}593			};594		}595		let result = self.get_idx_uncached(key, core);596		{597			let mut cache = self.0.value_cache.borrow_mut();598			cache.insert(cache_key, CacheValue::Cached(result.clone()));599		}600		result601	}602	fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {603		self.run_assertions()?;604		let mut add_stack = Vec::with_capacity(2);605		let mut skip = Saturating(0);606		for (sup, core) in self.0.cores[..core.idx].iter().enumerate().rev() {607			let sup_this = SupThis {608				sup: CoreIdx { idx: sup },609				this: self.clone(),610			};611			match core.0.get_for_core(key.clone(), sup_this, skip.0 != 0)? {612				GetFor::Final(val) if add_stack.is_empty() => {613					if skip.0 == 0 {614						return Ok(Some(val));615					}616				}617				GetFor::Final(val) => {618					if skip.0 == 0 {619						add_stack.push(val);620						break;621					}622				}623				GetFor::SuperPlus(val) => {624					if skip.0 == 0 {625						add_stack.push(val);626					}627				}628				GetFor::Omit(new_skip) => {629					// +1 including this core630					skip = skip.max(new_skip + Saturating(1));631				}632				GetFor::NotFound => {}633			}634			skip -= 1;635		}636		if add_stack.is_empty() {637			// None of layers had this field638			return Ok(None);639		} else if add_stack.len() == 1 {640			// A layer had this field, but it wanted this field to be added with super.641			// However, no super had this field, fail-safe642			return Ok(Some(add_stack.pop().expect("single element on stack")));643		}644		let mut values = add_stack.into_iter().rev();645		let init = values.next().expect("at least 2 elements");646647		values648			.try_fold(init, |a, b| evaluate_add_op(&a, &b))649			.map(Some)650651		// self.0.get_raw(key, this)652	}653654	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {655		let Some(value) = self.get(key.clone())? else {656			let suggestions = suggest_object_fields(self, key.clone());657			bail!(NoSuchField(key, suggestions))658		};659		Ok(value)660	}661662	fn field_visibility(&self, field: IStr) -> Option<Visibility> {663		self.field_visibility_idx(664			field,665			CoreIdx {666				idx: self.0.cores.len(),667			},668		)669	}670	fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {671		let mut exists = false;672		let mut skip = Saturating(0usize);673		for ele in self.0.cores[..core.idx].iter().rev() {674			let vis = ele.0.field_visibility_core(field.clone());675			match vis {676				FieldVisibility::Found(vis @ (Visibility::Unhide | Visibility::Hidden)) => {677					if skip.0 == 0 {678						return Some(vis);679					}680				}681				FieldVisibility::Found(Visibility::Normal) => {682					if skip.0 == 0 {683						exists = true;684					}685				}686				FieldVisibility::NotFound => {}687				FieldVisibility::Omit(new_skip) => {688					// +1 including this core689					skip = skip.max(new_skip + Saturating(1));690				}691			}692			skip -= 1;693		}694		exists.then_some(Visibility::Normal)695	}696697	pub fn run_assertions(&self) -> Result<()> {698		if self.0.assertions_ran.get() {699			return Ok(());700		}701		if !start_asserting(self) {702			return Ok(());703		}704		for (idx, ele) in self.0.cores.iter().enumerate() {705			let sup_this = SupThis {706				sup: CoreIdx { idx },707				this: self.clone(),708			};709			ele.0.run_assertions_core(sup_this).inspect_err(|_e| {710				finish_asserting(self);711			})?;712		}713		finish_asserting(self);714		self.0.assertions_ran.set(true);715		Ok(())716	}717718	pub fn iter(719		&self,720		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,721	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {722		let fields = self.fields(723			#[cfg(feature = "exp-preserve-order")]724			preserve_order,725		);726		fields.into_iter().map(|field| {727			(728				field.clone(),729				self.get(field)730					.map(|opt| opt.expect("iterating over keys, field exists")),731			)732		})733	}734	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {735		#[derive(Trace)]736		struct ObjFieldThunk {737			obj: ObjValue,738			key: IStr,739		}740		impl ThunkValue for ObjFieldThunk {741			type Output = Val;742743			fn get(&self) -> Result<Self::Output> {744				self.obj745					.get(self.key.clone())746					.transpose()747					.expect("field existence checked")748			}749		}750751		if !self.has_field_ex(key.clone(), true) {752			return None;753		}754755		Some(Thunk::new(ObjFieldThunk {756			obj: self.clone(),757			key,758		}))759	}760	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {761		#[derive(Trace)]762		struct ObjFieldThunk {763			obj: ObjValue,764			key: IStr,765		}766		impl ThunkValue for ObjFieldThunk {767			type Output = Val;768769			fn get(&self) -> Result<Self::Output> {770				self.obj.get_or_bail(self.key.clone())771			}772		}773774		Thunk::new(ObjFieldThunk {775			obj: self.clone(),776			key,777		})778	}779	pub fn ptr_eq(a: &Self, b: &Self) -> bool {780		Cc::ptr_eq(&a.0, &b.0)781	}782	pub fn downgrade(self) -> WeakObjValue {783		WeakObjValue(self.0.downgrade())784	}785}786787#[derive(Debug)]788struct FieldVisibilityData {789	omitted_until: Saturating<usize>,790	exists_visible: Option<Visibility>,791	#[cfg(feature = "exp-preserve-order")]792	key: FieldSortKey,793}794impl FieldVisibilityData {795	fn visible(&self) -> bool {796		self.exists_visible797			.expect("non-existing fields shall be dropped at the end of fn fields_visibility()")798			.is_visible()799	}800	#[cfg(feature = "exp-preserve-order")]801	fn sort_key(&self) -> FieldSortKey {802		self.key803	}804}805806impl ObjValue {807	fn fields_visibility(&self) -> FxHashMap<IStr, FieldVisibilityData> {808		let mut out = FxHashMap::default();809810		let mut super_depth = SuperDepth::default();811		let mut omit_index = Saturating(0);812		for core in self.0.cores.iter().rev() {813			core.0814				.enum_fields_core(&mut super_depth, &mut |_depth, _index, name, visibility| {815					let entry = out.entry(name);816					let data = entry.or_insert(FieldVisibilityData {817						exists_visible: None,818						#[cfg(feature = "exp-preserve-order")]819						key: FieldSortKey::new(_depth, _index),820						omitted_until: omit_index,821					});822					match visibility {823						EnumFields::Omit(new_skip) => {824							// +1 including this core825							data.omitted_until = data826								.omitted_until827								.max(omit_index + new_skip + Saturating(1));828						}829						EnumFields::Normal(Visibility::Normal) => {830							if data.omitted_until <= omit_index && data.exists_visible.is_none() {831								data.exists_visible = Some(Visibility::Normal);832							}833						}834						EnumFields::Normal(Visibility::Hidden) => {835							if data.omitted_until <= omit_index {836								data.exists_visible = Some(match data.exists_visible {837									// We're iterating in reverse, later unhide is preserved838									Some(Visibility::Unhide) => Visibility::Unhide,839									_ => Visibility::Hidden,840								});841							}842						}843						EnumFields::Normal(Visibility::Unhide) => {844							if data.omitted_until <= omit_index {845								data.exists_visible = Some(match data.exists_visible {846									// We're iterating in reverse, later hide is preserved847									Some(Visibility::Hidden) => Visibility::Hidden,848									_ => Visibility::Unhide,849								});850							}851						}852					}853					ControlFlow::Continue(())854				});855856			super_depth.deepen();857			omit_index += 1;858		}859860		out.retain(|_, v| v.exists_visible.is_some());861862		out863	}864	pub fn fields_ex(865		&self,866		include_hidden: bool,867		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,868	) -> Vec<IStr> {869		#[cfg(feature = "exp-preserve-order")]870		if preserve_order {871			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self872				.fields_visibility()873				.into_iter()874				.filter(|(_, d)| include_hidden || d.visible())875				.enumerate()876				.map(|(idx, (k, d))| (k, (d.sort_key(), idx)))877				.unzip();878			keys.sort_unstable_by_key(|v| v.0);879			// Reorder in-place by resulting indexes880			for i in 0..fields.len() {881				let x = fields[i].clone();882				let mut j = i;883				loop {884					let k = keys[j].1;885					keys[j].1 = j;886					if k == i {887						break;888					}889					fields[j] = fields[k].clone();890					j = k;891				}892				fields[j] = x;893			}894			return fields;895		}896897		let mut fields: Vec<_> = self898			.fields_visibility()899			.into_iter()900			.filter(|(_, d)| include_hidden || d.visible())901			.map(|(k, _)| k)902			.collect();903		fields.sort_unstable();904		fields905	}906	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {907		self.fields_ex(908			false,909			#[cfg(feature = "exp-preserve-order")]910			preserve_order,911		)912	}913	pub fn values_ex(914		&self,915		include_hidden: bool,916		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,917	) -> ArrValue {918		ArrValue::new(PickObjectValues::new(919			self.clone(),920			self.fields_ex(921				include_hidden,922				#[cfg(feature = "exp-preserve-order")]923				preserve_order,924			),925		))926	}927	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {928		self.values_ex(929			false,930			#[cfg(feature = "exp-preserve-order")]931			preserve_order,932		)933	}934	pub fn key_values_ex(935		&self,936		include_hidden: bool,937		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,938	) -> ArrValue {939		ArrValue::new(PickObjectKeyValues::new(940			self.clone(),941			self.fields_ex(942				include_hidden,943				#[cfg(feature = "exp-preserve-order")]944				preserve_order,945			),946		))947	}948	pub fn key_values(949		&self,950		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,951	) -> ArrValue {952		self.key_values_ex(953			false,954			#[cfg(feature = "exp-preserve-order")]955			preserve_order,956		)957	}958}959960#[allow(clippy::module_name_repetitions)]961#[must_use = "value not added unless binding() was called"]962pub struct ObjMemberBuilder<Kind> {963	kind: Kind,964	name: IStr,965	add: bool,966	visibility: Visibility,967	original_index: FieldIndex,968	location: Option<Span>,969}970971#[allow(clippy::missing_const_for_fn)]972impl<Kind> ObjMemberBuilder<Kind> {973	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {974		Self {975			kind,976			name,977			original_index,978			add: false,979			visibility: Visibility::Normal,980			location: None,981		}982	}983984	pub const fn with_add(mut self, add: bool) -> Self {985		self.add = add;986		self987	}988	pub fn add(self) -> Self {989		self.with_add(true)990	}991	pub fn with_visibility(mut self, visibility: Visibility) -> Self {992		self.visibility = visibility;993		self994	}995	pub fn hide(self) -> Self {996		self.with_visibility(Visibility::Hidden)997	}998	pub fn with_location(mut self, location: Span) -> Self {999		self.location = Some(location);1000		self1001	}1002	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {1003		(1004			self.kind,1005			self.name,1006			ObjMember {1007				flags: ObjFieldFlags::new(self.add, self.visibility),1008				original_index: self.original_index,1009				invoke: binding,1010				location: self.location,1011			},1012		)1013	}1014}10151016pub struct ExtendBuilder<'v>(&'v mut ObjValue);1017impl ObjMemberBuilder<ExtendBuilder<'_>> {1018	pub fn value(self, value: impl Into<Val>) {1019		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));1020	}1021	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {1022		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));1023	}1024	pub fn binding(self, binding: MaybeUnbound) {1025		let (receiver, name, member) = self.build_member(binding);1026		let new = receiver.0.clone();1027		*receiver.0 = new.extend_with_raw_member(name, member);1028	}1029}
addedcrates/jrsonnet-evaluator/src/obj/oop.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/obj/oop.rs
@@ -0,0 +1,248 @@
+use std::cell::Cell;
+use std::ops::ControlFlow;
+use std::{fmt, mem};
+
+use crate::function::{CallLocation, FuncVal};
+use crate::gc::WithCapacityExt as _;
+use crate::{
+	bail, error::ErrorKind::*, in_frame, CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
+};
+use jrsonnet_gcmodule::{Cc, Trace};
+use jrsonnet_parser::IStr;
+use rustc_hash::{FxHashMap, FxHashSet};
+
+use super::ordering::{FieldIndex, SuperDepth};
+use super::{
+	CcObjectAssertion, CcObjectCore, EnumFields, EnumFieldsHandler, FieldVisibility, GetFor,
+	HasFieldIncludeHidden, ObjMember, ObjMemberBuilder, ObjValue, ObjValueInner, ObjectAssertion,
+	ObjectCore, OmitFieldsCore, SupThis,
+};
+
+#[allow(clippy::module_name_repetitions)]
+#[derive(Trace, Default)]
+#[trace(tracking(force))]
+pub struct OopObject {
+	assertion: Option<CcObjectAssertion>,
+	this_entries: FxHashMap<IStr, ObjMember>,
+}
+impl fmt::Debug for OopObject {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		f.debug_struct("OopObject")
+			.field("this_entries", &self.this_entries)
+			.finish_non_exhaustive()
+	}
+}
+impl OopObject {
+	fn is_empty(&self) -> bool {
+		self.assertion.is_none() && self.this_entries.is_empty()
+	}
+}
+impl OopObject {
+	pub fn new(
+		this_entries: FxHashMap<IStr, ObjMember>,
+		assertion: Option<CcObjectAssertion>,
+	) -> Self {
+		Self {
+			assertion,
+			this_entries,
+		}
+	}
+}
+
+impl ObjectCore for OopObject {
+	fn enum_fields_core(
+		&self,
+		super_depth: &mut SuperDepth,
+		handler: &mut EnumFieldsHandler<'_>,
+	) -> bool {
+		for (name, member) in &self.this_entries {
+			if matches!(
+				handler(
+					*super_depth,
+					member.original_index,
+					name.clone(),
+					EnumFields::Normal(member.flags.visibility()),
+				),
+				ControlFlow::Break(())
+			) {
+				return false;
+			}
+		}
+		true
+	}
+
+	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {
+		if self.this_entries.contains_key(&name) {
+			HasFieldIncludeHidden::Exists
+		} else {
+			HasFieldIncludeHidden::NotFound
+		}
+	}
+
+	fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor> {
+		if omit_only {
+			return Ok(GetFor::NotFound);
+		}
+		match self.this_entries.get(&key) {
+			Some(k) => {
+				let v = k.invoke.evaluate(sup_this)?;
+				Ok(if k.flags.add() {
+					GetFor::SuperPlus(v)
+				} else {
+					GetFor::Final(v)
+				})
+			}
+			None => Ok(GetFor::NotFound),
+		}
+	}
+	fn field_visibility_core(&self, name: IStr) -> FieldVisibility {
+		self.this_entries
+			.get(&name)
+			.map_or(FieldVisibility::NotFound, |f| {
+				FieldVisibility::Found(f.flags.visibility())
+			})
+	}
+
+	fn run_assertions_core(&self, sup_this: SupThis) -> Result<()> {
+		if let Some(assertion) = &self.assertion {
+			assertion.0.run(sup_this.clone())?;
+		}
+		Ok(())
+	}
+}
+
+#[allow(clippy::module_name_repetitions)]
+pub struct ObjValueBuilder {
+	sup: Vec<CcObjectCore>,
+
+	new: OopObject,
+	next_field_index: FieldIndex,
+}
+impl ObjValueBuilder {
+	pub fn new() -> Self {
+		Self::with_capacity(0)
+	}
+	pub fn with_capacity(capacity: usize) -> Self {
+		Self {
+			sup: vec![],
+			new: OopObject::new(FxHashMap::with_capacity(capacity), None),
+			next_field_index: FieldIndex::default(),
+		}
+	}
+	pub fn reserve_cores(&mut self, capacity: usize) -> &mut Self {
+		self.sup.reserve_exact(capacity);
+		self
+	}
+	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {
+		self.sup.clone_from(&super_obj.0.cores);
+		self
+	}
+
+	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {
+		assert!(
+			self.new.assertion.is_none(),
+			"one OopObject can only have one assertion"
+		);
+		self.new.assertion = Some(CcObjectAssertion::new(assertion));
+		self
+	}
+	pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {
+		let field_index = self.next_field_index;
+		self.next_field_index = self.next_field_index.next();
+		ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)
+	}
+	/// Preset for common method definiton pattern:
+	/// Create a hidden field with the function value.
+	///
+	/// `.field(name).hide().value(Val::function(value))`
+	pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {
+		self.field(name).hide().value(Val::Func(value.into()));
+		self
+	}
+	pub fn try_method(
+		&mut self,
+		name: impl Into<IStr>,
+		value: impl Into<FuncVal>,
+	) -> Result<&mut Self> {
+		self.field(name).hide().try_value(Val::Func(value.into()))?;
+		Ok(self)
+	}
+
+	pub fn extend_with_core(&mut self, core: impl ObjectCore) {
+		self.commit();
+		self.sup.push(CcObjectCore::new(core));
+	}
+
+	fn commit(&mut self) {
+		if !self.new.is_empty() {
+			self.sup.push(CcObjectCore::new(mem::take(&mut self.new)));
+		}
+		self.next_field_index = FieldIndex::default();
+	}
+
+	pub fn with_fields_omitted(&mut self, omit: FxHashSet<IStr>) {
+		self.commit();
+		self.sup.push(CcObjectCore::new(OmitFieldsCore {
+			omit,
+			prev_layers: self.sup.len(),
+		}));
+	}
+
+	pub fn build(mut self) -> ObjValue {
+		self.commit();
+		if self.sup.is_empty() {
+			return ObjValue::empty();
+		}
+		ObjValue(Cc::new(ObjValueInner {
+			cores: self.sup,
+			assertions_ran: Cell::new(false),
+			value_cache: Default::default(),
+		}))
+	}
+}
+impl Default for ObjValueBuilder {
+	fn default() -> Self {
+		Self::with_capacity(0)
+	}
+}
+
+pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
+impl ObjMemberBuilder<ValueBuilder<'_>> {
+	/// Inserts value, replacing if it is already defined
+	pub fn value(self, value: impl Into<Val>) {
+		let (receiver, name, member) =
+			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));
+		let entry = receiver.0.new.this_entries.entry(name);
+		entry.insert_entry(member);
+	}
+	/// Inserts thunk, replacing if it is already defined
+	pub fn thunk(self, value: impl Into<Thunk<Val>>) {
+		let (receiver, name, member) = self.build_member(MaybeUnbound::Bound(value.into()));
+		let entry = receiver.0.new.this_entries.entry(name);
+		entry.insert_entry(member);
+	}
+
+	/// Tries to insert value, returns an error if it was already defined
+	pub fn try_value(self, value: impl Into<Val>) -> Result<()> {
+		self.try_thunk(Thunk::evaluated(value.into()))
+	}
+	pub fn try_thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {
+		self.binding(MaybeUnbound::Bound(value.into()))
+	}
+	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {
+		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)))
+	}
+	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {
+		let (receiver, name, member) = self.build_member(binding);
+		let location = member.location.clone();
+		let old = receiver.0.new.this_entries.insert(name.clone(), member);
+		if old.is_some() {
+			in_frame(
+				CallLocation(location.as_ref()),
+				|| format!("field <{}> initializtion", name.clone()),
+				|| bail!(DuplicateFieldName(name.clone())),
+			)?;
+		}
+		Ok(())
+	}
+}