git.delta.rocks / jrsonnet / refs/commits / 1c69f1ac7855

difftreelog

source

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