git.delta.rocks / jrsonnet / refs/commits / 27958b04316f

difftreelog

refactor cleanup

pyypxomoYaroslav Bolyukin2026-03-23parent: #325f0a1.patch.diff
in: master

9 files changed

modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -45,8 +45,8 @@
 /// If this does not match `LIB_JSONNET_VERSION`
 /// then there is a mismatch between header and compiled library.
 #[no_mangle]
-pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {
-	b"v0.20.0\0"
+pub extern "C" fn jsonnet_version() -> &'static [u8; 12] {
+	b"v0.22.0-rc1\0"
 }
 
 unsafe fn parse_path(input: &CStr) -> Cow<'_, Path> {
modifiedcrates/jrsonnet-evaluator/src/async_import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/async_import.rs
+++ b/crates/jrsonnet-evaluator/src/async_import.rs
@@ -3,11 +3,7 @@
 
 use jrsonnet_gcmodule::Acyclic;
 use jrsonnet_ir::visit::Visitor;
-use jrsonnet_ir::{
-	ArgsDesc, AssertExpr, AssertStmt, BindSpec, CompSpec, Destruct, Expr, ExprParam, ExprParams,
-	FieldMember, FieldName, ForSpecData, IStr, IfElse, IfSpecData, ImportKind, ObjBody, Slice,
-	SliceDesc, Source, SourcePath, Spanned,
-};
+use jrsonnet_ir::{IStr, Source, SourcePath};
 use rustc_hash::FxHashMap;
 
 use crate::{AsPathLike, FileData, ImportResolver, ResolvePathOwned, State};
@@ -23,7 +19,7 @@
 		self.0.push(Import {
 			path: ResolvePathOwned::Str(value.to_string()),
 			expression,
-		})
+		});
 	}
 }
 
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -5,7 +5,7 @@
 extern crate self as jrsonnet_evaluator;
 
 mod arr;
-// pub mod async_import;
+pub mod async_import;
 mod ctx;
 mod dynamic;
 pub mod error;
modifiedcrates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/obj/mod.rs
1use std::{2	any::Any, cell::{Cell, RefCell}, clone::Clone, cmp::Reverse, collections::hash_map::Entry, fmt::{self, Debug}, hash::{Hash, Hasher}, num::Saturating, ops::ControlFlow3};45use educe::Educe;6use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace, Weak};7use jrsonnet_interner::IStr;8use jrsonnet_ir::Span;9use rustc_hash::{FxHashMap, FxHashSet};1011mod oop;1213pub use jrsonnet_ir::Visibility;14pub use oop::ObjValueBuilder;1516use crate::{17	arr::{PickObjectKeyValues, PickObjectValues},18	bail,19	error::{suggest_object_fields, ErrorKind::*},20	identity_hash,21	operator::evaluate_add_op,22	val::{ArrValue, ThunkValue},23	CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,24};2526#[cfg(not(feature = "exp-preserve-order"))]27pub mod 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, PartialEq, Eq, PartialOrd, Ord)]36	pub struct FieldIndex(());37	impl FieldIndex {38		pub fn absolute(_v: u32) -> Self {39			Self(())40		}41		#[must_use]42		pub const fn next(self) -> Self {43			Self(())44		}45	}4647	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]48	pub struct SuperDepth(());49	impl SuperDepth {50		pub(super) fn deepen(self) {}51	}52}5354#[cfg(feature = "exp-preserve-order")]55pub mod ordering {56	use jrsonnet_gcmodule::Trace;5758	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]59	pub struct FieldIndex(u32);60	impl FieldIndex {61		pub fn absolute(v: u32) -> Self {62			Self(v)63		}64		#[must_use]65		pub fn next(self) -> Self {66			Self(self.0 + 1)67		}68	}6970	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]71	pub struct SuperDepth(u32);72	impl SuperDepth {73		pub(super) fn deepen(&mut self) {74			self.0 += 1;75		}76	}77}7879use ordering::{FieldIndex, SuperDepth};8081#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]82pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);83impl FieldSortKey {84	pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {85		Self(Reverse(depth), index)86	}87}8889// 0 - add90//  12 - visibility91#[derive(Clone, Copy)]92pub struct ObjFieldFlags(u8);93impl ObjFieldFlags {94	fn new(add: bool, visibility: Visibility) -> Self {95		let mut v = 0;96		if add {97			v |= 1;98		}99		v |= match visibility {100			Visibility::Normal => 0b000,101			Visibility::Hidden => 0b010,102			Visibility::Unhide => 0b100,103		};104		Self(v)105	}106	pub fn add(&self) -> bool {107		self.0 & 1 != 0108	}109	pub fn visibility(&self) -> Visibility {110		match (self.0 & 0b110) >> 1 {111			0b00 => Visibility::Normal,112			0b01 => Visibility::Hidden,113			0b10 => Visibility::Unhide,114			_ => unreachable!(),115		}116	}117}118impl Debug for ObjFieldFlags {119	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {120		f.debug_struct("ObjFieldFlags")121			.field("add", &self.add())122			.field("visibility", &self.visibility())123			.finish()124	}125}126127#[allow(clippy::module_name_repetitions)]128#[derive(Debug, Trace)]129pub struct ObjMember {130	#[trace(skip)]131	flags: ObjFieldFlags,132	original_index: FieldIndex,133	pub invoke: MaybeUnbound,134	pub location: Option<Span>,135}136137cc_dyn!(CcObjectAssertion, ObjectAssertion);138pub trait ObjectAssertion: Trace {139	fn run(&self, sup_this: SupThis) -> Result<()>;140}141142// Field => This143144#[derive(Trace, Debug)]145enum CacheValue {146	Cached(Result<Option<Val>>),147	Pending,148}149150pub type EnumFieldsHandler<'a> =151	dyn FnMut(SuperDepth, FieldIndex, IStr, EnumFields) -> ControlFlow<()> + 'a;152153pub enum EnumFields {154	Normal(Visibility),155	Omit(Skip),156}157158#[derive(Trace, Clone)]159pub enum GetFor {160	// Return value161	Final(Val),162	// Continue iterating over cores, add current value to sum stack163	SuperPlus(Val),164	// Ignore the field value, stop at this layer instead165	Omit(#[trace(skip)] Skip),166	NotFound,167}168169#[derive(Acyclic, Clone)]170pub enum FieldVisibility {171	Found(Visibility),172	Omit(Skip),173	NotFound,174}175176#[derive(Acyclic, Clone)]177pub enum HasFieldIncludeHidden {178	Exists,179	NotFound,180	Omit(Skip),181}182183type Skip = Saturating<usize>;184185pub trait ObjectCore: Trace + Any + Debug {186	// If callback returns false, iteration stops, and this call returns false.187	fn enum_fields_core(188		&self,189		super_depth: &mut SuperDepth,190		handler: &mut EnumFieldsHandler<'_>,191	) -> bool;192193	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden;194195	fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor>;196	fn field_visibility_core(&self, field: IStr) -> FieldVisibility;197198	fn run_assertions_core(&self, sup_this: SupThis) -> Result<()>;199}200201#[derive(Clone, Trace)]202pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);203impl Debug for WeakObjValue {204	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {205		f.debug_tuple("WeakObjValue").finish()206	}207}208209impl PartialEq for WeakObjValue {210	fn eq(&self, other: &Self) -> bool {211		Weak::ptr_eq(&self.0, &other.0)212	}213}214215impl Eq for WeakObjValue {}216impl Hash for WeakObjValue {217	fn hash<H: Hasher>(&self, hasher: &mut H) {218		// Safety: usize is POD219		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };220		hasher.write_usize(addr);221	}222}223224cc_dyn!(225	#[derive(Clone, Debug)]226	CcObjectCore, ObjectCore,227	pub fn new() {...}228);229#[derive(Trace, Educe)]230#[educe(Debug)]231struct ObjValueInner {232	cores: Vec<CcObjectCore>,233	assertions_ran: Cell<bool>,234	#[trace(skip)]235	has_assertions: bool,236	value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,237}238239thread_local! {240	static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();241}242fn is_asserting(obj: &ObjValue) -> bool {243	RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))244}245/// Returns false if already asserting246fn start_asserting(obj: &ObjValue) -> bool {247	RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))248}249fn finish_asserting(obj: &ObjValue) {250	RUNNING_ASSERTIONS.with_borrow_mut(|v| {251		let r = v.remove(obj);252		debug_assert!(253			r,254			"finish_asserting was called before start_asserting or twice"255		);256	});257}258259thread_local! {260	static EMPTY_OBJ: ObjValue = ObjValue(Cc::new(ObjValueInner {261		cores: vec![],262		assertions_ran: Cell::new(true),263		has_assertions: false,264		value_cache: RefCell::default(),265	}))266}267268#[allow(clippy::module_name_repetitions)]269#[derive(Clone, Trace, Debug, Educe)]270#[educe(PartialEq, Hash, Eq)]271pub struct ObjValue(272	#[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,273);274275impl ObjValue {276	pub fn empty() -> Self {277		EMPTY_OBJ.with(Clone::clone)278	}279	pub fn is_empty(&self) -> bool {280		self.0.cores.is_empty() || self.len() == 0281	}282}283284#[derive(Trace, Debug)]285struct StandaloneSuperCore {286	sup: CoreIdx,287	this: ObjValue,288}289impl ObjectCore for StandaloneSuperCore {290	fn enum_fields_core(291		&self,292		super_depth: &mut SuperDepth,293		handler: &mut EnumFieldsHandler<'_>,294	) -> bool {295		self.this.enum_fields_idx(super_depth, handler, self.sup)296	}297298	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {299		if self.this.has_field_include_hidden_idx(name, self.sup) {300			HasFieldIncludeHidden::Exists301		} else {302			HasFieldIncludeHidden::NotFound303		}304	}305306	fn get_for_core(&self, key: IStr, _sup_this: SupThis, omit_only: bool) -> Result<GetFor> {307		if omit_only {308			return Ok(GetFor::NotFound);309		}310		let v = self.this.get_idx(key, self.sup)?;311		Ok(v.map_or(GetFor::NotFound, GetFor::Final))312	}313314	fn field_visibility_core(&self, field: IStr) -> FieldVisibility {315		self.this316			.field_visibility_idx(field, self.sup)317			.map_or(FieldVisibility::NotFound, FieldVisibility::Found)318	}319320	fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {321		self.this.run_assertions()322	}323}324325#[derive(Debug, Acyclic)]326struct OmitFieldsCore {327	omit: FxHashSet<IStr>,328	prev_layers: usize,329}330impl ObjectCore for OmitFieldsCore {331	fn enum_fields_core(332		&self,333		super_depth: &mut SuperDepth,334		handler: &mut EnumFieldsHandler<'_>,335	) -> bool {336		let mut fi = FieldIndex::default();337		for f in &self.omit {338			if handler(339				*super_depth,340				fi,341				f.clone(),342				EnumFields::Omit(Saturating(self.prev_layers)),343			) == ControlFlow::Break(())344			{345				return false;346			}347			fi = fi.next();348		}349		true350	}351352	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {353		if self.omit.contains(&name) {354			return HasFieldIncludeHidden::Omit(Saturating(self.prev_layers));355		}356		HasFieldIncludeHidden::NotFound357	}358359	fn get_for_core(&self, key: IStr, _sup_this: SupThis, _omit_only: bool) -> Result<GetFor> {360		if self.omit.contains(&key) {361			return Ok(GetFor::Omit(Saturating(self.prev_layers)));362		}363		Ok(GetFor::NotFound)364	}365366	fn field_visibility_core(&self, field: IStr) -> FieldVisibility {367		if self.omit.contains(&field) {368			return FieldVisibility::Omit(Saturating(self.prev_layers));369		}370		FieldVisibility::NotFound371	}372373	fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {374		Ok(())375	}376}377378#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]379struct CoreIdx {380	idx: usize,381}382impl CoreIdx {383	fn super_exists(self) -> bool {384		self.idx != 0385	}386}387#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]388pub struct SupThis {389	sup: CoreIdx,390	this: ObjValue,391}392impl SupThis {393	pub fn has_super(&self) -> bool {394		self.sup.super_exists()395	}396	/// Implementation of `"field" in super` operation,397	/// works faster than standalone super path.398	///399	/// In case of no `super` existence, returns false.400	pub fn field_in_super(&self, field: IStr) -> bool {401		self.this.has_field_include_hidden_idx(field, self.sup)402	}403	/// Implementation of `super.field` operation,404	/// works faster than standalone super path.405	///406	/// In case of no `super` existence, returns `NoSuperFound`407	pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {408		if !self.sup.super_exists() {409			bail!(NoSuperFound);410		}411		self.this.get_idx(field, self.sup)412	}413	/// `super` with `self` overriden for top-level lookups.414	/// Exists when super appears outside of `super.field`/`"field" in super` expressions415	/// Exclusive to jrsonnet.416	///417	/// Might return `NoSuperFound` error.418	pub fn standalone_super(&self) -> Result<ObjValue> {419		if !self.sup.super_exists() {420			bail!(NoSuperFound)421		}422		let mut out = ObjValue::builder();423		out.reserve_cores(1).extend_with_core(StandaloneSuperCore {424			sup: self.sup,425			this: self.this.clone(),426		});427		Ok(out.build())428	}429	pub fn this(&self) -> &ObjValue {430		&self.this431	}432	pub fn downgrade(self) -> WeakSupThis {433		WeakSupThis {434			sup: self.sup,435			this: self.this.downgrade(),436		}437	}438}439#[derive(Trace, PartialEq, Eq, Hash, Debug)]440pub struct WeakSupThis {441	sup: CoreIdx,442	this: WeakObjValue,443}444445impl ObjValue {446	pub fn builder() -> ObjValueBuilder {447		ObjValueBuilder::new()448	}449	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {450		ObjValueBuilder::with_capacity(capacity)451	}452	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {453		let mut out = ObjValueBuilder::with_capacity(1);454		out.with_super(self);455		let mut member = out.field(key);456		if value.flags.add() {457			member = member.add();458		}459		if let Some(loc) = value.location {460			member = member.with_location(loc);461		}462		let _ = member463			.with_visibility(value.flags.visibility())464			.binding(value.invoke);465		out.build()466	}467	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {468		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())469	}470471	pub fn extend(&mut self) -> ObjValueBuilder {472		let mut out = ObjValueBuilder::new();473		out.with_super(self.clone());474		out475	}476477	#[must_use]478	pub fn extend_from(&self, sup: Self) -> Self {479		let mut cores = Vec::with_capacity(sup.0.cores.len() + self.0.cores.len());480		cores.extend(sup.0.cores.iter().cloned());481		cores.extend(self.0.cores.iter().cloned());482		let has_assertions = sup.0.has_assertions || self.0.has_assertions;483		ObjValue(Cc::new(ObjValueInner {484			cores,485			value_cache: RefCell::default(),486			assertions_ran: Cell::new(!has_assertions),487			has_assertions,488		}))489	}490	// #[must_use]491	// pub fn with_this(&self, this: Self) -> Self {492	// 	self.0.with_this(self.clone(), this)493	// }494	/// Returns amount of visible object fields495	/// If object only contains hidden fields - may return zero.496	pub fn len(&self) -> usize {497		self.fields_visibility()498			.values()499			.filter(|d| d.visible())500			.count()501	}502	/// For each field, calls callback.503	/// If callback returns false - ends iteration prematurely.504	///505	/// Returns false if ended prematurely506	pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {507		let mut super_depth = SuperDepth::default();508		self.enum_fields_idx(509			&mut super_depth,510			handler,511			CoreIdx {512				idx: self.0.cores.len(),513			},514		)515	}516	fn enum_fields_idx(517		&self,518		super_depth: &mut SuperDepth,519		handler: &mut EnumFieldsHandler<'_>,520		idx: CoreIdx,521	) -> bool {522		for core in self.0.cores[..idx.idx].iter().rev() {523			if !core.0.enum_fields_core(super_depth, handler) {524				return false;525			}526			super_depth.deepen();527		}528		true529	}530531	pub fn has_field_include_hidden(&self, name: IStr) -> bool {532		self.has_field_include_hidden_idx(533			name,534			CoreIdx {535				idx: self.0.cores.len(),536			},537		)538	}539	fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {540		let mut skip = Saturating(0usize);541		for ele in self.0.cores[..core.idx].iter().rev() {542			match ele.0.has_field_include_hidden_core(name.clone()) {543				HasFieldIncludeHidden::Exists => {544					if skip.0 == 0 {545						return true;546					}547				}548				HasFieldIncludeHidden::Omit(new_skip) => {549					// +1 including this core550					skip = skip.max(new_skip + Saturating(1));551				}552				HasFieldIncludeHidden::NotFound => {}553			}554			skip -= 1;555		}556		false557	}558	pub fn has_field(&self, name: IStr) -> bool {559		match self.field_visibility(name) {560			Some(Visibility::Unhide | Visibility::Normal) => true,561			Some(Visibility::Hidden) | None => false,562		}563	}564	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {565		if include_hidden {566			self.has_field_include_hidden(name)567		} else {568			self.has_field(name)569		}570	}571	pub fn get(&self, key: IStr) -> Result<Option<Val>> {572		self.get_idx(573			key,574			CoreIdx {575				idx: self.0.cores.len(),576			},577		)578	}579580	fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {581		let cache_key = (key.clone(), core);582		{583			let mut cache = self.0.value_cache.borrow_mut();584			// entry_ref candidate?585			match cache.entry(cache_key.clone()) {586				Entry::Occupied(v) => match v.get() {587					CacheValue::Cached(v) => return v.clone(),588					CacheValue::Pending => {589						if !is_asserting(self) {590							bail!(InfiniteRecursionDetected);591						}592					}593				},594				Entry::Vacant(v) => {595					v.insert(CacheValue::Pending);596				}597			};598		}599		let result = self.get_idx_uncached(key, core);600		{601			let mut cache = self.0.value_cache.borrow_mut();602			cache.insert(cache_key, CacheValue::Cached(result.clone()));603		}604		result605	}606	fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {607		self.run_assertions()?;608		let mut first_add = None;609		let mut add_stack: Vec<Val> = Vec::new();610		let mut skip = Saturating(0);611		for (sup, core) in self.0.cores[..core.idx].iter().enumerate().rev() {612			let sup_this = SupThis {613				sup: CoreIdx { idx: sup },614				this: self.clone(),615			};616			match core.0.get_for_core(key.clone(), sup_this, skip.0 != 0)? {617				GetFor::Final(val) if first_add.is_none() => {618					if skip.0 == 0 {619						return Ok(Some(val));620					}621				}622				GetFor::Final(val) => {623					if skip.0 == 0 {624						add_stack.push(val);625						break;626					}627				}628				GetFor::SuperPlus(val) => {629					if skip.0 == 0 {630						if first_add.is_none() {631							first_add = Some(val);632						} else {633							add_stack.push(val);634						}635					}636				}637				GetFor::Omit(new_skip) => {638					skip = skip.max(new_skip + Saturating(1));639				}640				GetFor::NotFound => {}641			}642			skip -= 1;643		}644		let Some(first) = first_add else {645			if add_stack.is_empty() {646				return Ok(None);647			}648			return Ok(Some(add_stack.pop().expect("single element on stack")));649		};650		if add_stack.is_empty() {651			return Ok(Some(first));652		}653		add_stack.insert(0, first);654		let mut values = add_stack.into_iter().rev();655		let init = values.next().expect("at least 2 elements");656657		values658			.try_fold(init, |a, b| evaluate_add_op(&a, &b))659			.map(Some)660	}661662	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {663		let Some(value) = self.get(key.clone())? else {664			let suggestions = suggest_object_fields(self, key.clone());665			bail!(NoSuchField(key, suggestions))666		};667		Ok(value)668	}669670	fn field_visibility(&self, field: IStr) -> Option<Visibility> {671		self.field_visibility_idx(672			field,673			CoreIdx {674				idx: self.0.cores.len(),675			},676		)677	}678	fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {679		let mut exists = false;680		let mut skip = Saturating(0usize);681		for ele in self.0.cores[..core.idx].iter().rev() {682			let vis = ele.0.field_visibility_core(field.clone());683			match vis {684				FieldVisibility::Found(vis @ (Visibility::Unhide | Visibility::Hidden)) => {685					if skip.0 == 0 {686						return Some(vis);687					}688				}689				FieldVisibility::Found(Visibility::Normal) => {690					if skip.0 == 0 {691						exists = true;692					}693				}694				FieldVisibility::NotFound => {}695				FieldVisibility::Omit(new_skip) => {696					// +1 including this core697					skip = skip.max(new_skip + Saturating(1));698				}699			}700			skip -= 1;701		}702		exists.then_some(Visibility::Normal)703	}704705	pub fn run_assertions(&self) -> Result<()> {706		if self.0.assertions_ran.get() {707			return Ok(());708		}709		if !start_asserting(self) {710			return Ok(());711		}712		for (idx, ele) in self.0.cores.iter().enumerate() {713			let sup_this = SupThis {714				sup: CoreIdx { idx },715				this: self.clone(),716			};717			ele.0.run_assertions_core(sup_this).inspect_err(|_e| {718				finish_asserting(self);719			})?;720		}721		finish_asserting(self);722		self.0.assertions_ran.set(true);723		Ok(())724	}725726	pub fn iter(727		&self,728		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,729	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {730		let fields = self.fields(731			#[cfg(feature = "exp-preserve-order")]732			preserve_order,733		);734		fields.into_iter().map(|field| {735			(736				field.clone(),737				self.get(field)738					.map(|opt| opt.expect("iterating over keys, field exists")),739			)740		})741	}742	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {743		#[derive(Trace)]744		struct ObjFieldThunk {745			obj: ObjValue,746			key: IStr,747		}748		impl ThunkValue for ObjFieldThunk {749			type Output = Val;750751			fn get(&self) -> Result<Self::Output> {752				self.obj753					.get(self.key.clone())754					.transpose()755					.expect("field existence checked")756			}757		}758759		if !self.has_field_ex(key.clone(), true) {760			return None;761		}762763		Some(Thunk::new(ObjFieldThunk {764			obj: self.clone(),765			key,766		}))767	}768	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {769		#[derive(Trace)]770		struct ObjFieldThunk {771			obj: ObjValue,772			key: IStr,773		}774		impl ThunkValue for ObjFieldThunk {775			type Output = Val;776777			fn get(&self) -> Result<Self::Output> {778				self.obj.get_or_bail(self.key.clone())779			}780		}781782		Thunk::new(ObjFieldThunk {783			obj: self.clone(),784			key,785		})786	}787	pub fn ptr_eq(a: &Self, b: &Self) -> bool {788		Cc::ptr_eq(&a.0, &b.0)789	}790	pub fn downgrade(self) -> WeakObjValue {791		WeakObjValue(self.0.downgrade())792	}793}794795#[derive(Debug)]796struct FieldVisibilityData {797	omitted_until: Saturating<usize>,798	exists_visible: Option<Visibility>,799	#[allow(dead_code, reason = "used for exp-object-ordering, ZST otherwise")]800	key: FieldSortKey,801}802impl FieldVisibilityData {803	fn visible(&self) -> bool {804		self.exists_visible805			.expect("non-existing fields shall be dropped at the end of fn fields_visibility()")806			.is_visible()807	}808	#[allow(dead_code, reason = "used for exp-object-ordering, ZST otherwise")]809	fn sort_key(&self) -> FieldSortKey {810		self.key811	}812}813814impl ObjValue {815	fn fields_visibility(&self) -> FxHashMap<IStr, FieldVisibilityData> {816		let mut out = FxHashMap::default();817818		let mut super_depth = SuperDepth::default();819		let mut omit_index = Saturating(0);820		for core in self.0.cores.iter().rev() {821			core.0822				.enum_fields_core(&mut super_depth, &mut |depth, index, name, visibility| {823					let entry = out.entry(name);824					let data = entry.or_insert_with(|| FieldVisibilityData {825						exists_visible: None,826						key: FieldSortKey::new(depth, index),827						omitted_until: omit_index,828					});829					match visibility {830						EnumFields::Omit(new_skip) => {831							// +1 including this core832							data.omitted_until = data833								.omitted_until834								.max(omit_index + new_skip + Saturating(1));835						}836						EnumFields::Normal(Visibility::Normal) => {837							if data.omitted_until <= omit_index && data.exists_visible.is_none() {838								data.exists_visible = Some(Visibility::Normal);839							}840						}841						EnumFields::Normal(Visibility::Hidden) => {842							if data.omitted_until <= omit_index {843								data.exists_visible = Some(match data.exists_visible {844									// We're iterating in reverse, later unhide is preserved845									Some(Visibility::Unhide) => Visibility::Unhide,846									_ => Visibility::Hidden,847								});848							}849						}850						EnumFields::Normal(Visibility::Unhide) => {851							if data.omitted_until <= omit_index {852								data.exists_visible = Some(match data.exists_visible {853									// We're iterating in reverse, later hide is preserved854									Some(Visibility::Hidden) => Visibility::Hidden,855									_ => Visibility::Unhide,856								});857							}858						}859					}860					ControlFlow::Continue(())861				});862863			super_depth.deepen();864			omit_index += 1;865		}866867		out.retain(|_, v| v.exists_visible.is_some());868869		out870	}871	pub fn fields_ex(872		&self,873		include_hidden: bool,874		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,875	) -> Vec<IStr> {876		#[cfg(feature = "exp-preserve-order")]877		if preserve_order {878			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self879				.fields_visibility()880				.into_iter()881				.filter(|(_, d)| include_hidden || d.visible())882				.enumerate()883				.map(|(idx, (k, d))| (k, (d.sort_key(), idx)))884				.unzip();885			keys.sort_unstable_by_key(|v| v.0);886			// Reorder in-place by resulting indexes887			for i in 0..fields.len() {888				let x = fields[i].clone();889				let mut j = i;890				loop {891					let k = keys[j].1;892					keys[j].1 = j;893					if k == i {894						break;895					}896					fields[j] = fields[k].clone();897					j = k;898				}899				fields[j] = x;900			}901			return fields;902		}903904		let mut fields: Vec<_> = self905			.fields_visibility()906			.into_iter()907			.filter(|(_, d)| include_hidden || d.visible())908			.map(|(k, _)| k)909			.collect();910		fields.sort_unstable();911		fields912	}913	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {914		self.fields_ex(915			false,916			#[cfg(feature = "exp-preserve-order")]917			preserve_order,918		)919	}920	pub fn values_ex(921		&self,922		include_hidden: bool,923		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,924	) -> ArrValue {925		ArrValue::new(PickObjectValues::new(926			self.clone(),927			self.fields_ex(928				include_hidden,929				#[cfg(feature = "exp-preserve-order")]930				preserve_order,931			),932		))933	}934	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {935		self.values_ex(936			false,937			#[cfg(feature = "exp-preserve-order")]938			preserve_order,939		)940	}941	pub fn key_values_ex(942		&self,943		include_hidden: bool,944		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,945	) -> ArrValue {946		ArrValue::new(PickObjectKeyValues::new(947			self.clone(),948			self.fields_ex(949				include_hidden,950				#[cfg(feature = "exp-preserve-order")]951				preserve_order,952			),953		))954	}955	pub fn key_values(956		&self,957		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,958	) -> ArrValue {959		self.key_values_ex(960			false,961			#[cfg(feature = "exp-preserve-order")]962			preserve_order,963		)964	}965}966967#[allow(clippy::module_name_repetitions)]968#[must_use = "value not added unless binding() was called"]969pub struct ObjMemberBuilder<Kind> {970	kind: Kind,971	name: IStr,972	add: bool,973	visibility: Visibility,974	original_index: FieldIndex,975	location: Option<Span>,976}977978#[allow(clippy::missing_const_for_fn)]979impl<Kind> ObjMemberBuilder<Kind> {980	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {981		Self {982			kind,983			name,984			original_index,985			add: false,986			visibility: Visibility::Normal,987			location: None,988		}989	}990991	pub const fn with_add(mut self, add: bool) -> Self {992		self.add = add;993		self994	}995	pub fn add(self) -> Self {996		self.with_add(true)997	}998	pub fn with_visibility(mut self, visibility: Visibility) -> Self {999		self.visibility = visibility;1000		self1001	}1002	pub fn hide(self) -> Self {1003		self.with_visibility(Visibility::Hidden)1004	}1005	pub fn with_location(mut self, location: Span) -> Self {1006		self.location = Some(location);1007		self1008	}1009	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {1010		(1011			self.kind,1012			self.name,1013			ObjMember {1014				flags: ObjFieldFlags::new(self.add, self.visibility),1015				original_index: self.original_index,1016				invoke: binding,1017				location: self.location,1018			},1019		)1020	}1021}10221023pub struct ExtendBuilder<'v>(&'v mut ObjValue);1024impl ObjMemberBuilder<ExtendBuilder<'_>> {1025	pub fn value(self, value: impl Into<Val>) {1026		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));1027	}1028	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {1029		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));1030	}1031	pub fn binding(self, binding: MaybeUnbound) {1032		let (receiver, name, member) = self.build_member(binding);1033		let new = receiver.0.clone();1034		*receiver.0 = new.extend_with_raw_member(name, member);1035	}1036}
after · crates/jrsonnet-evaluator/src/obj/mod.rs
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::{cc_dyn, Acyclic, Cc, Trace, Weak};15use jrsonnet_interner::IStr;16use jrsonnet_ir::Span;17use rustc_hash::{FxHashMap, FxHashSet};1819mod oop;2021pub use jrsonnet_ir::Visibility;22pub use oop::ObjValueBuilder;2324use crate::{25	arr::{PickObjectKeyValues, PickObjectValues},26	bail,27	error::{suggest_object_fields, ErrorKind::*},28	identity_hash,29	operator::evaluate_add_op,30	val::{ArrValue, ThunkValue},31	CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,32};3334#[cfg(not(feature = "exp-preserve-order"))]35pub mod ordering {36	#![allow(37		// This module works as stub for preserve-order feature38		clippy::unused_self,39	)]4041	use jrsonnet_gcmodule::Trace;4243	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]44	pub struct FieldIndex(());45	impl FieldIndex {46		pub fn absolute(_v: u32) -> Self {47			Self(())48		}49		#[must_use]50		pub const fn next(self) -> Self {51			Self(())52		}53	}5455	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]56	pub struct SuperDepth(());57	impl SuperDepth {58		pub(super) fn deepen(self) {}59	}60}6162#[cfg(feature = "exp-preserve-order")]63pub mod ordering {64	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 absolute(v: u32) -> Self {70			Self(v)71		}72		#[must_use]73		pub fn next(self) -> Self {74			Self(self.0 + 1)75		}76	}7778	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]79	pub struct SuperDepth(u32);80	impl SuperDepth {81		pub(super) fn deepen(&mut self) {82			self.0 += 1;83		}84	}85}8687use ordering::{FieldIndex, SuperDepth};8889#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]90pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);91impl FieldSortKey {92	pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {93		Self(Reverse(depth), index)94	}95}9697// 0 - add98//  12 - visibility99#[derive(Clone, Copy)]100pub struct ObjFieldFlags(u8);101impl ObjFieldFlags {102	fn new(add: bool, visibility: Visibility) -> Self {103		let mut v = 0;104		if add {105			v |= 1;106		}107		v |= match visibility {108			Visibility::Normal => 0b000,109			Visibility::Hidden => 0b010,110			Visibility::Unhide => 0b100,111		};112		Self(v)113	}114	pub fn add(&self) -> bool {115		self.0 & 1 != 0116	}117	pub fn visibility(&self) -> Visibility {118		match (self.0 & 0b110) >> 1 {119			0b00 => Visibility::Normal,120			0b01 => Visibility::Hidden,121			0b10 => Visibility::Unhide,122			_ => unreachable!(),123		}124	}125}126impl Debug for ObjFieldFlags {127	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {128		f.debug_struct("ObjFieldFlags")129			.field("add", &self.add())130			.field("visibility", &self.visibility())131			.finish()132	}133}134135#[allow(clippy::module_name_repetitions)]136#[derive(Debug, Trace)]137pub struct ObjMember {138	#[trace(skip)]139	flags: ObjFieldFlags,140	original_index: FieldIndex,141	pub invoke: MaybeUnbound,142	pub location: Option<Span>,143}144145cc_dyn!(CcObjectAssertion, ObjectAssertion);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;160161pub enum EnumFields {162	Normal(Visibility),163	Omit(Skip),164}165166#[derive(Trace, Clone)]167pub enum GetFor {168	// Return value169	Final(Val),170	// Continue iterating over cores, add current value to sum stack171	SuperPlus(Val),172	// Ignore the field value, stop at this layer instead173	Omit(#[trace(skip)] Skip),174	NotFound,175}176177#[derive(Acyclic, Clone)]178pub enum FieldVisibility {179	Found(Visibility),180	Omit(Skip),181	NotFound,182}183184#[derive(Acyclic, Clone)]185pub enum HasFieldIncludeHidden {186	Exists,187	NotFound,188	Omit(Skip),189}190191type Skip = Saturating<usize>;192193pub trait ObjectCore: Trace + Any + Debug {194	// If callback returns false, iteration stops, and this call returns false.195	fn enum_fields_core(196		&self,197		super_depth: &mut SuperDepth,198		handler: &mut EnumFieldsHandler<'_>,199	) -> bool;200201	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden;202203	fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor>;204	fn field_visibility_core(&self, field: IStr) -> FieldVisibility;205206	fn run_assertions_core(&self, sup_this: SupThis) -> Result<()>;207}208209#[derive(Clone, Trace)]210pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);211impl Debug for WeakObjValue {212	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {213		f.debug_tuple("WeakObjValue").finish()214	}215}216217impl PartialEq for WeakObjValue {218	fn eq(&self, other: &Self) -> bool {219		Weak::ptr_eq(&self.0, &other.0)220	}221}222223impl Eq for WeakObjValue {}224impl Hash for WeakObjValue {225	fn hash<H: Hasher>(&self, hasher: &mut H) {226		// Safety: usize is POD227		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };228		hasher.write_usize(addr);229	}230}231232cc_dyn!(233	#[derive(Clone, Debug)]234	CcObjectCore, ObjectCore,235	pub fn new() {...}236);237#[derive(Trace, Educe)]238#[educe(Debug)]239struct ObjValueInner {240	cores: Vec<CcObjectCore>,241	assertions_ran: Cell<bool>,242	#[trace(skip)]243	has_assertions: bool,244	value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,245}246247thread_local! {248	static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();249}250fn is_asserting(obj: &ObjValue) -> bool {251	RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))252}253/// Returns false if already asserting254fn start_asserting(obj: &ObjValue) -> bool {255	RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))256}257fn finish_asserting(obj: &ObjValue) {258	RUNNING_ASSERTIONS.with_borrow_mut(|v| {259		let r = v.remove(obj);260		debug_assert!(261			r,262			"finish_asserting was called before start_asserting or twice"263		);264	});265}266267thread_local! {268	static EMPTY_OBJ: ObjValue = ObjValue(Cc::new(ObjValueInner {269		cores: vec![],270		assertions_ran: Cell::new(true),271		has_assertions: false,272		value_cache: RefCell::default(),273	}))274}275276#[allow(clippy::module_name_repetitions)]277#[derive(Clone, Trace, Debug, Educe)]278#[educe(PartialEq, Hash, Eq)]279pub struct ObjValue(280	#[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,281);282283impl ObjValue {284	pub fn empty() -> Self {285		EMPTY_OBJ.with(Clone::clone)286	}287	pub fn is_empty(&self) -> bool {288		self.0.cores.is_empty() || self.len() == 0289	}290}291292#[derive(Trace, Debug)]293struct StandaloneSuperCore {294	sup: CoreIdx,295	this: ObjValue,296}297impl ObjectCore for StandaloneSuperCore {298	fn enum_fields_core(299		&self,300		super_depth: &mut SuperDepth,301		handler: &mut EnumFieldsHandler<'_>,302	) -> bool {303		self.this.enum_fields_idx(super_depth, handler, self.sup)304	}305306	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {307		if self.this.has_field_include_hidden_idx(name, self.sup) {308			HasFieldIncludeHidden::Exists309		} else {310			HasFieldIncludeHidden::NotFound311		}312	}313314	fn get_for_core(&self, key: IStr, _sup_this: SupThis, omit_only: bool) -> Result<GetFor> {315		if omit_only {316			return Ok(GetFor::NotFound);317		}318		let v = self.this.get_idx(key, self.sup)?;319		Ok(v.map_or(GetFor::NotFound, GetFor::Final))320	}321322	fn field_visibility_core(&self, field: IStr) -> FieldVisibility {323		self.this324			.field_visibility_idx(field, self.sup)325			.map_or(FieldVisibility::NotFound, FieldVisibility::Found)326	}327328	fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {329		self.this.run_assertions()330	}331}332333#[derive(Debug, Acyclic)]334struct OmitFieldsCore {335	omit: FxHashSet<IStr>,336	prev_layers: usize,337}338impl ObjectCore for OmitFieldsCore {339	fn enum_fields_core(340		&self,341		super_depth: &mut SuperDepth,342		handler: &mut EnumFieldsHandler<'_>,343	) -> bool {344		let mut fi = FieldIndex::default();345		for f in &self.omit {346			if handler(347				*super_depth,348				fi,349				f.clone(),350				EnumFields::Omit(Saturating(self.prev_layers)),351			) == ControlFlow::Break(())352			{353				return false;354			}355			fi = fi.next();356		}357		true358	}359360	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {361		if self.omit.contains(&name) {362			return HasFieldIncludeHidden::Omit(Saturating(self.prev_layers));363		}364		HasFieldIncludeHidden::NotFound365	}366367	fn get_for_core(&self, key: IStr, _sup_this: SupThis, _omit_only: bool) -> Result<GetFor> {368		if self.omit.contains(&key) {369			return Ok(GetFor::Omit(Saturating(self.prev_layers)));370		}371		Ok(GetFor::NotFound)372	}373374	fn field_visibility_core(&self, field: IStr) -> FieldVisibility {375		if self.omit.contains(&field) {376			return FieldVisibility::Omit(Saturating(self.prev_layers));377		}378		FieldVisibility::NotFound379	}380381	fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {382		Ok(())383	}384}385386#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]387struct CoreIdx {388	idx: usize,389}390impl CoreIdx {391	fn super_exists(self) -> bool {392		self.idx != 0393	}394}395#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]396pub struct SupThis {397	sup: CoreIdx,398	this: ObjValue,399}400impl SupThis {401	pub fn has_super(&self) -> bool {402		self.sup.super_exists()403	}404	/// Implementation of `"field" in super` operation,405	/// works faster than standalone super path.406	///407	/// In case of no `super` existence, returns false.408	pub fn field_in_super(&self, field: IStr) -> bool {409		self.this.has_field_include_hidden_idx(field, self.sup)410	}411	/// Implementation of `super.field` operation,412	/// works faster than standalone super path.413	///414	/// In case of no `super` existence, returns `NoSuperFound`415	pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {416		if !self.sup.super_exists() {417			bail!(NoSuperFound);418		}419		self.this.get_idx(field, self.sup)420	}421	/// `super` with `self` overriden for top-level lookups.422	/// Exists when super appears outside of `super.field`/`"field" in super` expressions423	/// Exclusive to jrsonnet.424	///425	/// Might return `NoSuperFound` error.426	pub fn standalone_super(&self) -> Result<ObjValue> {427		if !self.sup.super_exists() {428			bail!(NoSuperFound)429		}430		let mut out = ObjValue::builder();431		out.reserve_cores(1).extend_with_core(StandaloneSuperCore {432			sup: self.sup,433			this: self.this.clone(),434		});435		Ok(out.build())436	}437	pub fn this(&self) -> &ObjValue {438		&self.this439	}440	pub fn downgrade(self) -> WeakSupThis {441		WeakSupThis {442			sup: self.sup,443			this: self.this.downgrade(),444		}445	}446}447#[derive(Trace, PartialEq, Eq, Hash, Debug)]448pub struct WeakSupThis {449	sup: CoreIdx,450	this: WeakObjValue,451}452453impl ObjValue {454	pub fn builder() -> ObjValueBuilder {455		ObjValueBuilder::new()456	}457	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {458		ObjValueBuilder::with_capacity(capacity)459	}460	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {461		let mut out = ObjValueBuilder::with_capacity(1);462		out.with_super(self);463		let mut member = out.field(key);464		if value.flags.add() {465			member = member.add();466		}467		if let Some(loc) = value.location {468			member = member.with_location(loc);469		}470		let _ = member471			.with_visibility(value.flags.visibility())472			.binding(value.invoke);473		out.build()474	}475	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {476		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())477	}478479	pub fn extend(&mut self) -> ObjValueBuilder {480		let mut out = ObjValueBuilder::new();481		out.with_super(self.clone());482		out483	}484485	#[must_use]486	pub fn extend_from(&self, sup: Self) -> Self {487		let mut cores = Vec::with_capacity(sup.0.cores.len() + self.0.cores.len());488		cores.extend(sup.0.cores.iter().cloned());489		cores.extend(self.0.cores.iter().cloned());490		let has_assertions = sup.0.has_assertions || self.0.has_assertions;491		ObjValue(Cc::new(ObjValueInner {492			cores,493			value_cache: RefCell::default(),494			assertions_ran: Cell::new(!has_assertions),495			has_assertions,496		}))497	}498	// #[must_use]499	// pub fn with_this(&self, this: Self) -> Self {500	// 	self.0.with_this(self.clone(), this)501	// }502	/// Returns amount of visible object fields503	/// If object only contains hidden fields - may return zero.504	pub fn len(&self) -> usize {505		self.fields_visibility()506			.values()507			.filter(|d| d.visible())508			.count()509	}510	/// For each field, calls callback.511	/// If callback returns false - ends iteration prematurely.512	///513	/// Returns false if ended prematurely514	pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {515		let mut super_depth = SuperDepth::default();516		self.enum_fields_idx(517			&mut super_depth,518			handler,519			CoreIdx {520				idx: self.0.cores.len(),521			},522		)523	}524	fn enum_fields_idx(525		&self,526		super_depth: &mut SuperDepth,527		handler: &mut EnumFieldsHandler<'_>,528		idx: CoreIdx,529	) -> bool {530		for core in self.0.cores[..idx.idx].iter().rev() {531			if !core.0.enum_fields_core(super_depth, handler) {532				return false;533			}534			super_depth.deepen();535		}536		true537	}538539	pub fn has_field_include_hidden(&self, name: IStr) -> bool {540		self.has_field_include_hidden_idx(541			name,542			CoreIdx {543				idx: self.0.cores.len(),544			},545		)546	}547	fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {548		let mut skip = Saturating(0usize);549		for ele in self.0.cores[..core.idx].iter().rev() {550			match ele.0.has_field_include_hidden_core(name.clone()) {551				HasFieldIncludeHidden::Exists => {552					if skip.0 == 0 {553						return true;554					}555				}556				HasFieldIncludeHidden::Omit(new_skip) => {557					// +1 including this core558					skip = skip.max(new_skip + Saturating(1));559				}560				HasFieldIncludeHidden::NotFound => {}561			}562			skip -= 1;563		}564		false565	}566	pub fn has_field(&self, name: IStr) -> bool {567		match self.field_visibility(name) {568			Some(Visibility::Unhide | Visibility::Normal) => true,569			Some(Visibility::Hidden) | None => false,570		}571	}572	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {573		if include_hidden {574			self.has_field_include_hidden(name)575		} else {576			self.has_field(name)577		}578	}579	pub fn get(&self, key: IStr) -> Result<Option<Val>> {580		self.get_idx(581			key,582			CoreIdx {583				idx: self.0.cores.len(),584			},585		)586	}587588	fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {589		let cache_key = (key.clone(), core);590		{591			let mut cache = self.0.value_cache.borrow_mut();592			// entry_ref candidate?593			match cache.entry(cache_key.clone()) {594				Entry::Occupied(v) => match v.get() {595					CacheValue::Cached(v) => return v.clone(),596					CacheValue::Pending => {597						if !is_asserting(self) {598							bail!(InfiniteRecursionDetected);599						}600					}601				},602				Entry::Vacant(v) => {603					v.insert(CacheValue::Pending);604				}605			};606		}607		let result = self.get_idx_uncached(key, core);608		{609			let mut cache = self.0.value_cache.borrow_mut();610			cache.insert(cache_key, CacheValue::Cached(result.clone()));611		}612		result613	}614	fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {615		self.run_assertions()?;616		let mut first_add = None;617		let mut add_stack: Vec<Val> = Vec::new();618		let mut skip = Saturating(0);619		for (sup, core) in self.0.cores[..core.idx].iter().enumerate().rev() {620			let sup_this = SupThis {621				sup: CoreIdx { idx: sup },622				this: self.clone(),623			};624			match core.0.get_for_core(key.clone(), sup_this, skip.0 != 0)? {625				GetFor::Final(val) if first_add.is_none() => {626					if skip.0 == 0 {627						return Ok(Some(val));628					}629				}630				GetFor::Final(val) => {631					if skip.0 == 0 {632						add_stack.push(val);633						break;634					}635				}636				GetFor::SuperPlus(val) => {637					if skip.0 == 0 {638						if first_add.is_none() {639							first_add = Some(val);640						} else {641							add_stack.push(val);642						}643					}644				}645				GetFor::Omit(new_skip) => {646					skip = skip.max(new_skip + Saturating(1));647				}648				GetFor::NotFound => {}649			}650			skip -= 1;651		}652		let Some(first) = first_add else {653			if add_stack.is_empty() {654				return Ok(None);655			}656			return Ok(Some(add_stack.pop().expect("single element on stack")));657		};658		if add_stack.is_empty() {659			return Ok(Some(first));660		}661		add_stack.insert(0, first);662		let mut values = add_stack.into_iter().rev();663		let init = values.next().expect("at least 2 elements");664665		values666			.try_fold(init, |a, b| evaluate_add_op(&a, &b))667			.map(Some)668	}669670	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {671		let Some(value) = self.get(key.clone())? else {672			let suggestions = suggest_object_fields(self, key.clone());673			bail!(NoSuchField(key, suggestions))674		};675		Ok(value)676	}677678	fn field_visibility(&self, field: IStr) -> Option<Visibility> {679		self.field_visibility_idx(680			field,681			CoreIdx {682				idx: self.0.cores.len(),683			},684		)685	}686	fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {687		let mut exists = false;688		let mut skip = Saturating(0usize);689		for ele in self.0.cores[..core.idx].iter().rev() {690			let vis = ele.0.field_visibility_core(field.clone());691			match vis {692				FieldVisibility::Found(vis @ (Visibility::Unhide | Visibility::Hidden)) => {693					if skip.0 == 0 {694						return Some(vis);695					}696				}697				FieldVisibility::Found(Visibility::Normal) => {698					if skip.0 == 0 {699						exists = true;700					}701				}702				FieldVisibility::NotFound => {}703				FieldVisibility::Omit(new_skip) => {704					// +1 including this core705					skip = skip.max(new_skip + Saturating(1));706				}707			}708			skip -= 1;709		}710		exists.then_some(Visibility::Normal)711	}712713	pub fn run_assertions(&self) -> Result<()> {714		if self.0.assertions_ran.get() {715			return Ok(());716		}717		if !start_asserting(self) {718			return Ok(());719		}720		for (idx, ele) in self.0.cores.iter().enumerate() {721			let sup_this = SupThis {722				sup: CoreIdx { idx },723				this: self.clone(),724			};725			ele.0.run_assertions_core(sup_this).inspect_err(|_e| {726				finish_asserting(self);727			})?;728		}729		finish_asserting(self);730		self.0.assertions_ran.set(true);731		Ok(())732	}733734	pub fn iter(735		&self,736		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,737	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {738		let fields = self.fields(739			#[cfg(feature = "exp-preserve-order")]740			preserve_order,741		);742		fields.into_iter().map(|field| {743			(744				field.clone(),745				self.get(field)746					.map(|opt| opt.expect("iterating over keys, field exists")),747			)748		})749	}750	pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {751		#[derive(Trace)]752		struct ObjFieldThunk {753			obj: ObjValue,754			key: IStr,755		}756		impl ThunkValue for ObjFieldThunk {757			type Output = Val;758759			fn get(&self) -> Result<Self::Output> {760				self.obj761					.get(self.key.clone())762					.transpose()763					.expect("field existence checked")764			}765		}766767		if !self.has_field_ex(key.clone(), true) {768			return None;769		}770771		Some(Thunk::new(ObjFieldThunk {772			obj: self.clone(),773			key,774		}))775	}776	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {777		#[derive(Trace)]778		struct ObjFieldThunk {779			obj: ObjValue,780			key: IStr,781		}782		impl ThunkValue for ObjFieldThunk {783			type Output = Val;784785			fn get(&self) -> Result<Self::Output> {786				self.obj.get_or_bail(self.key.clone())787			}788		}789790		Thunk::new(ObjFieldThunk {791			obj: self.clone(),792			key,793		})794	}795	pub fn ptr_eq(a: &Self, b: &Self) -> bool {796		Cc::ptr_eq(&a.0, &b.0)797	}798	pub fn downgrade(self) -> WeakObjValue {799		WeakObjValue(self.0.downgrade())800	}801}802803#[derive(Debug)]804struct FieldVisibilityData {805	omitted_until: Saturating<usize>,806	exists_visible: Option<Visibility>,807	#[allow(dead_code, reason = "used for exp-object-ordering, ZST otherwise")]808	key: FieldSortKey,809}810impl FieldVisibilityData {811	fn visible(&self) -> bool {812		self.exists_visible813			.expect("non-existing fields shall be dropped at the end of fn fields_visibility()")814			.is_visible()815	}816	#[allow(dead_code, reason = "used for exp-object-ordering, ZST otherwise")]817	fn sort_key(&self) -> FieldSortKey {818		self.key819	}820}821822impl ObjValue {823	fn fields_visibility(&self) -> FxHashMap<IStr, FieldVisibilityData> {824		let mut out = FxHashMap::default();825826		let mut super_depth = SuperDepth::default();827		let mut omit_index = Saturating(0);828		for core in self.0.cores.iter().rev() {829			core.0830				.enum_fields_core(&mut super_depth, &mut |depth, index, name, visibility| {831					let entry = out.entry(name);832					let data = entry.or_insert_with(|| FieldVisibilityData {833						exists_visible: None,834						key: FieldSortKey::new(depth, index),835						omitted_until: omit_index,836					});837					match visibility {838						EnumFields::Omit(new_skip) => {839							// +1 including this core840							data.omitted_until = data841								.omitted_until842								.max(omit_index + new_skip + Saturating(1));843						}844						EnumFields::Normal(Visibility::Normal) => {845							if data.omitted_until <= omit_index && data.exists_visible.is_none() {846								data.exists_visible = Some(Visibility::Normal);847							}848						}849						EnumFields::Normal(Visibility::Hidden) => {850							if data.omitted_until <= omit_index {851								data.exists_visible = Some(match data.exists_visible {852									// We're iterating in reverse, later unhide is preserved853									Some(Visibility::Unhide) => Visibility::Unhide,854									_ => Visibility::Hidden,855								});856							}857						}858						EnumFields::Normal(Visibility::Unhide) => {859							if data.omitted_until <= omit_index {860								data.exists_visible = Some(match data.exists_visible {861									// We're iterating in reverse, later hide is preserved862									Some(Visibility::Hidden) => Visibility::Hidden,863									_ => Visibility::Unhide,864								});865							}866						}867					}868					ControlFlow::Continue(())869				});870871			super_depth.deepen();872			omit_index += 1;873		}874875		out.retain(|_, v| v.exists_visible.is_some());876877		out878	}879	pub fn fields_ex(880		&self,881		include_hidden: bool,882		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,883	) -> Vec<IStr> {884		#[cfg(feature = "exp-preserve-order")]885		if preserve_order {886			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self887				.fields_visibility()888				.into_iter()889				.filter(|(_, d)| include_hidden || d.visible())890				.enumerate()891				.map(|(idx, (k, d))| (k, (d.sort_key(), idx)))892				.unzip();893			keys.sort_unstable_by_key(|v| v.0);894			// Reorder in-place by resulting indexes895			for i in 0..fields.len() {896				let x = fields[i].clone();897				let mut j = i;898				loop {899					let k = keys[j].1;900					keys[j].1 = j;901					if k == i {902						break;903					}904					fields[j] = fields[k].clone();905					j = k;906				}907				fields[j] = x;908			}909			return fields;910		}911912		let mut fields: Vec<_> = self913			.fields_visibility()914			.into_iter()915			.filter(|(_, d)| include_hidden || d.visible())916			.map(|(k, _)| k)917			.collect();918		fields.sort_unstable();919		fields920	}921	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {922		self.fields_ex(923			false,924			#[cfg(feature = "exp-preserve-order")]925			preserve_order,926		)927	}928	pub fn values_ex(929		&self,930		include_hidden: bool,931		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,932	) -> ArrValue {933		ArrValue::new(PickObjectValues::new(934			self.clone(),935			self.fields_ex(936				include_hidden,937				#[cfg(feature = "exp-preserve-order")]938				preserve_order,939			),940		))941	}942	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {943		self.values_ex(944			false,945			#[cfg(feature = "exp-preserve-order")]946			preserve_order,947		)948	}949	pub fn key_values_ex(950		&self,951		include_hidden: bool,952		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,953	) -> ArrValue {954		ArrValue::new(PickObjectKeyValues::new(955			self.clone(),956			self.fields_ex(957				include_hidden,958				#[cfg(feature = "exp-preserve-order")]959				preserve_order,960			),961		))962	}963	pub fn key_values(964		&self,965		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,966	) -> ArrValue {967		self.key_values_ex(968			false,969			#[cfg(feature = "exp-preserve-order")]970			preserve_order,971		)972	}973}974975#[allow(clippy::module_name_repetitions)]976#[must_use = "value not added unless binding() was called"]977pub struct ObjMemberBuilder<Kind> {978	kind: Kind,979	name: IStr,980	add: bool,981	visibility: Visibility,982	original_index: FieldIndex,983	location: Option<Span>,984}985986#[allow(clippy::missing_const_for_fn)]987impl<Kind> ObjMemberBuilder<Kind> {988	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {989		Self {990			kind,991			name,992			original_index,993			add: false,994			visibility: Visibility::Normal,995			location: None,996		}997	}998999	pub const fn with_add(mut self, add: bool) -> Self {1000		self.add = add;1001		self1002	}1003	pub fn add(self) -> Self {1004		self.with_add(true)1005	}1006	pub fn with_visibility(mut self, visibility: Visibility) -> Self {1007		self.visibility = visibility;1008		self1009	}1010	pub fn hide(self) -> Self {1011		self.with_visibility(Visibility::Hidden)1012	}1013	pub fn with_location(mut self, location: Span) -> Self {1014		self.location = Some(location);1015		self1016	}1017	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {1018		(1019			self.kind,1020			self.name,1021			ObjMember {1022				flags: ObjFieldFlags::new(self.add, self.visibility),1023				original_index: self.original_index,1024				invoke: binding,1025				location: self.location,1026			},1027		)1028	}1029}10301031pub struct ExtendBuilder<'v>(&'v mut ObjValue);1032impl ObjMemberBuilder<ExtendBuilder<'_>> {1033	pub fn value(self, value: impl Into<Val>) {1034		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));1035	}1036	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {1037		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));1038	}1039	pub fn binding(self, binding: MaybeUnbound) {1040		let (receiver, name, member) = self.build_member(binding);1041		let new = receiver.0.clone();1042		*receiver.0 = new.extend_with_raw_member(name, member);1043	}1044}
modifiedcrates/jrsonnet-ir-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-ir-parser/src/lib.rs
+++ b/crates/jrsonnet-ir-parser/src/lib.rs
@@ -3,9 +3,9 @@
 use jrsonnet_gcmodule::Acyclic;
 use jrsonnet_ir::{
 	unescape, ArgsDesc, AssertExpr, AssertStmt, BinaryOp, BinaryOpType, BindSpec, CompSpec,
-	Destruct, DestructRest, Expr, ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr,
-	IfElse, IfSpecData, ImportKind, IndexPart, LiteralType, Member, ObjBody, ObjComp, ObjMembers,
-	Slice, SliceDesc, Source, Span, Spanned, UnaryOpType, Visibility,
+	Destruct, Expr, ExprParam, ExprParams, FieldMember, FieldName, ForSpecData, IStr, IfElse,
+	IfSpecData, ImportKind, IndexPart, LiteralType, Member, ObjBody, ObjComp, ObjMembers, Slice,
+	SliceDesc, Source, Span, Spanned, UnaryOpType, Visibility,
 };
 use jrsonnet_lexer::{collect_lexed_str_block, Lexeme, Lexer, SyntaxKind, T};
 
@@ -30,7 +30,7 @@
 	}
 }
 
-type R<T> = Result<T, ParseError>;
+type Result<T> = std::result::Result<T, ParseError>;
 
 struct Parser<'a> {
 	lexemes: Vec<Lexeme<'a>>,
@@ -103,7 +103,7 @@
 		}
 	}
 
-	fn eat(&mut self, t: SyntaxKind) -> R<()> {
+	fn eat(&mut self, t: SyntaxKind) -> Result<()> {
 		if !self.at(t) {
 			return Err(self.error(format!(
 				"expected {}, got {}",
@@ -138,15 +138,13 @@
 		}
 	}
 
-	fn expect_ident(&mut self) -> R<IStr> {
+	fn expect_ident(&mut self) -> Result<IStr> {
 		if !self.at(SyntaxKind::IDENT) {
 			return Err(self.error(format!("expected identifier, got {}", self.current_desc())));
 		}
 		let text = self.text();
 		if is_reserved(text) {
-			return Err(self.error(format!(
-				"expected identifier, got reserved word '{text}'"
-			)));
+			return Err(self.error(format!("expected identifier, got reserved word '{text}'")));
 		}
 		let s: IStr = text.into();
 		self.eat_any();
@@ -164,36 +162,38 @@
 		"assert"
 			| "else" | "error"
 			| "false" | "for"
-			| "function" | "if"
-			| "import" | "importstr"
-			| "importbin" | "in"
-			| "local" | "null"
-			| "tailstrict" | "then"
-			| "self" | "super"
-			| "true"
+			| "function"
+			| "if" | "import"
+			| "importstr"
+			| "importbin"
+			| "in" | "local"
+			| "null" | "tailstrict"
+			| "then" | "self"
+			| "super" | "true"
 	)
 }
 
-fn spanned<T: Acyclic>(p: &mut Parser<'_>, cb: impl FnOnce(&mut Parser<'_>) -> R<T>) -> R<Spanned<T>> {
+fn spanned<T: Acyclic>(
+	p: &mut Parser<'_>,
+	cb: impl FnOnce(&mut Parser<'_>) -> Result<T>,
+) -> Result<Spanned<T>> {
 	let start = p.span_start();
 	let v = cb(p)?;
 	let end = p.span_end();
 	Ok(Spanned::new(v, Span(p.source.clone(), start, end)))
 }
 
-fn parse_string_content(p: &mut Parser<'_>) -> R<IStr> {
+fn parse_string_content(p: &mut Parser<'_>) -> Result<IStr> {
 	let kind = p.peek();
 	let text = p.text();
 	let s = match kind {
 		SyntaxKind::STRING_DOUBLE => {
 			let inner = &text[1..text.len() - 1];
-			unescape::unescape(inner)
-				.ok_or_else(|| p.error("invalid string escape".into()))?
+			unescape::unescape(inner).ok_or_else(|| p.error("invalid string escape".into()))?
 		}
 		SyntaxKind::STRING_SINGLE => {
 			let inner = &text[1..text.len() - 1];
-			unescape::unescape(inner)
-				.ok_or_else(|| p.error("invalid string escape".into()))?
+			unescape::unescape(inner).ok_or_else(|| p.error("invalid string escape".into()))?
 		}
 		SyntaxKind::STRING_DOUBLE_VERBATIM => {
 			let inner = &text[2..text.len() - 1];
@@ -236,7 +236,7 @@
 	)
 }
 
-fn parse_number(p: &mut Parser<'_>) -> R<f64> {
+fn parse_number(p: &mut Parser<'_>) -> Result<f64> {
 	let text = p.text();
 	let n: f64 = text
 		.replace('_', "")
@@ -263,7 +263,7 @@
 	Some(t)
 }
 
-fn assert_stmt(p: &mut Parser<'_>) -> R<AssertStmt> {
+fn assert_stmt(p: &mut Parser<'_>) -> Result<AssertStmt> {
 	p.eat(T![assert])?;
 	let cond = spanned(p, expr)?;
 	let msg = if p.try_eat(T![:]) {
@@ -274,13 +274,13 @@
 	Ok(AssertStmt(cond, msg))
 }
 
-fn if_spec_data(p: &mut Parser<'_>) -> R<IfSpecData> {
+fn if_spec_data(p: &mut Parser<'_>) -> Result<IfSpecData> {
 	let v = spanned(p, |p| p.eat(T![if]))?;
 	let cond = expr(p)?;
 	Ok(IfSpecData { span: v.span, cond })
 }
 
-fn if_else(p: &mut Parser<'_>) -> R<IfElse> {
+fn if_else(p: &mut Parser<'_>) -> Result<IfElse> {
 	let cond = if_spec_data(p)?;
 	p.eat(T![then])?;
 	let cond_then = expr(p)?;
@@ -296,7 +296,7 @@
 	})
 }
 
-fn slice_desc(p: &mut Parser<'_>, start: Option<Spanned<Expr>>) -> R<SliceDesc> {
+fn slice_desc(p: &mut Parser<'_>, start: Option<Spanned<Expr>>) -> Result<SliceDesc> {
 	p.eat(T![:])?;
 	let end = if !p.at(T![:]) && !p.at(T![']']) {
 		Some(spanned(p, expr)?)
@@ -315,15 +315,12 @@
 	Ok(SliceDesc { start, end, step })
 }
 
-fn destruct(p: &mut Parser<'_>) -> R<Destruct> {
+fn destruct(p: &mut Parser<'_>) -> Result<Destruct> {
 	if p.at_ident() {
 		return Ok(Destruct::Full(p.expect_ident()?));
 	}
 	#[cfg(not(feature = "exp-destruct"))]
-	return Err(p.error(format!(
-		"expected identifier, got {}",
-		p.current_desc()
-	)));
+	return Err(p.error(format!("expected identifier, got {}", p.current_desc())));
 	#[cfg(feature = "exp-destruct")]
 	{
 		if p.try_eat(T![?]) {
@@ -343,17 +340,17 @@
 }
 
 #[cfg(feature = "exp-destruct")]
-fn destruct_rest(p: &mut Parser<'_>) -> R<DestructRest> {
+fn destruct_rest(p: &mut Parser<'_>) -> Result<jrsonnet_ir::DestructRest> {
 	p.eat(T![...])?;
 	if p.at_ident() {
-		Ok(DestructRest::Keep(p.expect_ident()?))
+		Ok(jrsonnet_ir::DestructRest::Keep(p.expect_ident()?))
 	} else {
-		Ok(DestructRest::Drop)
+		Ok(jrsonnet_ir::DestructRest::Drop)
 	}
 }
 
 #[cfg(feature = "exp-destruct")]
-fn destruct_array(p: &mut Parser<'_>) -> R<Destruct> {
+fn destruct_array(p: &mut Parser<'_>) -> Result<Destruct> {
 	p.eat(T!['['])?;
 	let mut start = Vec::new();
 	let mut rest = None;
@@ -391,7 +388,7 @@
 }
 
 #[cfg(feature = "exp-destruct")]
-fn destruct_object(p: &mut Parser<'_>) -> R<Destruct> {
+fn destruct_object(p: &mut Parser<'_>) -> Result<Destruct> {
 	p.eat(T!['{'])?;
 	let mut fields = Vec::new();
 	let mut rest = None;
@@ -426,7 +423,7 @@
 	Ok(Destruct::Object { fields, rest })
 }
 
-fn params(p: &mut Parser<'_>) -> R<ExprParams> {
+fn params(p: &mut Parser<'_>) -> Result<ExprParams> {
 	if p.at(T![')']) {
 		return Ok(ExprParams::new(Vec::new()));
 	}
@@ -452,7 +449,7 @@
 	Ok(ExprParams::new(result))
 }
 
-fn args(p: &mut Parser<'_>) -> R<ArgsDesc> {
+fn args(p: &mut Parser<'_>) -> Result<ArgsDesc> {
 	if p.at(T![')']) {
 		return Ok(ArgsDesc::new(Vec::new(), Vec::new()));
 	}
@@ -489,7 +486,7 @@
 	Ok(ArgsDesc::new(unnamed, named))
 }
 
-fn bind(p: &mut Parser<'_>) -> R<BindSpec> {
+fn bind(p: &mut Parser<'_>) -> Result<BindSpec> {
 	#[cfg(feature = "exp-destruct")]
 	{
 		if !p.at_ident() {
@@ -520,7 +517,7 @@
 	}
 }
 
-fn visibility(p: &mut Parser<'_>) -> R<Visibility> {
+fn visibility(p: &mut Parser<'_>) -> Result<Visibility> {
 	p.eat(T![:])?;
 	if p.try_eat(T![:]) {
 		if p.try_eat(T![:]) {
@@ -533,7 +530,7 @@
 	}
 }
 
-fn field_name(p: &mut Parser<'_>) -> R<FieldName> {
+fn field_name(p: &mut Parser<'_>) -> Result<FieldName> {
 	if p.at_ident() {
 		Ok(FieldName::Fixed(p.expect_ident()?))
 	} else if is_string_token(p.peek()) {
@@ -548,7 +545,7 @@
 	}
 }
 
-fn field(p: &mut Parser<'_>) -> R<FieldMember> {
+fn field(p: &mut Parser<'_>) -> Result<FieldMember> {
 	let name = spanned(p, field_name)?;
 
 	if p.at(T!['(']) {
@@ -578,7 +575,7 @@
 	}
 }
 
-fn member(p: &mut Parser<'_>) -> R<Member> {
+fn member(p: &mut Parser<'_>) -> Result<Member> {
 	if p.at(T![local]) {
 		p.eat(T![local])?;
 		Ok(Member::BindStmt(bind(p)?))
@@ -589,7 +586,7 @@
 	}
 }
 
-fn for_spec(p: &mut Parser<'_>) -> R<ForSpecData> {
+fn for_spec(p: &mut Parser<'_>) -> Result<ForSpecData> {
 	p.eat(T![for])?;
 	let d = destruct(p)?;
 	p.eat(T![in])?;
@@ -597,7 +594,7 @@
 	Ok(ForSpecData { destruct: d, over })
 }
 
-fn compspecs(p: &mut Parser<'_>) -> R<Vec<CompSpec>> {
+fn compspecs(p: &mut Parser<'_>) -> Result<Vec<CompSpec>> {
 	let mut specs = Vec::new();
 	specs.push(CompSpec::ForSpec(for_spec(p)?));
 	loop {
@@ -613,7 +610,7 @@
 	Ok(specs)
 }
 
-fn objinside(p: &mut Parser<'_>) -> R<ObjBody> {
+fn objinside(p: &mut Parser<'_>) -> Result<ObjBody> {
 	if p.at(T!['}']) {
 		return Ok(ObjBody::MemberList(ObjMembers {
 			locals: Rc::new(Vec::new()),
@@ -641,26 +638,22 @@
 			match m {
 				Member::Field(f) => {
 					if field_member.is_some() {
-						return Err(p.error(
-							"object comprehension can only contain one field".into(),
-						));
+						return Err(
+							p.error("object comprehension can only contain one field".into())
+						);
 					}
 					field_member = Some(f);
 				}
 				Member::BindStmt(b) => locals.push(b),
 				Member::AssertStmt(_) => {
-					return Err(p.error(
-						"asserts are unsupported in object comprehension".into(),
-					));
+					return Err(p.error("asserts are unsupported in object comprehension".into()));
 				}
 			}
 		}
 		Ok(ObjBody::ObjComp(ObjComp {
 			locals: Rc::new(locals),
 			field: Rc::new(
-				field_member.ok_or_else(|| {
-					p.error("missing object comprehension field".into())
-				})?,
+				field_member.ok_or_else(|| p.error("missing object comprehension field".into()))?,
 			),
 			compspecs: specs,
 		}))
@@ -683,7 +676,7 @@
 	}
 }
 
-fn expr_basic(p: &mut Parser<'_>) -> R<Expr> {
+fn expr_basic(p: &mut Parser<'_>) -> Result<Expr> {
 	if let Some(lit) = literal(p) {
 		return Ok(Expr::Literal(lit));
 	}
@@ -825,7 +818,6 @@
 	}
 }
 
-/// Flush accumulated index parts into an Expr::Index wrapping `e`.
 fn flush_index_parts(e: &mut Expr, parts: &mut Vec<IndexPart>) {
 	if parts.is_empty() {
 		return;
@@ -837,7 +829,7 @@
 	};
 }
 
-fn expr_suffix(p: &mut Parser<'_>) -> R<Expr> {
+fn expr_suffix(p: &mut Parser<'_>) -> Result<Expr> {
 	let mut e = expr_basic(p)?;
 	// Accumulate consecutive index parts (.field, [expr], ?.field, ?.[expr])
 	// into a single Expr::Index. This is critical for null-coalesce semantics:
@@ -1006,7 +998,7 @@
 	}
 }
 
-fn expr_bp(p: &mut Parser<'_>, min_bp: u8) -> R<Expr> {
+fn expr_bp(p: &mut Parser<'_>, min_bp: u8) -> Result<Expr> {
 	let mut lhs = if let Some(op) = unary_op(p.peek()) {
 		p.eat_any();
 		let rbp = prefix_binding_power(op);
@@ -1038,11 +1030,11 @@
 	Ok(lhs)
 }
 
-fn expr(p: &mut Parser<'_>) -> R<Expr> {
+fn expr(p: &mut Parser<'_>) -> Result<Expr> {
 	expr_bp(p, 0)
 }
 
-pub fn parse(str: &str, settings: &ParserSettings) -> Result<Expr, ParseError> {
+pub fn parse(str: &str, settings: &ParserSettings) -> Result<Expr> {
 	let mut p = Parser::new(str, settings.source.clone());
 	for lexeme in &p.lexemes {
 		if let Some(desc) = lexeme.kind.error_description() {
@@ -1056,20 +1048,14 @@
 	}
 	let e = expr(&mut p)?;
 	if !p.at_eof() {
-		return Err(p.error(format!(
-			"expected end of file, got {}",
-			p.current_desc(),
-		)));
+		return Err(p.error(format!("expected end of file, got {}", p.current_desc(),)));
 	}
 	Ok(e)
 }
 
 pub fn string_to_expr(s: IStr, settings: &ParserSettings) -> Spanned<Expr> {
 	let len = s.len();
-	Spanned::new(
-		Expr::Str(s),
-		Span(settings.source.clone(), 0, len as u32),
-	)
+	Spanned::new(Expr::Str(s), Span(settings.source.clone(), 0, len as u32))
 }
 
 #[cfg(test)]
modifiedcrates/jrsonnet-ir/src/visit.rsdiffbeforeafterboth
--- a/crates/jrsonnet-ir/src/visit.rs
+++ b/crates/jrsonnet-ir/src/visit.rs
@@ -21,6 +21,7 @@
 	}
 }
 
+#[allow(unused_variables, reason = "used with exp-destruct")]
 pub fn visit_destruct<V: Visitor>(v: &mut V, destruct: &Destruct) {
 	match destruct {
 		Destruct::Full(_istr) => {}
modifiedcrates/jrsonnet-rowan-parser/src/lex.rsdiffbeforeafterboth
--- a/crates/jrsonnet-rowan-parser/src/lex.rs
+++ b/crates/jrsonnet-rowan-parser/src/lex.rs
@@ -11,9 +11,11 @@
 }
 
 pub fn lex(input: &str) -> Vec<Lexeme<'_>> {
-	Lexer::new(input).map(|l| Lexeme {
-		kind: SyntaxKind::from_raw(l.kind.into_raw()),
-		text: l.text,
-		range: TextRange::new(TextSize::from(l.range.0), TextSize::from(l.range.1)),
-	}).collect()
+	Lexer::new(input)
+		.map(|l| Lexeme {
+			kind: SyntaxKind::from_raw(l.kind.into_raw()),
+			text: l.text,
+			range: TextRange::new(TextSize::from(l.range.0), TextSize::from(l.range.1)),
+		})
+		.collect()
 }
modifiedcrates/jrsonnet-stdlib/src/manifest/ini.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/ini.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/ini.rs
@@ -3,8 +3,7 @@
 use jrsonnet_evaluator::{
 	manifest::{ManifestFormat, ToStringFormat},
 	typed::{FromUntyped, Typed},
-	ObjValue, Result, ResultExt, Val,
-	IStr,
+	IStr, ObjValue, Result, ResultExt, Val,
 };
 
 pub struct IniFormat {
modifiedxtask/src/sourcegen/kinds.rsdiffbeforeafterboth
--- a/xtask/src/sourcegen/kinds.rs
+++ b/xtask/src/sourcegen/kinds.rs
@@ -120,11 +120,15 @@
 			Self::Literal { name, .. } => match name.as_str() {
 				"FLOAT" => "number".to_owned(),
 				"IDENT" => "identifier".to_owned(),
-				"STRING_DOUBLE" | "STRING_SINGLE" | "STRING_DOUBLE_VERBATIM"
-				| "STRING_SINGLE_VERBATIM" | "STRING_BLOCK" => "string".to_owned(),
+				"STRING_DOUBLE"
+				| "STRING_SINGLE"
+				| "STRING_DOUBLE_VERBATIM"
+				| "STRING_SINGLE_VERBATIM"
+				| "STRING_BLOCK" => "string".to_owned(),
 				"WHITESPACE" => "whitespace".to_owned(),
-				"SINGLE_LINE_SLASH_COMMENT" | "SINGLE_LINE_HASH_COMMENT"
-				| "MULTI_LINE_COMMENT" => "comment".to_owned(),
+				"SINGLE_LINE_SLASH_COMMENT" | "SINGLE_LINE_HASH_COMMENT" | "MULTI_LINE_COMMENT" => {
+					"comment".to_owned()
+				}
 				_ => name.to_lowercase(),
 			},
 			Self::Meta { name, .. } => name.to_lowercase(),