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

difftreelog

style fix clippy warnings

Yaroslav Bolyukin2023-01-20parent: #974f2c1.patch.diff
in: master

16 files changed

modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -5,7 +5,7 @@
 
 use clap::{CommandFactory, Parser};
 use clap_complete::Shell;
-use jrsonnet_cli::{ManifestOpts, OutputOpts, TraceOpts, MiscOpts, TlaOpts, StdOpts, GcOpts};
+use jrsonnet_cli::{GcOpts, ManifestOpts, MiscOpts, OutputOpts, StdOpts, TlaOpts, TraceOpts};
 use jrsonnet_evaluator::{
 	apply_tla,
 	error::{Error as JrError, ErrorKind},
@@ -133,16 +133,14 @@
 
 fn main_catch(opts: Opts) -> bool {
 	let s = State::default();
-	let trace = opts
-		.trace
-		.trace_format();
+	let trace = opts.trace.trace_format();
 	if let Err(e) = main_real(&s, opts) {
 		if let Error::Evaluation(e) = e {
 			let mut out = String::new();
 			trace.write_trace(&mut out, &e).expect("format error");
 			eprintln!("{out}")
 		} else {
-			eprintln!("{}", e);
+			eprintln!("{e}");
 		}
 		return false;
 	}
@@ -150,7 +148,7 @@
 }
 
 fn main_real(s: &State, opts: Opts) -> Result<(), Error> {
-	let _gc_leak_guard= opts.gc.leak_on_exit();
+	let _gc_leak_guard = opts.gc.leak_on_exit();
 	let _gc_print_stats = opts.gc.stats_printer();
 	let _stack_depth_override = opts.misc.stack_size_override();
 
@@ -220,7 +218,7 @@
 	} else {
 		let output = val.manifest(manifest_format)?;
 		if !output.is_empty() {
-			println!("{}", output);
+			println!("{output}");
 		}
 	}
 
modifiedcrates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -6,7 +6,10 @@
 use std::{env, marker::PhantomData, path::PathBuf};
 
 use clap::Parser;
-use jrsonnet_evaluator::{error::Result, stack::{set_stack_depth_limit, StackDepthLimitOverrideGuard, limit_stack_depth}, FileImportResolver, State, ImportResolver};
+use jrsonnet_evaluator::{
+	stack::{limit_stack_depth, StackDepthLimitOverrideGuard},
+	FileImportResolver,
+};
 use jrsonnet_gcmodule::with_thread_object_space;
 pub use manifest::*;
 pub use stdlib::*;
@@ -71,6 +74,7 @@
 }
 impl GcOpts {
 	pub fn stats_printer(&self) -> Option<GcStatsPrinter> {
+		#[allow(clippy::unnecessary_lazy_evaluations/*, reason = "GcStatsPrinter has side-effect on Drop"*/)]
 		self.gc_print_stats.then(|| GcStatsPrinter {
 			collect_before_printing_stats: self.gc_collect_before_printing_stats,
 		})
@@ -96,7 +100,7 @@
 		eprintln!("=== GC STATS ===");
 		if self.collect_before_printing_stats {
 			let collected = jrsonnet_gcmodule::collect_thread_cycles();
-			eprintln!("Collected: {}", collected);
+			eprintln!("Collected: {collected}");
 		}
 		eprintln!("Tracked: {}", jrsonnet_gcmodule::count_thread_tracked())
 	}
modifiedcrates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -1,10 +1,8 @@
 use std::path::PathBuf;
 
 use clap::{Parser, ValueEnum};
-use jrsonnet_evaluator::{
-	error::Result,
-	manifest::{JsonFormat, ManifestFormat, StringFormat, ToStringFormat, YamlStreamFormat},
-	State,
+use jrsonnet_evaluator::manifest::{
+	JsonFormat, ManifestFormat, StringFormat, ToStringFormat, YamlStreamFormat,
 };
 use jrsonnet_stdlib::{TomlFormat, YamlFormat};
 
modifiedcrates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -1,7 +1,7 @@
 use std::{fs::read_to_string, str::FromStr};
 
 use clap::Parser;
-use jrsonnet_evaluator::{error::Result, tb, trace::PathResolver, State};
+use jrsonnet_evaluator::{error::Result, trace::PathResolver, State};
 use jrsonnet_stdlib::ContextInitializer;
 
 #[derive(Clone)]
@@ -49,7 +49,7 @@
 				name: out[0].into(),
 				value: content,
 			}),
-			Err(e) => Err(format!("{}", e)),
+			Err(e) => Err(format!("{e}")),
 		}
 	}
 }
@@ -86,8 +86,7 @@
 		if self.no_stdlib {
 			return Ok(None);
 		}
-		let ctx =
-			ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback());
+		let ctx = ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback());
 		for ext in self.ext_str.iter() {
 			ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());
 		}
modifiedcrates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -3,7 +3,7 @@
 	error::{ErrorKind, Result},
 	function::TlaArg,
 	gc::GcHashMap,
-	IStr, State,
+	IStr,
 };
 use jrsonnet_parser::{ParserSettings, Source};
 
modifiedcrates/jrsonnet-cli/src/trace.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/trace.rs
+++ b/crates/jrsonnet-cli/src/trace.rs
@@ -1,9 +1,5 @@
 use clap::{Parser, ValueEnum};
-use jrsonnet_evaluator::{
-	error::Result,
-	trace::{CompactFormat, ExplainingFormat, PathResolver, TraceFormat},
-	State,
-};
+use jrsonnet_evaluator::trace::{CompactFormat, ExplainingFormat, PathResolver, TraceFormat};
 
 #[derive(PartialEq, Eq, ValueEnum, Clone)]
 pub enum TraceFormatName {
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -274,6 +274,7 @@
 		f.debug_tuple("LocError").field(&self.0).finish()
 	}
 }
+impl std::error::Error for Error {}
 
 pub trait ErrorSource {
 	fn to_location(self) -> Option<ExprLocation>;
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -104,28 +104,15 @@
 					}
 				}
 			} else {
-				{
-					let ai = a.iter();
-					let bi = b.iter();
+				let ai = a.iter();
+				let bi = b.iter();
 
-					for (a, b) in ai.zip(bi) {
-						let ord = evaluate_compare_op(&a?, &b?, op)?;
-						if !ord.is_eq() {
-							return Ok(ord);
-						}
+				for (a, b) in ai.zip(bi) {
+					let ord = evaluate_compare_op(&a?, &b?, op)?;
+					if !ord.is_eq() {
+						return Ok(ord);
 					}
 				}
-				// {
-				// 	let ai = a.iter_expl();
-				// 	let bi = b.iter_expl();
-
-				// 	for (a, b) in ai.zip(bi) {
-				// 		let ord = evaluate_compare_op(&a?, &b?, op)?;
-				// 		if !ord.is_eq() {
-				// 			return Ok(ord);
-				// 		}
-				// 	}
-				// }
 			}
 			a.len().cmp(&b.len())
 		}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -36,6 +36,7 @@
 	clippy::use_self,
 	// https://github.com/rust-lang/rust-clippy/issues/8539
 	clippy::iter_with_drain,
+	clippy::type_repetition_in_bounds,
 	// ci is being run with nightly, but library should work on stable
 	clippy::missing_const_for_fn,
 )]
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	cell::RefCell,3	fmt::Debug,4	hash::{Hash, Hasher},5	ptr::addr_of,6};78use jrsonnet_gcmodule::{Cc, Trace, Weak};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ExprLocation, Visibility};11use rustc_hash::FxHashMap;1213use crate::{14	error::{Error, ErrorKind::*},15	function::CallLocation,16	gc::{GcHashMap, GcHashSet, TraceBox},17	operator::evaluate_add_op,18	tb, throw, MaybeUnbound, Result, State, Thunk, Unbound, Val,19};2021#[cfg(not(feature = "exp-preserve-order"))]22mod ordering {23	#![allow(24		// This module works as stub for preserve-order feature25		clippy::unused_self,26	)]2728	use jrsonnet_gcmodule::Trace;2930	#[derive(Clone, Copy, Default, Debug, Trace)]31	pub struct FieldIndex;32	impl FieldIndex {33		pub const fn next(self) -> Self {34			Self35		}36	}3738	#[derive(Clone, Copy, Default, Debug, Trace)]39	pub struct SuperDepth;40	impl SuperDepth {41		pub const fn deeper(self) -> Self {42			Self43		}44	}4546	#[derive(Clone, Copy)]47	pub struct FieldSortKey;48	impl FieldSortKey {49		pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {50			Self51		}52	}53}5455#[cfg(feature = "exp-preserve-order")]56mod ordering {57	use std::cmp::Reverse;5859	use jrsonnet_gcmodule::Trace;6061	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]62	pub struct FieldIndex(u32);63	impl FieldIndex {64		pub fn next(self) -> Self {65			Self(self.0 + 1)66		}67	}6869	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]70	pub struct SuperDepth(u32);71	impl SuperDepth {72		pub fn deeper(self) -> Self {73			Self(self.0 + 1)74		}75	}7677	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]78	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);79	impl FieldSortKey {80		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {81			Self(Reverse(depth), index)82		}83		pub fn collide(self, other: Self) -> Self {84			if self.0 .0 > other.0 .0 {85				self86			} else if self.0 .0 < other.0 .0 {87				other88			} else {89				unreachable!("object can't have two fields with same name")90			}91		}92	}93}9495use ordering::*;9697#[allow(clippy::module_name_repetitions)]98#[derive(Debug, Trace)]99pub struct ObjMember {100	pub add: bool,101	pub visibility: Visibility,102	original_index: FieldIndex,103	pub invoke: MaybeUnbound,104	pub location: Option<ExprLocation>,105}106107pub trait ObjectAssertion: Trace {108	fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;109}110111// Field => This112113#[derive(Trace)]114enum CacheValue {115	Cached(Val),116	NotFound,117	Pending,118	Errored(Error),119}120121#[allow(clippy::module_name_repetitions)]122#[derive(Trace)]123#[trace(tracking(force))]124pub struct ObjValueInternals {125	sup: Option<ObjValue>,126	this: Option<ObjValue>,127128	assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,129	assertions_ran: RefCell<GcHashSet<ObjValue>>,130	this_entries: Cc<GcHashMap<IStr, ObjMember>>,131	value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,132}133134#[derive(Clone, Trace)]135pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<ObjValueInternals>);136137impl PartialEq for WeakObjValue {138	fn eq(&self, other: &Self) -> bool {139		Weak::ptr_eq(&self.0, &other.0)140	}141}142143impl Eq for WeakObjValue {}144impl Hash for WeakObjValue {145	fn hash<H: Hasher>(&self, hasher: &mut H) {146		// Safety: usize is POD147		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };148		hasher.write_usize(addr);149	}150}151152#[allow(clippy::module_name_repetitions)]153#[derive(Clone, Trace)]154pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);155impl Debug for ObjValue {156	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {157		if let Some(super_obj) = self.0.sup.as_ref() {158			if f.alternate() {159				write!(f, "{super_obj:#?}")?;160			} else {161				write!(f, "{super_obj:?}")?;162			}163			write!(f, " + ")?;164		}165		let mut debug = f.debug_struct("ObjValue");166		for (name, member) in self.0.this_entries.iter() {167			debug.field(name, member);168		}169		debug.finish_non_exhaustive()170	}171}172173impl ObjValue {174	pub fn new(175		sup: Option<Self>,176		this_entries: Cc<GcHashMap<IStr, ObjMember>>,177		assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,178	) -> Self {179		Self(Cc::new(ObjValueInternals {180			sup,181			this: None,182			assertions,183			assertions_ran: RefCell::new(GcHashSet::new()),184			this_entries,185			value_cache: RefCell::new(GcHashMap::new()),186		}))187	}188	pub fn new_empty() -> Self {189		Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))190	}191	#[must_use]192	pub fn extend_from(&self, sup: Self) -> Self {193		match &self.0.sup {194			None => Self::new(195				Some(sup),196				self.0.this_entries.clone(),197				self.0.assertions.clone(),198			),199			Some(v) => Self::new(200				Some(v.extend_from(sup)),201				self.0.this_entries.clone(),202				self.0.assertions.clone(),203			),204		}205	}206	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {207		let mut new = GcHashMap::with_capacity(1);208		new.insert(key, value);209		Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))210	}211	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {212		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())213	}214215	#[must_use]216	pub fn with_this(&self, this: Self) -> Self {217		Self(Cc::new(ObjValueInternals {218			sup: self.0.sup.clone(),219			assertions: self.0.assertions.clone(),220			assertions_ran: RefCell::new(GcHashSet::new()),221			this: Some(this),222			this_entries: self.0.this_entries.clone(),223			value_cache: RefCell::new(GcHashMap::new()),224		}))225	}226227	pub fn len(&self) -> usize {228		self.fields_visibility()229			.into_iter()230			.filter(|(_, (visible, _))| *visible)231			.count()232	}233234	pub fn is_empty(&self) -> bool {235		if !self.0.this_entries.is_empty() {236			return false;237		}238		self.0.sup.as_ref().map_or(true, Self::is_empty)239	}240241	/// Run callback for every field found in object242	///243	/// Returns true if ended prematurely244	pub(crate) fn enum_fields(245		&self,246		depth: SuperDepth,247		handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,248	) -> bool {249		if let Some(s) = &self.0.sup {250			if s.enum_fields(depth.deeper(), handler) {251				return true;252			}253		}254		for (name, member) in self.0.this_entries.iter() {255			if handler(depth, name, member) {256				return true;257			}258		}259		false260	}261262	pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {263		let mut out = FxHashMap::default();264		self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {265			let new_sort_key = FieldSortKey::new(depth, member.original_index);266			let entry = out.entry(name.clone());267			let (visible, _) = entry.or_insert((true, new_sort_key));268			match member.visibility {269				Visibility::Normal => {}270				Visibility::Hidden => {271					*visible = false;272				}273				Visibility::Unhide => {274					*visible = true;275				}276			};277			false278		});279		out280	}281	pub fn fields_ex(282		&self,283		include_hidden: bool,284		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,285	) -> Vec<IStr> {286		#[cfg(feature = "exp-preserve-order")]287		if preserve_order {288			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self289				.fields_visibility()290				.into_iter()291				.filter(|(_, (visible, _))| include_hidden || *visible)292				.enumerate()293				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))294				.unzip();295			keys.sort_unstable_by_key(|v| v.0);296			// Reorder in-place by resulting indexes297			for i in 0..fields.len() {298				let x = fields[i].clone();299				let mut j = i;300				loop {301					let k = keys[j].1;302					keys[j].1 = j;303					if k == i {304						break;305					}306					fields[j] = fields[k].clone();307					j = k308				}309				fields[j] = x;310			}311			return fields;312		}313314		let mut fields: Vec<_> = self315			.fields_visibility()316			.into_iter()317			.filter(|(_, (visible, _))| include_hidden || *visible)318			.map(|(k, _)| k)319			.collect();320		fields.sort_unstable();321		fields322	}323	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {324		self.fields_ex(325			false,326			#[cfg(feature = "exp-preserve-order")]327			preserve_order,328		)329	}330331	pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {332		if let Some(m) = self.0.this_entries.get(&name) {333			Some(match &m.visibility {334				Visibility::Normal => self335					.0336					.sup337					.as_ref()338					.and_then(|super_obj| super_obj.field_visibility(name))339					.unwrap_or(Visibility::Normal),340				v => *v,341			})342		} else if let Some(super_obj) = &self.0.sup {343			super_obj.field_visibility(name)344		} else {345			None346		}347	}348349	fn has_field_include_hidden(&self, name: IStr) -> bool {350		if self.0.this_entries.contains_key(&name) {351			true352		} else if let Some(super_obj) = &self.0.sup {353			super_obj.has_field_include_hidden(name)354		} else {355			false356		}357	}358359	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {360		if include_hidden {361			self.has_field_include_hidden(name)362		} else {363			self.has_field(name)364		}365	}366	pub fn has_field(&self, name: IStr) -> bool {367		self.field_visibility(name)368			.map_or(false, |v| v.is_visible())369	}370371	pub fn iter(372		&self,373		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,374	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {375		let fields = self.fields(376			#[cfg(feature = "exp-preserve-order")]377			preserve_order,378		);379		fields.into_iter().map(|field| {380			(381				field.clone(),382				self.get(field)383					.map(|opt| opt.expect("iterating over keys, field exists")),384			)385		})386	}387388	pub fn get(&self, key: IStr) -> Result<Option<Val>> {389		self.run_assertions()?;390		let cache_key = (key.clone(), None);391		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {392			return Ok(match v {393				CacheValue::Cached(v) => Some(v.clone()),394				CacheValue::NotFound => None,395				CacheValue::Pending => throw!(InfiniteRecursionDetected),396				CacheValue::Errored(e) => return Err(e.clone()),397			});398		}399		self.0400			.value_cache401			.borrow_mut()402			.insert(cache_key.clone(), CacheValue::Pending);403		let value = self404			.get_raw(key, self.0.this.clone().unwrap_or_else(|| self.clone()))405			.map_err(|e| {406				self.0407					.value_cache408					.borrow_mut()409					.insert(cache_key.clone(), CacheValue::Errored(e.clone()));410				e411			})?;412		self.0.value_cache.borrow_mut().insert(413			cache_key,414			value415				.as_ref()416				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),417		);418		Ok(value)419	}420	pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {421		self.run_assertions()?;422		let cache_key = (key.clone(), Some(this.clone().downgrade()));423		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {424			return Ok(match v {425				CacheValue::Cached(v) => Some(v.clone()),426				CacheValue::NotFound => None,427				CacheValue::Pending => throw!(InfiniteRecursionDetected),428				CacheValue::Errored(e) => return Err(e.clone()),429			});430		}431		self.0432			.value_cache433			.borrow_mut()434			.insert(cache_key.clone(), CacheValue::Pending);435		let value = self.get_raw(key, this).map_err(|e| {436			self.0437				.value_cache438				.borrow_mut()439				.insert(cache_key.clone(), CacheValue::Errored(e.clone()));440			e441		})?;442		self.0.value_cache.borrow_mut().insert(443			cache_key,444			value445				.as_ref()446				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),447		);448		Ok(value)449	}450451	fn get_raw(&self, key: IStr, real_this: Self) -> Result<Option<Val>> {452		match (self.0.this_entries.get(&key), &self.0.sup) {453			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),454			(Some(k), Some(super_obj)) => {455				let our = self.evaluate_this(k, real_this.clone())?;456				if k.add {457					super_obj458						.get_raw(key, real_this)?459						.map_or(Ok(Some(our.clone())), |v| {460							Ok(Some(evaluate_add_op(&v, &our)?))461						})462				} else {463					Ok(Some(our))464				}465			}466			(None, Some(super_obj)) => super_obj.get_raw(key, real_this),467			(None, None) => Ok(None),468		}469	}470	fn evaluate_this(&self, v: &ObjMember, real_this: Self) -> Result<Val> {471		v.invoke.evaluate(self.0.sup.clone(), Some(real_this))472	}473474	fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {475		if self.0.assertions.is_empty() {476			if let Some(super_obj) = &self.0.sup {477				super_obj.run_assertions_raw(real_this)?;478			}479			return Ok(());480		}481		if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {482			for assertion in self.0.assertions.iter() {483				if let Err(e) = assertion.run(self.0.sup.clone(), Some(real_this.clone())) {484					self.0.assertions_ran.borrow_mut().remove(real_this);485					return Err(e);486				}487			}488			if let Some(super_obj) = &self.0.sup {489				super_obj.run_assertions_raw(real_this)?;490			}491		}492		Ok(())493	}494	pub fn run_assertions(&self) -> Result<()> {495		self.run_assertions_raw(self)496	}497498	pub fn ptr_eq(a: &Self, b: &Self) -> bool {499		Cc::ptr_eq(&a.0, &b.0)500	}501	pub fn downgrade(self) -> WeakObjValue {502		WeakObjValue(self.0.downgrade())503	}504}505506impl PartialEq for ObjValue {507	fn eq(&self, other: &Self) -> bool {508		Cc::ptr_eq(&self.0, &other.0)509	}510}511512impl Eq for ObjValue {}513impl Hash for ObjValue {514	fn hash<H: Hasher>(&self, hasher: &mut H) {515		hasher.write_usize(addr_of!(*self.0) as usize);516	}517}518519#[allow(clippy::module_name_repetitions)]520pub struct ObjValueBuilder {521	sup: Option<ObjValue>,522	map: GcHashMap<IStr, ObjMember>,523	assertions: Vec<TraceBox<dyn ObjectAssertion>>,524	next_field_index: FieldIndex,525}526impl ObjValueBuilder {527	pub fn new() -> Self {528		Self::with_capacity(0)529	}530	pub fn with_capacity(capacity: usize) -> Self {531		Self {532			sup: None,533			map: GcHashMap::with_capacity(capacity),534			assertions: Vec::new(),535			next_field_index: FieldIndex::default(),536		}537	}538	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {539		self.assertions.reserve_exact(capacity);540		self541	}542	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {543		self.sup = Some(super_obj);544		self545	}546547	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {548		self.assertions.push(tb!(assertion));549		self550	}551	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {552		let field_index = self.next_field_index;553		self.next_field_index = self.next_field_index.next();554		ObjMemberBuilder::new(ValueBuilder(self), name, field_index)555	}556557	pub fn build(self) -> ObjValue {558		ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))559	}560}561impl Default for ObjValueBuilder {562	fn default() -> Self {563		Self::with_capacity(0)564	}565}566567#[allow(clippy::module_name_repetitions)]568#[must_use = "value not added unless binding() was called"]569pub struct ObjMemberBuilder<Kind> {570	kind: Kind,571	name: IStr,572	add: bool,573	visibility: Visibility,574	original_index: FieldIndex,575	location: Option<ExprLocation>,576}577578#[allow(clippy::missing_const_for_fn)]579impl<Kind> ObjMemberBuilder<Kind> {580	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {581		Self {582			kind,583			name,584			original_index,585			add: false,586			visibility: Visibility::Normal,587			location: None,588		}589	}590591	pub const fn with_add(mut self, add: bool) -> Self {592		self.add = add;593		self594	}595	pub fn add(self) -> Self {596		self.with_add(true)597	}598	pub fn with_visibility(mut self, visibility: Visibility) -> Self {599		self.visibility = visibility;600		self601	}602	pub fn hide(self) -> Self {603		self.with_visibility(Visibility::Hidden)604	}605	pub fn with_location(mut self, location: ExprLocation) -> Self {606		self.location = Some(location);607		self608	}609	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {610		(611			self.kind,612			self.name,613			ObjMember {614				add: self.add,615				visibility: self.visibility,616				original_index: self.original_index,617				invoke: binding,618				location: self.location,619			},620		)621	}622}623624pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);625impl ObjMemberBuilder<ValueBuilder<'_>> {626	/// Inserts value, replacing if it is already defined627	pub fn value_unchecked(self, value: Val) {628		let (receiver, name, member) =629			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));630		let entry = receiver.0.map.entry(name);631		entry.insert(member);632	}633634	pub fn value(self, value: Val) -> Result<()> {635		self.thunk(Thunk::evaluated(value))636	}637	pub fn thunk(self, value: Thunk<Val>) -> Result<()> {638		self.binding(MaybeUnbound::Bound(value))639	}640	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {641		self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))642	}643	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {644		let (receiver, name, member) = self.build_member(binding);645		let location = member.location.clone();646		let old = receiver.0.map.insert(name.clone(), member);647		if old.is_some() {648			State::push(649				CallLocation(location.as_ref()),650				|| format!("field <{}> initializtion", name.clone()),651				|| throw!(DuplicateFieldName(name.clone())),652			)?;653		}654		Ok(())655	}656}657658pub struct ExtendBuilder<'v>(&'v mut ObjValue);659impl ObjMemberBuilder<ExtendBuilder<'_>> {660	pub fn value(self, value: Val) {661		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));662	}663	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {664		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));665	}666	pub fn binding(self, binding: MaybeUnbound) {667		let (receiver, name, member) = self.build_member(binding);668		let new = receiver.0.clone();669		*receiver.0 = new.extend_with_raw_member(name, member);670	}671}
after · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	cell::RefCell,3	fmt::Debug,4	hash::{Hash, Hasher},5	ptr::addr_of,6};78use jrsonnet_gcmodule::{Cc, Trace, Weak};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ExprLocation, Visibility};11use rustc_hash::FxHashMap;1213use crate::{14	error::{Error, ErrorKind::*},15	function::CallLocation,16	gc::{GcHashMap, GcHashSet, TraceBox},17	operator::evaluate_add_op,18	tb, throw, MaybeUnbound, Result, State, Thunk, Unbound, Val,19};2021#[cfg(not(feature = "exp-preserve-order"))]22mod ordering {23	#![allow(24		// This module works as stub for preserve-order feature25		clippy::unused_self,26	)]2728	use jrsonnet_gcmodule::Trace;2930	#[derive(Clone, Copy, Default, Debug, Trace)]31	pub struct FieldIndex;32	impl FieldIndex {33		pub const fn next(self) -> Self {34			Self35		}36	}3738	#[derive(Clone, Copy, Default, Debug, Trace)]39	pub struct SuperDepth;40	impl SuperDepth {41		pub const fn deeper(self) -> Self {42			Self43		}44	}4546	#[derive(Clone, Copy)]47	pub struct FieldSortKey;48	impl FieldSortKey {49		pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {50			Self51		}52	}53}5455#[cfg(feature = "exp-preserve-order")]56mod ordering {57	use std::cmp::{Ordering, Reverse};5859	use jrsonnet_gcmodule::Trace;6061	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]62	pub struct FieldIndex(u32);63	impl FieldIndex {64		pub fn next(self) -> Self {65			Self(self.0 + 1)66		}67	}6869	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]70	pub struct SuperDepth(u32);71	impl SuperDepth {72		pub fn deeper(self) -> Self {73			Self(self.0 + 1)74		}75	}7677	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]78	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);79	impl FieldSortKey {80		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {81			Self(Reverse(depth), index)82		}83		pub fn collide(self, other: Self) -> Self {84			match self.0 .0.cmp(&other.0 .0) {85				Ordering::Greater => self,86				Ordering::Less => other,87				Ordering::Equal => unreachable!("object can't have two fields with the same name"),88			}89		}90	}91}9293use ordering::*;9495#[allow(clippy::module_name_repetitions)]96#[derive(Debug, Trace)]97pub struct ObjMember {98	pub add: bool,99	pub visibility: Visibility,100	original_index: FieldIndex,101	pub invoke: MaybeUnbound,102	pub location: Option<ExprLocation>,103}104105pub trait ObjectAssertion: Trace {106	fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;107}108109// Field => This110111#[derive(Trace)]112enum CacheValue {113	Cached(Val),114	NotFound,115	Pending,116	Errored(Error),117}118119#[allow(clippy::module_name_repetitions)]120#[derive(Trace)]121#[trace(tracking(force))]122pub struct ObjValueInternals {123	sup: Option<ObjValue>,124	this: Option<ObjValue>,125126	assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,127	assertions_ran: RefCell<GcHashSet<ObjValue>>,128	this_entries: Cc<GcHashMap<IStr, ObjMember>>,129	value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,130}131132#[derive(Clone, Trace)]133pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<ObjValueInternals>);134135impl PartialEq for WeakObjValue {136	fn eq(&self, other: &Self) -> bool {137		Weak::ptr_eq(&self.0, &other.0)138	}139}140141impl Eq for WeakObjValue {}142impl Hash for WeakObjValue {143	fn hash<H: Hasher>(&self, hasher: &mut H) {144		// Safety: usize is POD145		let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };146		hasher.write_usize(addr);147	}148}149150#[allow(clippy::module_name_repetitions)]151#[derive(Clone, Trace)]152pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);153impl Debug for ObjValue {154	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {155		if let Some(super_obj) = self.0.sup.as_ref() {156			if f.alternate() {157				write!(f, "{super_obj:#?}")?;158			} else {159				write!(f, "{super_obj:?}")?;160			}161			write!(f, " + ")?;162		}163		let mut debug = f.debug_struct("ObjValue");164		for (name, member) in self.0.this_entries.iter() {165			debug.field(name, member);166		}167		debug.finish_non_exhaustive()168	}169}170171impl ObjValue {172	pub fn new(173		sup: Option<Self>,174		this_entries: Cc<GcHashMap<IStr, ObjMember>>,175		assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,176	) -> Self {177		Self(Cc::new(ObjValueInternals {178			sup,179			this: None,180			assertions,181			assertions_ran: RefCell::new(GcHashSet::new()),182			this_entries,183			value_cache: RefCell::new(GcHashMap::new()),184		}))185	}186	pub fn new_empty() -> Self {187		Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))188	}189	pub fn builder() -> ObjValueBuilder {190		ObjValueBuilder::new()191	}192	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {193		ObjValueBuilder::with_capacity(capacity)194	}195	#[must_use]196	pub fn extend_from(&self, sup: Self) -> Self {197		match &self.0.sup {198			None => Self::new(199				Some(sup),200				self.0.this_entries.clone(),201				self.0.assertions.clone(),202			),203			Some(v) => Self::new(204				Some(v.extend_from(sup)),205				self.0.this_entries.clone(),206				self.0.assertions.clone(),207			),208		}209	}210	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {211		let mut new = GcHashMap::with_capacity(1);212		new.insert(key, value);213		Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))214	}215	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {216		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())217	}218219	#[must_use]220	pub fn with_this(&self, this: Self) -> Self {221		Self(Cc::new(ObjValueInternals {222			sup: self.0.sup.clone(),223			assertions: self.0.assertions.clone(),224			assertions_ran: RefCell::new(GcHashSet::new()),225			this: Some(this),226			this_entries: self.0.this_entries.clone(),227			value_cache: RefCell::new(GcHashMap::new()),228		}))229	}230231	pub fn len(&self) -> usize {232		self.fields_visibility()233			.into_iter()234			.filter(|(_, (visible, _))| *visible)235			.count()236	}237238	pub fn is_empty(&self) -> bool {239		if !self.0.this_entries.is_empty() {240			return false;241		}242		self.0.sup.as_ref().map_or(true, Self::is_empty)243	}244245	/// Run callback for every field found in object246	///247	/// Returns true if ended prematurely248	pub(crate) fn enum_fields(249		&self,250		depth: SuperDepth,251		handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,252	) -> bool {253		if let Some(s) = &self.0.sup {254			if s.enum_fields(depth.deeper(), handler) {255				return true;256			}257		}258		for (name, member) in self.0.this_entries.iter() {259			if handler(depth, name, member) {260				return true;261			}262		}263		false264	}265266	pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {267		let mut out = FxHashMap::default();268		self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {269			let new_sort_key = FieldSortKey::new(depth, member.original_index);270			let entry = out.entry(name.clone());271			let (visible, _) = entry.or_insert((true, new_sort_key));272			match member.visibility {273				Visibility::Normal => {}274				Visibility::Hidden => {275					*visible = false;276				}277				Visibility::Unhide => {278					*visible = true;279				}280			};281			false282		});283		out284	}285	pub fn fields_ex(286		&self,287		include_hidden: bool,288		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,289	) -> Vec<IStr> {290		#[cfg(feature = "exp-preserve-order")]291		if preserve_order {292			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self293				.fields_visibility()294				.into_iter()295				.filter(|(_, (visible, _))| include_hidden || *visible)296				.enumerate()297				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))298				.unzip();299			keys.sort_unstable_by_key(|v| v.0);300			// Reorder in-place by resulting indexes301			for i in 0..fields.len() {302				let x = fields[i].clone();303				let mut j = i;304				loop {305					let k = keys[j].1;306					keys[j].1 = j;307					if k == i {308						break;309					}310					fields[j] = fields[k].clone();311					j = k;312				}313				fields[j] = x;314			}315			return fields;316		}317318		let mut fields: Vec<_> = self319			.fields_visibility()320			.into_iter()321			.filter(|(_, (visible, _))| include_hidden || *visible)322			.map(|(k, _)| k)323			.collect();324		fields.sort_unstable();325		fields326	}327	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {328		self.fields_ex(329			false,330			#[cfg(feature = "exp-preserve-order")]331			preserve_order,332		)333	}334335	pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {336		if let Some(m) = self.0.this_entries.get(&name) {337			Some(match &m.visibility {338				Visibility::Normal => self339					.0340					.sup341					.as_ref()342					.and_then(|super_obj| super_obj.field_visibility(name))343					.unwrap_or(Visibility::Normal),344				v => *v,345			})346		} else if let Some(super_obj) = &self.0.sup {347			super_obj.field_visibility(name)348		} else {349			None350		}351	}352353	fn has_field_include_hidden(&self, name: IStr) -> bool {354		if self.0.this_entries.contains_key(&name) {355			true356		} else if let Some(super_obj) = &self.0.sup {357			super_obj.has_field_include_hidden(name)358		} else {359			false360		}361	}362363	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {364		if include_hidden {365			self.has_field_include_hidden(name)366		} else {367			self.has_field(name)368		}369	}370	pub fn has_field(&self, name: IStr) -> bool {371		self.field_visibility(name)372			.map_or(false, |v| v.is_visible())373	}374375	pub fn iter(376		&self,377		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,378	) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {379		let fields = self.fields(380			#[cfg(feature = "exp-preserve-order")]381			preserve_order,382		);383		fields.into_iter().map(|field| {384			(385				field.clone(),386				self.get(field)387					.map(|opt| opt.expect("iterating over keys, field exists")),388			)389		})390	}391392	pub fn get(&self, key: IStr) -> Result<Option<Val>> {393		self.run_assertions()?;394		let cache_key = (key.clone(), None);395		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {396			return Ok(match v {397				CacheValue::Cached(v) => Some(v.clone()),398				CacheValue::NotFound => None,399				CacheValue::Pending => throw!(InfiniteRecursionDetected),400				CacheValue::Errored(e) => return Err(e.clone()),401			});402		}403		self.0404			.value_cache405			.borrow_mut()406			.insert(cache_key.clone(), CacheValue::Pending);407		let value = self408			.get_raw(key, self.0.this.clone().unwrap_or_else(|| self.clone()))409			.map_err(|e| {410				self.0411					.value_cache412					.borrow_mut()413					.insert(cache_key.clone(), CacheValue::Errored(e.clone()));414				e415			})?;416		self.0.value_cache.borrow_mut().insert(417			cache_key,418			value419				.as_ref()420				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),421		);422		Ok(value)423	}424	pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {425		self.run_assertions()?;426		let cache_key = (key.clone(), Some(this.clone().downgrade()));427		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {428			return Ok(match v {429				CacheValue::Cached(v) => Some(v.clone()),430				CacheValue::NotFound => None,431				CacheValue::Pending => throw!(InfiniteRecursionDetected),432				CacheValue::Errored(e) => return Err(e.clone()),433			});434		}435		self.0436			.value_cache437			.borrow_mut()438			.insert(cache_key.clone(), CacheValue::Pending);439		let value = self.get_raw(key, this).map_err(|e| {440			self.0441				.value_cache442				.borrow_mut()443				.insert(cache_key.clone(), CacheValue::Errored(e.clone()));444			e445		})?;446		self.0.value_cache.borrow_mut().insert(447			cache_key,448			value449				.as_ref()450				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),451		);452		Ok(value)453	}454455	fn get_raw(&self, key: IStr, real_this: Self) -> Result<Option<Val>> {456		match (self.0.this_entries.get(&key), &self.0.sup) {457			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),458			(Some(k), Some(super_obj)) => {459				let our = self.evaluate_this(k, real_this.clone())?;460				if k.add {461					super_obj462						.get_raw(key, real_this)?463						.map_or(Ok(Some(our.clone())), |v| {464							Ok(Some(evaluate_add_op(&v, &our)?))465						})466				} else {467					Ok(Some(our))468				}469			}470			(None, Some(super_obj)) => super_obj.get_raw(key, real_this),471			(None, None) => Ok(None),472		}473	}474	fn evaluate_this(&self, v: &ObjMember, real_this: Self) -> Result<Val> {475		v.invoke.evaluate(self.0.sup.clone(), Some(real_this))476	}477478	fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {479		if self.0.assertions.is_empty() {480			if let Some(super_obj) = &self.0.sup {481				super_obj.run_assertions_raw(real_this)?;482			}483			return Ok(());484		}485		if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {486			for assertion in self.0.assertions.iter() {487				if let Err(e) = assertion.run(self.0.sup.clone(), Some(real_this.clone())) {488					self.0.assertions_ran.borrow_mut().remove(real_this);489					return Err(e);490				}491			}492			if let Some(super_obj) = &self.0.sup {493				super_obj.run_assertions_raw(real_this)?;494			}495		}496		Ok(())497	}498	pub fn run_assertions(&self) -> Result<()> {499		self.run_assertions_raw(self)500	}501502	pub fn ptr_eq(a: &Self, b: &Self) -> bool {503		Cc::ptr_eq(&a.0, &b.0)504	}505	pub fn downgrade(self) -> WeakObjValue {506		WeakObjValue(self.0.downgrade())507	}508}509510impl PartialEq for ObjValue {511	fn eq(&self, other: &Self) -> bool {512		Cc::ptr_eq(&self.0, &other.0)513	}514}515516impl Eq for ObjValue {}517impl Hash for ObjValue {518	fn hash<H: Hasher>(&self, hasher: &mut H) {519		hasher.write_usize(addr_of!(*self.0) as usize);520	}521}522523#[allow(clippy::module_name_repetitions)]524pub struct ObjValueBuilder {525	sup: Option<ObjValue>,526	map: GcHashMap<IStr, ObjMember>,527	assertions: Vec<TraceBox<dyn ObjectAssertion>>,528	next_field_index: FieldIndex,529}530impl ObjValueBuilder {531	pub fn new() -> Self {532		Self::with_capacity(0)533	}534	pub fn with_capacity(capacity: usize) -> Self {535		Self {536			sup: None,537			map: GcHashMap::with_capacity(capacity),538			assertions: Vec::new(),539			next_field_index: FieldIndex::default(),540		}541	}542	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {543		self.assertions.reserve_exact(capacity);544		self545	}546	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {547		self.sup = Some(super_obj);548		self549	}550551	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {552		self.assertions.push(tb!(assertion));553		self554	}555	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {556		let field_index = self.next_field_index;557		self.next_field_index = self.next_field_index.next();558		ObjMemberBuilder::new(ValueBuilder(self), name, field_index)559	}560561	pub fn build(self) -> ObjValue {562		ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))563	}564}565impl Default for ObjValueBuilder {566	fn default() -> Self {567		Self::with_capacity(0)568	}569}570571#[allow(clippy::module_name_repetitions)]572#[must_use = "value not added unless binding() was called"]573pub struct ObjMemberBuilder<Kind> {574	kind: Kind,575	name: IStr,576	add: bool,577	visibility: Visibility,578	original_index: FieldIndex,579	location: Option<ExprLocation>,580}581582#[allow(clippy::missing_const_for_fn)]583impl<Kind> ObjMemberBuilder<Kind> {584	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {585		Self {586			kind,587			name,588			original_index,589			add: false,590			visibility: Visibility::Normal,591			location: None,592		}593	}594595	pub const fn with_add(mut self, add: bool) -> Self {596		self.add = add;597		self598	}599	pub fn add(self) -> Self {600		self.with_add(true)601	}602	pub fn with_visibility(mut self, visibility: Visibility) -> Self {603		self.visibility = visibility;604		self605	}606	pub fn hide(self) -> Self {607		self.with_visibility(Visibility::Hidden)608	}609	pub fn with_location(mut self, location: ExprLocation) -> Self {610		self.location = Some(location);611		self612	}613	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {614		(615			self.kind,616			self.name,617			ObjMember {618				add: self.add,619				visibility: self.visibility,620				original_index: self.original_index,621				invoke: binding,622				location: self.location,623			},624		)625	}626}627628pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);629impl ObjMemberBuilder<ValueBuilder<'_>> {630	/// Inserts value, replacing if it is already defined631	pub fn value_unchecked(self, value: Val) {632		let (receiver, name, member) =633			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));634		let entry = receiver.0.map.entry(name);635		entry.insert(member);636	}637638	pub fn value(self, value: Val) -> Result<()> {639		self.thunk(Thunk::evaluated(value))640	}641	pub fn thunk(self, value: Thunk<Val>) -> Result<()> {642		self.binding(MaybeUnbound::Bound(value))643	}644	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {645		self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))646	}647	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {648		let (receiver, name, member) = self.build_member(binding);649		let location = member.location.clone();650		let old = receiver.0.map.insert(name.clone(), member);651		if old.is_some() {652			State::push(653				CallLocation(location.as_ref()),654				|| format!("field <{}> initializtion", name.clone()),655				|| throw!(DuplicateFieldName(name.clone())),656			)?;657		}658		Ok(())659	}660}661662pub struct ExtendBuilder<'v>(&'v mut ObjValue);663impl ObjMemberBuilder<ExtendBuilder<'_>> {664	pub fn value(self, value: Val) {665		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));666	}667	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {668		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));669	}670	pub fn binding(self, binding: MaybeUnbound) {671		let (receiver, name, member) = self.build_member(binding);672		let new = receiver.0.clone();673		*receiver.0 = new.extend_with_raw_member(name, member);674	}675}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -33,6 +33,7 @@
 	Pending,
 }
 
+/// Lazily evaluated value
 #[allow(clippy::module_name_repetitions)]
 #[derive(Clone, Trace)]
 pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);
@@ -57,6 +58,13 @@
 		self.evaluate()?;
 		Ok(())
 	}
+
+	/// Evaluate thunk, or return cached value
+	///
+	/// # Errors
+	///
+	/// - Lazy value evaluation returned error
+	/// - This method was called during inner value evaluation
 	pub fn evaluate(&self) -> Result<T> {
 		match &*self.0.borrow() {
 			ThunkInner::Computed(v) => return Ok(v.clone()),
@@ -132,7 +140,7 @@
 	}
 }
 
-/// Represents a Jsonnet value, which can be spliced or indexed (string or array).
+/// Represents a Jsonnet value, which can be sliced or indexed (string or array).
 #[allow(clippy::module_name_repetitions)]
 pub enum IndexableVal {
 	/// String.
@@ -247,6 +255,16 @@
 		}
 	}
 }
+impl From<&str> for StrValue {
+	fn from(value: &str) -> Self {
+		Self::Flat(value.into())
+	}
+}
+impl From<String> for StrValue {
+	fn from(value: String) -> Self {
+		Self::Flat(value.into())
+	}
+}
 impl Display for StrValue {
 	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 		match self {
modifiedcrates/jrsonnet-parser/src/source.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/source.rs
+++ b/crates/jrsonnet-parser/src/source.rs
@@ -33,8 +33,8 @@
 		}
 		fn dyn_eq(&self, other: &dyn $T) -> bool {
 			let Some(other) = other.as_any().downcast_ref::<Self>() else {
-												return false
-											};
+				return false
+			};
 			let this = <Self as $T>::as_any(self)
 				.downcast_ref::<Self>()
 				.expect("restricted by impl");
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -211,7 +211,7 @@
 				locs[0].line
 			);
 		}
-		eprintln!(" {}", value);
+		eprintln!(" {value}");
 	}
 }
 
@@ -229,7 +229,7 @@
 }
 
 fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {
-	let source_name = format!("<extvar:{}>", name);
+	let source_name = format!("<extvar:{name}>");
 	Source::new_virtual(source_name.into(), code.into())
 }
 
modifiedcrates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -46,7 +46,7 @@
 		.ext_natives
 		.get(&x)
 		.cloned()
-		.map_or(Val::Null, |v| Val::Func(FuncVal::Builtin(v.clone())))
+		.map_or(Val::Null, |v| Val::Func(FuncVal::Builtin(v)))
 }
 
 #[builtin(fields(
modifiedcrates/jrsonnet-stdlib/src/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/parse.rs
+++ b/crates/jrsonnet-stdlib/src/parse.rs
@@ -8,7 +8,7 @@
 #[builtin]
 pub fn builtin_parse_json(str: IStr) -> Result<Val> {
 	let value: Val = serde_json::from_str(&str)
-		.map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;
+		.map_err(|e| RuntimeError(format!("failed to parse json: {e}").into()))?;
 	Ok(value)
 }
 
@@ -22,7 +22,7 @@
 	let mut out = vec![];
 	for item in value {
 		let val = Val::deserialize(item)
-			.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
+			.map_err(|e| RuntimeError(format!("failed to parse yaml: {e}").into()))?;
 		out.push(val);
 	}
 	Ok(if out.is_empty() {
modifiedcrates/jrsonnet-types/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -150,7 +150,7 @@
 		if should_add_braces {
 			write!(f, "(")?;
 		}
-		write!(f, "{}", v)?;
+		write!(f, "{v}")?;
 		if should_add_braces {
 			write!(f, ")")?;
 		}
@@ -162,7 +162,7 @@
 	if *a == ComplexValType::Any {
 		write!(f, "array")?
 	} else {
-		write!(f, "Array<{}>", a)?
+		write!(f, "Array<{a}>")?
 	}
 	Ok(())
 }
@@ -171,7 +171,7 @@
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		match self {
 			ComplexValType::Any => write!(f, "any")?,
-			ComplexValType::Simple(s) => write!(f, "{}", s)?,
+			ComplexValType::Simple(s) => write!(f, "{s}")?,
 			ComplexValType::Char => write!(f, "char")?,
 			ComplexValType::BoundedNumber(a, b) => write!(
 				f,
@@ -187,7 +187,7 @@
 					if i != 0 {
 						write!(f, ", ")?;
 					}
-					write!(f, "{}: {}", k, v)?;
+					write!(f, "{k}: {v}")?;
 				}
 				write!(f, "}}")?;
 			}