git.delta.rocks / jrsonnet / refs/commits / 7bd5bbd0756a

difftreelog

source

crates/jrsonnet-evaluator/src/obj/mod.rs26.9 KiBsourcehistory
1use std::{2	any::Any,3	cell::{Cell, RefCell},4	clone::Clone,5	cmp::Reverse,6	collections::hash_map::Entry,7	fmt::{self, Debug},8	hash::{Hash, Hasher},9	num::Saturating,10	ops::ControlFlow,11};1213use educe::Educe;14use jrsonnet_gcmodule::{Acyclic, Cc, Trace, Weak, cc_dyn};15use jrsonnet_interner::IStr;16use jrsonnet_ir::Span;17use rustc_hash::{FxHashMap, FxHashSet};1819mod oop;20mod static_shape;2122pub use jrsonnet_ir::Visibility;23pub use oop::ObjValueBuilder;24pub use static_shape::{ObjShape, ObjShapeBuilder, ShapeField, StaticShapeOopObject};2526use crate::{27	CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,28	arr::{PickObjectKeyValues, PickObjectValues, arridx},29	bail,30	error::{ErrorKind::*, suggest_object_fields},31	evaluate::operator::evaluate_add_op,32	identity_hash,33	val::{ArrValue, ThunkValue},34};3536#[cfg(not(feature = "exp-preserve-order"))]37pub mod ordering {38	#![allow(39		// This module works as stub for preserve-order feature40		clippy::unused_self,41	)]4243	use jrsonnet_gcmodule::Trace;4445	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]46	pub struct FieldIndex(());47	impl FieldIndex {48		pub fn absolute(_v: u32) -> Self {49			Self(())50		}51		#[must_use]52		pub const fn next(self) -> Self {53			Self(())54		}55	}5657	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]58	pub struct SuperDepth(());59	impl SuperDepth {60		pub(super) fn deepen(self) {}61	}62}6364#[cfg(feature = "exp-preserve-order")]65pub mod ordering {66	use jrsonnet_gcmodule::Trace;6768	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]69	pub struct FieldIndex(u32);70	impl FieldIndex {71		pub fn absolute(v: u32) -> Self {72			Self(v)73		}74		#[must_use]75		pub fn next(self) -> Self {76			Self(self.0 + 1)77		}78	}7980	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]81	pub struct SuperDepth(u32);82	impl SuperDepth {83		pub(super) fn deepen(&mut self) {84			self.0 += 1;85		}86	}87}8889use ordering::{FieldIndex, SuperDepth};9091#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]92pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);93impl FieldSortKey {94	pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {95		Self(Reverse(depth), index)96	}97}9899// 0 - add100//  12 - visibility101#[derive(Clone, Copy, Acyclic)]102pub struct ObjFieldFlags(u8);103impl ObjFieldFlags {104	pub fn new(add: bool, visibility: Visibility) -> Self {105		let mut v = 0;106		if add {107			v |= 1;108		}109		v |= match visibility {110			Visibility::Normal => 0b000,111			Visibility::Hidden => 0b010,112			Visibility::Unhide => 0b100,113		};114		Self(v)115	}116	pub fn add(&self) -> bool {117		self.0 & 1 != 0118	}119	pub fn visibility(&self) -> Visibility {120		match (self.0 & 0b110) >> 1 {121			0b00 => Visibility::Normal,122			0b01 => Visibility::Hidden,123			0b10 => Visibility::Unhide,124			_ => unreachable!(),125		}126	}127}128impl Debug for ObjFieldFlags {129	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {130		f.debug_struct("ObjFieldFlags")131			.field("add", &self.add())132			.field("visibility", &self.visibility())133			.finish()134	}135}136137#[allow(clippy::module_name_repetitions)]138#[derive(Debug, Trace)]139pub struct ObjMember {140	flags: ObjFieldFlags,141	pub invoke: MaybeUnbound,142	pub location: Option<Span>,143}144145cc_dyn!(CcObjectAssertion, ObjectAssertion, pub fn new() {...});146pub trait ObjectAssertion: Trace {147	fn run(&self, sup_this: SupThis) -> Result<()>;148}149150// Field => This151152#[derive(Trace, Debug)]153enum CacheValue {154	Cached(Result<Option<Val>>),155	Pending,156}157158pub type EnumFieldsHandler<'a> =159	dyn FnMut(SuperDepth, FieldIndex, IStr, EnumFields) -> ControlFlow<()> + 'a;160161#[derive(Debug)]162pub enum EnumFields {163	Normal(Visibility),164	Omit(Skip),165}166167#[derive(Trace, Clone)]168pub enum GetFor {169	// Return value170	Final(Val),171	// Continue iterating over cores, add current value to sum stack172	SuperPlus(Val),173	// Ignore the field value, stop at this layer instead174	Omit(#[trace(skip)] Skip),175	NotFound,176}177178#[derive(Acyclic, Clone)]179pub enum FieldVisibility {180	Found(Visibility),181	Omit(Skip),182	NotFound,183}184185#[derive(Acyclic, Clone)]186pub enum HasFieldIncludeHidden {187	Exists,188	NotFound,189	Omit(Skip),190}191192type Skip = Saturating<usize>;193194pub trait ObjectCore: Trace + Any + Debug {195	// If callback returns false, iteration stops, and this call returns false.196	fn enum_fields_core(197		&self,198		super_depth: &mut SuperDepth,199		handler: &mut EnumFieldsHandler<'_>,200	) -> bool;201202	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden;203204	fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor>;205	fn field_visibility_core(&self, field: IStr) -> FieldVisibility;206207	fn run_assertions_core(&self, sup_this: SupThis) -> Result<()>;208209	fn has_assertion(&self) -> bool {210		false211	}212}213214#[derive(Clone, Trace)]215pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);216impl Debug for WeakObjValue {217	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {218		f.debug_tuple("WeakObjValue").finish()219	}220}221222impl PartialEq for WeakObjValue {223	fn eq(&self, other: &Self) -> bool {224		Weak::ptr_eq(&self.0, &other.0)225	}226}227228impl Eq for WeakObjValue {}229impl Hash for WeakObjValue {230	fn hash<H: Hasher>(&self, hasher: &mut H) {231		// Safety: usize is POD232		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };233		hasher.write_usize(addr);234	}235}236237cc_dyn!(238	#[derive(Clone, Debug)]239	CcObjectCore, ObjectCore,240	pub fn new() {...}241);242243#[derive(Trace, Educe)]244#[educe(Debug)]245struct ObjValueInner {246	cores: Vec<CcObjectCore>,247	assertions_ran: Cell<bool>,248	has_assertions: bool,249	value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,250}251252thread_local! {253	static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();254}255fn is_asserting(obj: &ObjValue) -> bool {256	RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))257}258/// Returns false if already asserting259fn start_asserting(obj: &ObjValue) -> bool {260	RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))261}262fn finish_asserting(obj: &ObjValue) {263	RUNNING_ASSERTIONS.with_borrow_mut(|v| {264		let r = v.remove(obj);265		debug_assert!(266			r,267			"finish_asserting was called before start_asserting or twice"268		);269	});270}271272thread_local! {273	static EMPTY_OBJ: ObjValue = ObjValue(Cc::new(ObjValueInner {274		cores: vec![],275		assertions_ran: Cell::new(true),276		has_assertions: false,277		value_cache: RefCell::default(),278	}))279}280281#[allow(clippy::module_name_repetitions)]282#[derive(Clone, Trace, Debug, Educe)]283#[educe(PartialEq, Hash, Eq)]284pub struct ObjValue(285	#[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,286);287288impl ObjValue {289	pub fn empty() -> Self {290		EMPTY_OBJ.with(Clone::clone)291	}292	pub fn is_empty(&self) -> bool {293		self.0.cores.is_empty() || self.len() == 0294	}295}296297#[derive(Trace, Debug)]298pub(crate) struct StandaloneSuperCore {299	sup: CoreIdx,300	this: ObjValue,301}302impl ObjectCore for StandaloneSuperCore {303	fn enum_fields_core(304		&self,305		super_depth: &mut SuperDepth,306		handler: &mut EnumFieldsHandler<'_>,307	) -> bool {308		self.this.enum_fields_idx(super_depth, handler, self.sup)309	}310311	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {312		if self.this.has_field_include_hidden_idx(name, self.sup) {313			HasFieldIncludeHidden::Exists314		} else {315			HasFieldIncludeHidden::NotFound316		}317	}318319	fn get_for_core(&self, key: IStr, _sup_this: SupThis, omit_only: bool) -> Result<GetFor> {320		if omit_only {321			return Ok(GetFor::NotFound);322		}323		let v = self.this.get_idx(key, self.sup)?;324		Ok(v.map_or(GetFor::NotFound, GetFor::Final))325	}326327	fn field_visibility_core(&self, field: IStr) -> FieldVisibility {328		self.this329			.field_visibility_idx(field, self.sup)330			.map_or(FieldVisibility::NotFound, FieldVisibility::Found)331	}332333	fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {334		self.this.run_assertions()335	}336}337338#[derive(Debug, Acyclic)]339struct OmitFieldsCore {340	omit: FxHashSet<IStr>,341	prev_layers: usize,342}343impl ObjectCore for OmitFieldsCore {344	fn enum_fields_core(345		&self,346		super_depth: &mut SuperDepth,347		handler: &mut EnumFieldsHandler<'_>,348	) -> bool {349		let mut fi = FieldIndex::default();350		for f in &self.omit {351			if handler(352				*super_depth,353				fi,354				f.clone(),355				EnumFields::Omit(Saturating(self.prev_layers)),356			) == ControlFlow::Break(())357			{358				return false;359			}360			fi = fi.next();361		}362		true363	}364365	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {366		if self.omit.contains(&name) {367			return HasFieldIncludeHidden::Omit(Saturating(self.prev_layers));368		}369		HasFieldIncludeHidden::NotFound370	}371372	fn get_for_core(&self, key: IStr, _sup_this: SupThis, _omit_only: bool) -> Result<GetFor> {373		if self.omit.contains(&key) {374			return Ok(GetFor::Omit(Saturating(self.prev_layers)));375		}376		Ok(GetFor::NotFound)377	}378379	fn field_visibility_core(&self, field: IStr) -> FieldVisibility {380		if self.omit.contains(&field) {381			return FieldVisibility::Omit(Saturating(self.prev_layers));382		}383		FieldVisibility::NotFound384	}385386	fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {387		Ok(())388	}389}390391#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]392struct CoreIdx {393	idx: usize,394}395impl CoreIdx {396	fn super_exists(self) -> bool {397		self.idx != 0398	}399}400#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]401pub struct SupThis {402	sup: CoreIdx,403	this: ObjValue,404}405impl SupThis {406	/// Create a `SupThis` for a freshly constructed object (no super).407	pub fn new(this: ObjValue) -> Self {408		Self {409			sup: CoreIdx {410				idx: this.0.cores.len(),411			},412			this,413		}414	}415	pub fn has_super(&self) -> bool {416		self.sup.super_exists()417	}418	/// Implementation of `"field" in super` operation,419	/// works faster than standalone super path.420	///421	/// In case of no `super` existence, returns false.422	pub fn field_in_super(&self, field: IStr) -> bool {423		self.this.has_field_include_hidden_idx(field, self.sup)424	}425	/// Implementation of `super.field` operation,426	/// works faster than standalone super path.427	///428	/// In case of no `super` existence, returns `NoSuperFound`429	pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {430		if !self.sup.super_exists() {431			bail!(NoSuperFound);432		}433		self.this.get_idx(field, self.sup)434	}435	/// `super` with `self` overriden for top-level lookups.436	/// Exists when super appears outside of `super.field`/`"field" in super` expressions437	/// Exclusive to jrsonnet.438	///439	/// Returns None if no `super` found440	pub fn standalone_super(&self) -> Option<ObjValue> {441		if !self.sup.super_exists() {442			return None;443		}444		let mut out = ObjValue::builder();445		out.extend_with_core(StandaloneSuperCore {446			sup: self.sup,447			this: self.this.clone(),448		});449		Some(out.build())450	}451	pub fn this(&self) -> &ObjValue {452		&self.this453	}454	pub fn downgrade(self) -> WeakSupThis {455		WeakSupThis {456			sup: self.sup,457			this: self.this.downgrade(),458		}459	}460}461#[derive(Trace, PartialEq, Eq, Hash, Debug)]462pub struct WeakSupThis {463	sup: CoreIdx,464	this: WeakObjValue,465}466467impl ObjValue {468	pub fn builder() -> ObjValueBuilder {469		ObjValueBuilder::new()470	}471	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {472		ObjValueBuilder::with_capacity(capacity)473	}474	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {475		let mut out = ObjValueBuilder::with_capacity(1);476		out.with_super(self);477		let mut member = out.field(key);478		if value.flags.add() {479			member = member.add();480		}481		if let Some(loc) = value.location {482			member = member.with_location(loc);483		}484		let _ = member485			.with_visibility(value.flags.visibility())486			.binding(value.invoke);487		out.build()488	}489	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {490		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())491	}492493	pub fn extend(&mut self) -> ObjValueBuilder {494		let mut out = ObjValueBuilder::new();495		out.with_super(self.clone());496		out497	}498499	#[must_use]500	pub fn extend_from(&self, sup: Self) -> Self {501		let mut cores = Vec::with_capacity(sup.0.cores.len() + self.0.cores.len());502		cores.extend(sup.0.cores.iter().cloned());503		cores.extend(self.0.cores.iter().cloned());504505		let has_assertions = sup.0.has_assertions || self.0.has_assertions;506		ObjValue(Cc::new(ObjValueInner {507			cores,508			value_cache: RefCell::default(),509			assertions_ran: Cell::new(!has_assertions),510			has_assertions,511		}))512	}513	// #[must_use]514	// pub fn with_this(&self, this: Self) -> Self {515	// 	self.0.with_this(self.clone(), this)516	// }517	/// Returns amount of visible object fields518	/// If object only contains hidden fields - may return zero.519	pub fn len(&self) -> usize {520		self.fields_visibility()521			.values()522			.filter(|d| d.visible())523			.count()524	}525	pub fn len32(&self) -> u32 {526		arridx(self.len())527	}528	/// For each field, calls callback.529	/// If callback returns false - ends iteration prematurely.530	///531	/// Returns false if ended prematurely532	pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {533		let mut super_depth = SuperDepth::default();534		self.enum_fields_idx(535			&mut super_depth,536			handler,537			CoreIdx {538				idx: self.0.cores.len(),539			},540		)541	}542543	fn iter_cores(&self, idx: CoreIdx) -> impl Iterator<Item = &CcObjectCore> {544		self.0.cores.iter().take(idx.idx).rev()545	}546	fn iter_cores_enumerate(&self, idx: CoreIdx) -> impl Iterator<Item = (CoreIdx, &CcObjectCore)> {547		self.0548			.cores549			.iter()550			.take(idx.idx)551			.enumerate()552			.rev()553			.map(|(idx, o)| (CoreIdx { idx }, o))554	}555556	fn enum_fields_idx(557		&self,558		super_depth: &mut SuperDepth,559		handler: &mut EnumFieldsHandler<'_>,560		idx: CoreIdx,561	) -> bool {562		for core in self.iter_cores(idx) {563			if !core.0.enum_fields_core(super_depth, handler) {564				return false;565			}566			super_depth.deepen();567		}568		true569	}570571	pub fn has_field_include_hidden(&self, name: IStr) -> bool {572		self.has_field_include_hidden_idx(573			name,574			CoreIdx {575				idx: self.0.cores.len(),576			},577		)578	}579	fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {580		let mut skip = Saturating(0usize);581		for ele in self.iter_cores(core) {582			match ele.0.has_field_include_hidden_core(name.clone()) {583				HasFieldIncludeHidden::Exists => {584					if skip.0 == 0 {585						return true;586					}587				}588				HasFieldIncludeHidden::Omit(new_skip) => {589					// +1 including this core590					skip = skip.max(new_skip + Saturating(1));591				}592				HasFieldIncludeHidden::NotFound => {}593			}594			skip -= 1;595		}596		false597	}598	pub fn has_field(&self, name: IStr) -> bool {599		match self.field_visibility(name) {600			Some(Visibility::Unhide | Visibility::Normal) => true,601			Some(Visibility::Hidden) | None => false,602		}603	}604	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {605		if include_hidden {606			self.has_field_include_hidden(name)607		} else {608			self.has_field(name)609		}610	}611	pub fn get(&self, key: IStr) -> Result<Option<Val>> {612		self.get_idx(613			key,614			CoreIdx {615				idx: self.0.cores.len(),616			},617		)618	}619620	fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {621		let cache_key = (key.clone(), core);622		{623			let mut cache = self.0.value_cache.borrow_mut();624			// entry_ref candidate?625			match cache.entry(cache_key.clone()) {626				Entry::Occupied(v) => match v.get() {627					CacheValue::Cached(v) => return v.clone(),628					CacheValue::Pending => {629						if !is_asserting(self) {630							bail!(InfiniteRecursionDetected);631						}632					}633				},634				Entry::Vacant(v) => {635					v.insert(CacheValue::Pending);636				}637			}638		}639		let result = self.get_idx_uncached(key, core);640		{641			let mut cache = self.0.value_cache.borrow_mut();642			cache.insert(cache_key, CacheValue::Cached(result.clone()));643		}644		result645	}646	fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {647		self.run_assertions()?;648		let mut first_add = None;649		let mut add_stack: Vec<Val> = Vec::new();650		let mut skip = Saturating(0);651		for (sup, core) in self.iter_cores_enumerate(core) {652			let sup_this = SupThis {653				sup,654				this: self.clone(),655			};656			match core.0.get_for_core(key.clone(), sup_this, skip.0 != 0)? {657				GetFor::Final(val) if first_add.is_none() => {658					if skip.0 == 0 {659						return Ok(Some(val));660					}661				}662				GetFor::Final(val) => {663					if skip.0 == 0 {664						add_stack.push(val);665						break;666					}667				}668				GetFor::SuperPlus(val) => {669					if skip.0 == 0 {670						if first_add.is_none() {671							first_add = Some(val);672						} else {673							add_stack.push(val);674						}675					}676				}677				GetFor::Omit(new_skip) => {678					skip = skip.max(new_skip + Saturating(1));679				}680				GetFor::NotFound => {}681			}682			skip -= 1;683		}684		let Some(first) = first_add else {685			if add_stack.is_empty() {686				return Ok(None);687			}688			return Ok(Some(add_stack.pop().expect("single element on stack")));689		};690		if add_stack.is_empty() {691			return Ok(Some(first));692		}693		add_stack.insert(0, first);694		let mut values = add_stack.into_iter().rev();695		let init = values.next().expect("at least 2 elements");696697		values698			.try_fold(init, |a, b| evaluate_add_op(&a, &b))699			.map(Some)700	}701702	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {703		let Some(value) = self.get(key.clone())? else {704			let suggestions = suggest_object_fields(self, key.clone());705			bail!(NoSuchField(key, suggestions))706		};707		Ok(value)708	}709710	fn field_visibility(&self, field: IStr) -> Option<Visibility> {711		self.field_visibility_idx(712			field,713			CoreIdx {714				idx: self.0.cores.len(),715			},716		)717	}718	fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {719		let mut exists = false;720		let mut skip = Saturating(0usize);721		for ele in self.iter_cores(core) {722			let vis = ele.0.field_visibility_core(field.clone());723			match vis {724				FieldVisibility::Found(vis @ (Visibility::Unhide | Visibility::Hidden)) => {725					if skip.0 == 0 {726						return Some(vis);727					}728				}729				FieldVisibility::Found(Visibility::Normal) => {730					if skip.0 == 0 {731						exists = true;732					}733				}734				FieldVisibility::NotFound => {}735				FieldVisibility::Omit(new_skip) => {736					// +1 including this core737					skip = skip.max(new_skip + Saturating(1));738				}739			}740			skip -= 1;741		}742		exists.then_some(Visibility::Normal)743	}744745	pub fn run_assertions(&self) -> Result<()> {746		if self.0.assertions_ran.get() {747			return Ok(());748		}749		if !start_asserting(self) {750			return Ok(());751		}752		for (idx, ele) in self.0.cores.iter().enumerate() {753			let sup_this = SupThis {754				sup: CoreIdx { idx },755				this: self.clone(),756			};757			ele.0.run_assertions_core(sup_this).inspect_err(|_e| {758				finish_asserting(self);759			})?;760		}761		finish_asserting(self);762		self.0.assertions_ran.set(true);763		Ok(())764	}765766	pub fn iter(767		&self,768		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,769	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {770		let fields = self.fields(771			#[cfg(feature = "exp-preserve-order")]772			preserve_order,773		);774		fields.into_iter().map(|field| {775			(776				field.clone(),777				self.get(field)778					.map(|opt| opt.expect("iterating over keys, field exists")),779			)780		})781	}782	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {783		#[derive(Trace)]784		struct ObjFieldThunk {785			obj: ObjValue,786			key: IStr,787		}788		impl ThunkValue for ObjFieldThunk {789			type Output = Val;790791			fn get(&self) -> Result<Self::Output> {792				self.obj793					.get(self.key.clone())794					.transpose()795					.expect("field existence checked")796			}797		}798799		if !self.has_field_ex(key.clone(), true) {800			return None;801		}802803		Some(Thunk::new(ObjFieldThunk {804			obj: self.clone(),805			key,806		}))807	}808	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {809		#[derive(Trace)]810		struct ObjFieldThunk {811			obj: ObjValue,812			key: IStr,813		}814		impl ThunkValue for ObjFieldThunk {815			type Output = Val;816817			fn get(&self) -> Result<Self::Output> {818				self.obj.get_or_bail(self.key.clone())819			}820		}821822		Thunk::new(ObjFieldThunk {823			obj: self.clone(),824			key,825		})826	}827828	#[allow(dead_code, reason = "used in object ...rest destructuring")]829	pub(crate) fn as_standalone(&self) -> StandaloneSuperCore {830		StandaloneSuperCore {831			sup: CoreIdx {832				idx: self.0.cores.len(),833			},834			this: self.clone(),835		}836	}837	pub fn ptr_eq(a: &Self, b: &Self) -> bool {838		Cc::ptr_eq(&a.0, &b.0)839	}840	pub fn downgrade(self) -> WeakObjValue {841		WeakObjValue(self.0.downgrade())842	}843}844845#[derive(Debug)]846struct FieldVisibilityData {847	omitted_until: Saturating<usize>,848	exists_visible: Option<Visibility>,849	#[allow(dead_code, reason = "used for exp-object-ordering, ZST otherwise")]850	key: FieldSortKey,851}852impl FieldVisibilityData {853	fn visible(&self) -> bool {854		self.exists_visible855			.expect("non-existing fields shall be dropped at the end of fn fields_visibility()")856			.is_visible()857	}858	#[allow(dead_code, reason = "used for exp-object-ordering, ZST otherwise")]859	fn sort_key(&self) -> FieldSortKey {860		self.key861	}862}863864impl ObjValue {865	fn fields_visibility(&self) -> FxHashMap<IStr, FieldVisibilityData> {866		let mut out = FxHashMap::default();867868		let mut super_depth = SuperDepth::default();869		let mut omit_index = Saturating(0);870		for core in self.0.cores.iter().rev() {871			core.0872				.enum_fields_core(&mut super_depth, &mut |depth, index, name, visibility| {873					let entry = out.entry(name);874					let data = entry.or_insert_with(|| FieldVisibilityData {875						exists_visible: None,876						key: FieldSortKey::new(depth, index),877						omitted_until: omit_index,878					});879					match visibility {880						EnumFields::Omit(new_skip) => {881							// +1 including this core882							data.omitted_until = data883								.omitted_until884								.max(omit_index + new_skip + Saturating(1));885						}886						EnumFields::Normal(Visibility::Normal) => {887							if data.omitted_until <= omit_index && data.exists_visible.is_none() {888								data.exists_visible = Some(Visibility::Normal);889							}890						}891						EnumFields::Normal(Visibility::Hidden) => {892							if data.omitted_until <= omit_index {893								data.exists_visible = Some(match data.exists_visible {894									// We're iterating in reverse, later unhide is preserved895									Some(Visibility::Unhide) => Visibility::Unhide,896									_ => Visibility::Hidden,897								});898							}899						}900						EnumFields::Normal(Visibility::Unhide) => {901							if data.omitted_until <= omit_index {902								data.exists_visible = Some(match data.exists_visible {903									// We're iterating in reverse, later hide is preserved904									Some(Visibility::Hidden) => Visibility::Hidden,905									_ => Visibility::Unhide,906								});907							}908						}909					}910					ControlFlow::Continue(())911				});912913			super_depth.deepen();914			omit_index += 1;915		}916917		out.retain(|_, v| v.exists_visible.is_some());918919		out920	}921	pub fn fields_with_visibility(922		&self,923		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,924	) -> Vec<(IStr, Visibility)> {925		#[cfg(feature = "exp-preserve-order")]926		if preserve_order {927			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self928				.fields_visibility()929				.into_iter()930				.enumerate()931				.map(|(idx, (k, d))| {932					(933						(934							k,935							d.exists_visible.expect("non-existing fields filtered out"),936						),937						(d.sort_key(), idx),938					)939				})940				.unzip();941			keys.sort_unstable_by_key(|v| v.0);942			for i in 0..fields.len() {943				let x = fields[i].clone();944				let mut j = i;945				loop {946					let k = keys[j].1;947					keys[j].1 = j;948					if k == i {949						break;950					}951					fields[j] = fields[k].clone();952					j = k;953				}954				fields[j] = x;955			}956			return fields;957		}958		let mut fields: Vec<_> = self959			.fields_visibility()960			.into_iter()961			.map(|(k, d)| {962				(963					k,964					d.exists_visible.expect("non-existing fields filtered out"),965				)966			})967			.collect();968		fields.sort_unstable_by(|a, b| a.0.cmp(&b.0));969		fields970	}971	pub fn fields_ex(972		&self,973		include_hidden: bool,974		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,975	) -> Vec<IStr> {976		#[cfg(feature = "exp-preserve-order")]977		if preserve_order {978			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self979				.fields_visibility()980				.into_iter()981				.filter(|(_, d)| include_hidden || d.visible())982				.enumerate()983				.map(|(idx, (k, d))| (k, (d.sort_key(), idx)))984				.unzip();985			keys.sort_unstable_by_key(|v| v.0);986			// Reorder in-place by resulting indexes987			for i in 0..fields.len() {988				let x = fields[i].clone();989				let mut j = i;990				loop {991					let k = keys[j].1;992					keys[j].1 = j;993					if k == i {994						break;995					}996					fields[j] = fields[k].clone();997					j = k;998				}999				fields[j] = x;1000			}1001			return fields;1002		}10031004		let mut fields: Vec<_> = self1005			.fields_visibility()1006			.into_iter()1007			.filter(|(_, d)| include_hidden || d.visible())1008			.map(|(k, _)| k)1009			.collect();1010		fields.sort_unstable();1011		fields1012	}1013	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {1014		self.fields_ex(1015			false,1016			#[cfg(feature = "exp-preserve-order")]1017			preserve_order,1018		)1019	}1020	pub fn values_ex(1021		&self,1022		include_hidden: bool,1023		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,1024	) -> ArrValue {1025		ArrValue::new(PickObjectValues::new(1026			self.clone(),1027			self.fields_ex(1028				include_hidden,1029				#[cfg(feature = "exp-preserve-order")]1030				preserve_order,1031			),1032		))1033	}1034	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {1035		self.values_ex(1036			false,1037			#[cfg(feature = "exp-preserve-order")]1038			preserve_order,1039		)1040	}1041	pub fn key_values_ex(1042		&self,1043		include_hidden: bool,1044		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,1045	) -> ArrValue {1046		ArrValue::new(PickObjectKeyValues::new(1047			self.clone(),1048			self.fields_ex(1049				include_hidden,1050				#[cfg(feature = "exp-preserve-order")]1051				preserve_order,1052			),1053		))1054	}1055	pub fn key_values(1056		&self,1057		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,1058	) -> ArrValue {1059		self.key_values_ex(1060			false,1061			#[cfg(feature = "exp-preserve-order")]1062			preserve_order,1063		)1064	}1065}10661067#[allow(clippy::module_name_repetitions)]1068#[must_use = "value not added unless binding() was called"]1069pub struct ObjMemberBuilder<Kind> {1070	kind: Kind,1071	name: IStr,1072	add: bool,1073	visibility: Visibility,1074	original_index: FieldIndex,1075	location: Option<Span>,1076}10771078#[allow(clippy::missing_const_for_fn)]1079impl<Kind> ObjMemberBuilder<Kind> {1080	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {1081		Self {1082			kind,1083			name,1084			original_index,1085			add: false,1086			visibility: Visibility::Normal,1087			location: None,1088		}1089	}10901091	pub const fn with_add(mut self, add: bool) -> Self {1092		self.add = add;1093		self1094	}1095	pub fn add(self) -> Self {1096		self.with_add(true)1097	}1098	pub fn with_visibility(mut self, visibility: Visibility) -> Self {1099		self.visibility = visibility;1100		self1101	}1102	pub fn hide(self) -> Self {1103		self.with_visibility(Visibility::Hidden)1104	}1105	pub fn with_location(mut self, location: Span) -> Self {1106		self.location = Some(location);1107		self1108	}1109	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, FieldIndex, ObjMember) {1110		(1111			self.kind,1112			self.name,1113			self.original_index,1114			ObjMember {1115				flags: ObjFieldFlags::new(self.add, self.visibility),1116				invoke: binding,1117				location: self.location,1118			},1119		)1120	}1121}11221123pub struct ExtendBuilder<'v>(&'v mut ObjValue);1124impl ObjMemberBuilder<ExtendBuilder<'_>> {1125	pub fn value(self, value: impl Into<Val>) {1126		self.binding(MaybeUnbound::Const(value.into()));1127	}1128	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {1129		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));1130	}1131	pub fn binding(self, binding: MaybeUnbound) {1132		let (receiver, name, _, member) = self.build_member(binding);1133		let new = receiver.0.clone();1134		*receiver.0 = new.extend_with_raw_member(name, member);1135	}1136}