git.delta.rocks / jrsonnet / refs/commits / 4f4be44d138e

difftreelog

style fix clippy warnings

Yaroslav Bolyukin2022-04-20parent: #ed4ee4d.patch.diff
in: master

5 files changed

modifiedcrates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -15,12 +15,12 @@
 #[derive(Clone, Copy)]
 pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);
 impl<'l> CallLocation<'l> {
-	pub fn new(loc: &'l ExprLocation) -> Self {
+	pub const fn new(loc: &'l ExprLocation) -> Self {
 		Self(Some(loc))
 	}
 }
 impl CallLocation<'static> {
-	pub fn native() -> Self {
+	pub const fn native() -> Self {
 		Self(None)
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -20,7 +20,7 @@
 			Val::Arr(a) => {
 				let mut out = Vec::with_capacity(a.len());
 				for item in a.iter() {
-					out.push((&item?).try_into()?);
+					out.push(item?.try_into()?);
 				}
 				Self::Array(out)
 			}
@@ -29,8 +29,8 @@
 				for key in o.fields() {
 					out.insert(
 						(&key as &str).into(),
-						(&o.get(key)?
-							.expect("key is present in fields, so value should exist"))
+						o.get(key)?
+							.expect("key is present in fields, so value should exist")
 							.try_into()?,
 					);
 				}
@@ -40,6 +40,13 @@
 		})
 	}
 }
+impl TryFrom<Val> for Value {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self, Self::Error> {
+		<Self as TryFrom<&Val>>::try_from(&value)
+	}
+}
 
 impl TryFrom<&Value> for Val {
 	type Error = LocError;
@@ -68,3 +75,10 @@
 		})
 	}
 }
+impl TryFrom<Value> for Val {
+	type Error = LocError;
+
+	fn try_from(value: Value) -> Result<Self, Self::Error> {
+		<Self as TryFrom<&Value>>::try_from(&value)
+	}
+}
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -442,7 +442,7 @@
 	fn try_from(value: Val) -> Result<Self, Self::Error> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
-			Val::Func(FuncVal::Normal(desc)) => Ok(desc.clone()),
+			Val::Func(FuncVal::Normal(desc)) => Ok(desc),
 			Val::Func(_) => throw!(RuntimeError("expected normal function, not builtin".into())),
 			_ => unreachable!(),
 		}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/val.rs
1use crate::{2	builtin::manifest::{3		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,4	},5	cc_ptr_eq,6	error::{Error::*, LocError},7	evaluate,8	function::{9		parse_default_function_call, parse_function_call, ArgsLike, Builtin, CallLocation,10		StaticBuiltin,11	},12	gc::TraceBox,13	throw, Context, ObjValue, Result,14};15use gcmodule::{Cc, Trace};16use jrsonnet_interner::IStr;17use jrsonnet_parser::{LocExpr, ParamsDesc};18use jrsonnet_types::ValType;19use std::{cell::RefCell, fmt::Debug, rc::Rc};2021pub trait LazyValValue: Trace {22	fn get(self: Box<Self>) -> Result<Val>;23}2425#[derive(Trace)]26enum LazyValInternals {27	Computed(Val),28	Errored(LocError),29	Waiting(TraceBox<dyn LazyValValue>),30	Pending,31}3233#[derive(Clone, Trace)]34pub struct LazyVal(Cc<RefCell<LazyValInternals>>);35impl LazyVal {36	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {37		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))38	}39	pub fn new_resolved(val: Val) -> Self {40		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))41	}42	pub fn force(&self) -> Result<()> {43		self.evaluate()?;44		Ok(())45	}46	pub fn evaluate(&self) -> Result<Val> {47		match &*self.0.borrow() {48			LazyValInternals::Computed(v) => return Ok(v.clone()),49			LazyValInternals::Errored(e) => return Err(e.clone()),50			LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),51			_ => (),52		};53		let value = if let LazyValInternals::Waiting(value) =54			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)55		{56			value57		} else {58			unreachable!()59		};60		let new_value = match value.0.get() {61			Ok(v) => v,62			Err(e) => {63				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());64				return Err(e);65			}66		};67		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());68		Ok(new_value)69	}70}7172impl Debug for LazyVal {73	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {74		write!(f, "Lazy")75	}76}77impl PartialEq for LazyVal {78	fn eq(&self, other: &Self) -> bool {79		cc_ptr_eq(&self.0, &other.0)80	}81}8283#[derive(Debug, PartialEq, Trace)]84pub struct FuncDesc {85	pub name: IStr,86	pub ctx: Context,87	pub params: ParamsDesc,88	pub body: LocExpr,89}90impl FuncDesc {91	/// Create body context, but fill arguments without defaults with lazy error92	pub fn default_body_context(&self) -> Context {93		parse_default_function_call(self.ctx.clone(), &self.params)94	}9596	/// Create context, with which body code will run97	pub fn call_body_context(98		&self,99		call_ctx: Context,100		args: &dyn ArgsLike,101		tailstrict: bool,102	) -> Result<Context> {103		parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)104	}105}106107#[derive(Trace, Clone)]108pub enum FuncVal {109	/// Plain function implemented in jsonnet110	Normal(Cc<FuncDesc>),111	/// Standard library function112	StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),113	/// User-provided function114	Builtin(Cc<TraceBox<dyn Builtin>>),115}116117impl Debug for FuncVal {118	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {119		match self {120			Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),121			Self::StaticBuiltin(arg0) => {122				f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()123			}124			Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),125		}126	}127}128129impl PartialEq for FuncVal {130	fn eq(&self, other: &Self) -> bool {131		match (self, other) {132			(Self::Normal(a), Self::Normal(b)) => a == b,133			(Self::StaticBuiltin(an), Self::StaticBuiltin(bn)) => std::ptr::eq(*an, *bn),134			(..) => false,135		}136	}137}138impl FuncVal {139	pub fn args_len(&self) -> usize {140		match self {141			Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),142			Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),143			Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),144		}145	}146	pub fn name(&self) -> IStr {147		match self {148			Self::Normal(normal) => normal.name.clone(),149			Self::StaticBuiltin(builtin) => builtin.name().into(),150			Self::Builtin(builtin) => builtin.name().into(),151		}152	}153	pub fn evaluate(154		&self,155		call_ctx: Context,156		loc: CallLocation,157		args: &dyn ArgsLike,158		tailstrict: bool,159	) -> Result<Val> {160		match self {161			Self::Normal(func) => {162				let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;163				evaluate(body_ctx, &func.body)164			}165			Self::StaticBuiltin(b) => b.call(call_ctx, loc, args),166			Self::Builtin(b) => b.call(call_ctx, loc, args),167		}168	}169	pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {170		self.evaluate(Context::default(), CallLocation::native(), args, true)171	}172}173174#[derive(Clone)]175pub enum ManifestFormat {176	YamlStream(Box<ManifestFormat>),177	Yaml(usize),178	Json(usize),179	ToString,180	String,181}182183#[derive(Debug, Clone, Trace)]184#[force_tracking]185pub enum ArrValue {186	Lazy(Cc<Vec<LazyVal>>),187	Eager(Cc<Vec<Val>>),188	Extended(Box<(Self, Self)>),189}190impl ArrValue {191	pub fn new_eager() -> Self {192		Self::Eager(Cc::new(Vec::new()))193	}194195	pub fn len(&self) -> usize {196		match self {197			Self::Lazy(l) => l.len(),198			Self::Eager(e) => e.len(),199			Self::Extended(v) => v.0.len() + v.1.len(),200		}201	}202203	pub fn is_empty(&self) -> bool {204		self.len() == 0205	}206207	pub fn get(&self, index: usize) -> Result<Option<Val>> {208		match self {209			Self::Lazy(vec) => {210				if let Some(v) = vec.get(index) {211					Ok(Some(v.evaluate()?))212				} else {213					Ok(None)214				}215			}216			Self::Eager(vec) => Ok(vec.get(index).cloned()),217			Self::Extended(v) => {218				let a_len = v.0.len();219				if a_len > index {220					v.0.get(index)221				} else {222					v.1.get(index - a_len)223				}224			}225		}226	}227228	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {229		match self {230			Self::Lazy(vec) => vec.get(index).cloned(),231			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),232			Self::Extended(v) => {233				let a_len = v.0.len();234				if a_len > index {235					v.0.get_lazy(index)236				} else {237					v.1.get_lazy(index - a_len)238				}239			}240		}241	}242243	pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {244		Ok(match self {245			Self::Lazy(vec) => {246				let mut out = Vec::with_capacity(vec.len());247				for item in vec.iter() {248					out.push(item.evaluate()?);249				}250				Cc::new(out)251			}252			Self::Eager(vec) => vec.clone(),253			Self::Extended(_v) => {254				let mut out = Vec::with_capacity(self.len());255				for item in self.iter() {256					out.push(item?);257				}258				Cc::new(out)259			}260		})261	}262263	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {264		(0..self.len()).map(move |idx| match self {265			Self::Lazy(l) => l[idx].evaluate(),266			Self::Eager(e) => Ok(e[idx].clone()),267			Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),268		})269	}270271	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {272		(0..self.len()).map(move |idx| match self {273			Self::Lazy(l) => l[idx].clone(),274			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),275			Self::Extended(_) => self.get_lazy(idx).unwrap(),276		})277	}278279	pub fn reversed(self) -> Self {280		match self {281			Self::Lazy(vec) => {282				let mut out = (&vec as &Vec<_>).clone();283				out.reverse();284				Self::Lazy(Cc::new(out))285			}286			Self::Eager(vec) => {287				let mut out = (&vec as &Vec<_>).clone();288				out.reverse();289				Self::Eager(Cc::new(out))290			}291			Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),292		}293	}294295	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {296		let mut out = Vec::with_capacity(self.len());297298		for value in self.iter() {299			out.push(mapper(value?)?);300		}301302		Ok(Self::Eager(Cc::new(out)))303	}304305	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {306		let mut out = Vec::with_capacity(self.len());307308		for value in self.iter() {309			let value = value?;310			if filter(&value)? {311				out.push(value);312			}313		}314315		Ok(Self::Eager(Cc::new(out)))316	}317318	pub fn ptr_eq(a: &Self, b: &Self) -> bool {319		match (a, b) {320			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),321			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),322			_ => false,323		}324	}325}326327impl From<Vec<LazyVal>> for ArrValue {328	fn from(v: Vec<LazyVal>) -> Self {329		Self::Lazy(Cc::new(v))330	}331}332333impl From<Vec<Val>> for ArrValue {334	fn from(v: Vec<Val>) -> Self {335		Self::Eager(Cc::new(v))336	}337}338339pub enum IndexableVal {340	Str(IStr),341	Arr(ArrValue),342}343344#[derive(Debug, Clone, Trace)]345pub enum Val {346	Bool(bool),347	Null,348	Str(IStr),349	Num(f64),350	Arr(ArrValue),351	Obj(ObjValue),352	Func(FuncVal),353}354355impl Val {356	pub fn as_bool(&self) -> Option<bool> {357		match self {358			Val::Bool(v) => Some(*v),359			_ => None,360		}361	}362	pub fn as_null(&self) -> Option<()> {363		match self {364			Val::Null => Some(()),365			_ => None,366		}367	}368	pub fn as_str(&self) -> Option<IStr> {369		match self {370			Val::Str(s) => Some(s.clone()),371			_ => None,372		}373	}374	pub fn as_num(&self) -> Option<f64> {375		match self {376			Val::Num(n) => Some(*n),377			_ => None,378		}379	}380	pub fn as_arr(&self) -> Option<ArrValue> {381		match self {382			Val::Arr(a) => Some(a.clone()),383			_ => None,384		}385	}386	pub fn as_obj(&self) -> Option<ObjValue> {387		match self {388			Val::Obj(o) => Some(o.clone()),389			_ => None,390		}391	}392	pub fn as_func(&self) -> Option<FuncVal> {393		match self {394			Val::Func(f) => Some(f.clone()),395			_ => None,396		}397	}398399	/// Creates `Val::Num` after checking for numeric overflow.400	/// As numbers are `f64`, we can just check for their finity.401	pub fn new_checked_num(num: f64) -> Result<Self> {402		if num.is_finite() {403			Ok(Self::Num(num))404		} else {405			throw!(RuntimeError("overflow".into()))406		}407	}408409	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {410		Ok(match self {411			Val::Null => None,412			Val::Num(num) => Some(num),413			_ => throw!(TypeMismatch(414				context,415				vec![ValType::Null, ValType::Num],416				self.value_type()417			)),418		})419	}420	pub const fn value_type(&self) -> ValType {421		match self {422			Self::Str(..) => ValType::Str,423			Self::Num(..) => ValType::Num,424			Self::Arr(..) => ValType::Arr,425			Self::Obj(..) => ValType::Obj,426			Self::Bool(_) => ValType::Bool,427			Self::Null => ValType::Null,428			Self::Func(..) => ValType::Func,429		}430	}431432	pub fn to_string(&self) -> Result<IStr> {433		Ok(match self {434			Self::Bool(true) => "true".into(),435			Self::Bool(false) => "false".into(),436			Self::Null => "null".into(),437			Self::Str(s) => s.clone(),438			v => manifest_json_ex(439				v,440				&ManifestJsonOptions {441					padding: "",442					mtype: ManifestType::ToString,443					newline: "\n",444					key_val_sep: ": ",445				},446			)?447			.into(),448		})449	}450451	/// Expects value to be object, outputs (key, manifested value) pairs452	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {453		let obj = match self {454			Self::Obj(obj) => obj,455			_ => throw!(MultiManifestOutputIsNotAObject),456		};457		let keys = obj.fields();458		let mut out = Vec::with_capacity(keys.len());459		for key in keys {460			let value = obj461				.get(key.clone())?462				.expect("item in object")463				.manifest(ty)?;464			out.push((key, value));465		}466		Ok(out)467	}468469	/// Expects value to be array, outputs manifested values470	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {471		let arr = match self {472			Self::Arr(a) => a,473			_ => throw!(StreamManifestOutputIsNotAArray),474		};475		let mut out = Vec::with_capacity(arr.len());476		for i in arr.iter() {477			out.push(i?.manifest(ty)?);478		}479		Ok(out)480	}481482	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {483		Ok(match ty {484			ManifestFormat::YamlStream(format) => {485				let arr = match self {486					Self::Arr(a) => a,487					_ => throw!(StreamManifestOutputIsNotAArray),488				};489				let mut out = String::new();490491				match format as &ManifestFormat {492					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),493					ManifestFormat::String => throw!(StreamManifestCannotNestString),494					_ => {}495				};496497				if !arr.is_empty() {498					for v in arr.iter() {499						out.push_str("---\n");500						out.push_str(&v?.manifest(format)?);501						out.push('\n');502					}503					out.push_str("...");504				}505506				out.into()507			}508			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,509			ManifestFormat::Json(padding) => self.to_json(*padding)?,510			ManifestFormat::ToString => self.to_string()?,511			ManifestFormat::String => match self {512				Self::Str(s) => s.clone(),513				_ => throw!(StringManifestOutputIsNotAString),514			},515		})516	}517518	/// For manifestification519	pub fn to_json(&self, padding: usize) -> Result<IStr> {520		manifest_json_ex(521			self,522			&ManifestJsonOptions {523				padding: &" ".repeat(padding),524				mtype: if padding == 0 {525					ManifestType::Minify526				} else {527					ManifestType::Manifest528				},529				newline: "\n",530				key_val_sep: ": ",531			},532		)533		.map(|s| s.into())534	}535536	/// Calls `std.manifestJson`537	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {538		manifest_json_ex(539			self,540			&ManifestJsonOptions {541				padding: &" ".repeat(padding),542				mtype: ManifestType::Std,543				newline: "\n",544				key_val_sep: ": ",545			},546		)547		.map(|s| s.into())548	}549550	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {551		let padding = &" ".repeat(padding);552		manifest_yaml_ex(553			self,554			&ManifestYamlOptions {555				padding,556				arr_element_padding: padding,557				quote_keys: false,558			},559		)560		.map(|s| s.into())561	}562	pub fn into_indexable(self) -> Result<IndexableVal> {563		Ok(match self {564			Val::Str(s) => IndexableVal::Str(s),565			Val::Arr(arr) => IndexableVal::Arr(arr),566			_ => throw!(ValueIsNotIndexable(self.value_type())),567		})568	}569}570571const fn is_function_like(val: &Val) -> bool {572	matches!(val, Val::Func(_))573}574575/// Native implementation of `std.primitiveEquals`576pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {577	Ok(match (val_a, val_b) {578		(Val::Bool(a), Val::Bool(b)) => a == b,579		(Val::Null, Val::Null) => true,580		(Val::Str(a), Val::Str(b)) => a == b,581		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,582		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(583			"primitiveEquals operates on primitive types, got array".into(),584		)),585		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(586			"primitiveEquals operates on primitive types, got object".into(),587		)),588		(a, b) if is_function_like(a) && is_function_like(b) => {589			throw!(RuntimeError("cannot test equality of functions".into()))590		}591		(_, _) => false,592	})593}594595/// Native implementation of `std.equals`596pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {597	if val_a.value_type() != val_b.value_type() {598		return Ok(false);599	}600	match (val_a, val_b) {601		(Val::Arr(a), Val::Arr(b)) => {602			if ArrValue::ptr_eq(a, b) {603				return Ok(true);604			}605			if a.len() != b.len() {606				return Ok(false);607			}608			for (a, b) in a.iter().zip(b.iter()) {609				if !equals(&a?, &b?)? {610					return Ok(false);611				}612			}613			Ok(true)614		}615		(Val::Obj(a), Val::Obj(b)) => {616			if ObjValue::ptr_eq(a, b) {617				return Ok(true);618			}619			let fields = a.fields();620			if fields != b.fields() {621				return Ok(false);622			}623			for field in fields {624				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {625					return Ok(false);626				}627			}628			Ok(true)629		}630		(a, b) => Ok(primitive_equals(a, b)?),631	}632}
after · crates/jrsonnet-evaluator/src/val.rs
1use crate::{2	builtin::manifest::{3		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,4	},5	cc_ptr_eq,6	error::{Error::*, LocError},7	evaluate,8	function::{9		parse_default_function_call, parse_function_call, ArgsLike, Builtin, CallLocation,10		StaticBuiltin,11	},12	gc::TraceBox,13	throw, Context, ObjValue, Result,14};15use gcmodule::{Cc, Trace};16use jrsonnet_interner::IStr;17use jrsonnet_parser::{LocExpr, ParamsDesc};18use jrsonnet_types::ValType;19use std::{cell::RefCell, fmt::Debug, rc::Rc};2021pub trait LazyValValue: Trace {22	fn get(self: Box<Self>) -> Result<Val>;23}2425#[derive(Trace)]26enum LazyValInternals {27	Computed(Val),28	Errored(LocError),29	Waiting(TraceBox<dyn LazyValValue>),30	Pending,31}3233#[derive(Clone, Trace)]34pub struct LazyVal(Cc<RefCell<LazyValInternals>>);35impl LazyVal {36	pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {37		Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))38	}39	pub fn new_resolved(val: Val) -> Self {40		Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))41	}42	pub fn force(&self) -> Result<()> {43		self.evaluate()?;44		Ok(())45	}46	pub fn evaluate(&self) -> Result<Val> {47		match &*self.0.borrow() {48			LazyValInternals::Computed(v) => return Ok(v.clone()),49			LazyValInternals::Errored(e) => return Err(e.clone()),50			LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),51			_ => (),52		};53		let value = if let LazyValInternals::Waiting(value) =54			std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)55		{56			value57		} else {58			unreachable!()59		};60		let new_value = match value.0.get() {61			Ok(v) => v,62			Err(e) => {63				*self.0.borrow_mut() = LazyValInternals::Errored(e.clone());64				return Err(e);65			}66		};67		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());68		Ok(new_value)69	}70}7172impl Debug for LazyVal {73	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {74		write!(f, "Lazy")75	}76}77impl PartialEq for LazyVal {78	fn eq(&self, other: &Self) -> bool {79		cc_ptr_eq(&self.0, &other.0)80	}81}8283#[derive(Debug, PartialEq, Trace)]84pub struct FuncDesc {85	pub name: IStr,86	pub ctx: Context,87	pub params: ParamsDesc,88	pub body: LocExpr,89}90impl FuncDesc {91	/// Create body context, but fill arguments without defaults with lazy error92	pub fn default_body_context(&self) -> Context {93		parse_default_function_call(self.ctx.clone(), &self.params)94	}9596	/// Create context, with which body code will run97	pub fn call_body_context(98		&self,99		call_ctx: Context,100		args: &dyn ArgsLike,101		tailstrict: bool,102	) -> Result<Context> {103		parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)104	}105}106107#[derive(Trace, Clone)]108pub enum FuncVal {109	/// Plain function implemented in jsonnet110	Normal(Cc<FuncDesc>),111	/// Standard library function112	StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),113	/// User-provided function114	Builtin(Cc<TraceBox<dyn Builtin>>),115}116117impl Debug for FuncVal {118	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {119		match self {120			Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),121			Self::StaticBuiltin(arg0) => {122				f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()123			}124			Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),125		}126	}127}128129impl FuncVal {130	pub fn args_len(&self) -> usize {131		match self {132			Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),133			Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),134			Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),135		}136	}137	pub fn name(&self) -> IStr {138		match self {139			Self::Normal(normal) => normal.name.clone(),140			Self::StaticBuiltin(builtin) => builtin.name().into(),141			Self::Builtin(builtin) => builtin.name().into(),142		}143	}144	pub fn evaluate(145		&self,146		call_ctx: Context,147		loc: CallLocation,148		args: &dyn ArgsLike,149		tailstrict: bool,150	) -> Result<Val> {151		match self {152			Self::Normal(func) => {153				let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;154				evaluate(body_ctx, &func.body)155			}156			Self::StaticBuiltin(b) => b.call(call_ctx, loc, args),157			Self::Builtin(b) => b.call(call_ctx, loc, args),158		}159	}160	pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {161		self.evaluate(Context::default(), CallLocation::native(), args, true)162	}163}164165#[derive(Clone)]166pub enum ManifestFormat {167	YamlStream(Box<ManifestFormat>),168	Yaml(usize),169	Json(usize),170	ToString,171	String,172}173174#[derive(Debug, Clone, Trace)]175#[force_tracking]176pub enum ArrValue {177	Lazy(Cc<Vec<LazyVal>>),178	Eager(Cc<Vec<Val>>),179	Extended(Box<(Self, Self)>),180}181impl ArrValue {182	pub fn new_eager() -> Self {183		Self::Eager(Cc::new(Vec::new()))184	}185186	pub fn len(&self) -> usize {187		match self {188			Self::Lazy(l) => l.len(),189			Self::Eager(e) => e.len(),190			Self::Extended(v) => v.0.len() + v.1.len(),191		}192	}193194	pub fn is_empty(&self) -> bool {195		self.len() == 0196	}197198	pub fn get(&self, index: usize) -> Result<Option<Val>> {199		match self {200			Self::Lazy(vec) => {201				if let Some(v) = vec.get(index) {202					Ok(Some(v.evaluate()?))203				} else {204					Ok(None)205				}206			}207			Self::Eager(vec) => Ok(vec.get(index).cloned()),208			Self::Extended(v) => {209				let a_len = v.0.len();210				if a_len > index {211					v.0.get(index)212				} else {213					v.1.get(index - a_len)214				}215			}216		}217	}218219	pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {220		match self {221			Self::Lazy(vec) => vec.get(index).cloned(),222			Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),223			Self::Extended(v) => {224				let a_len = v.0.len();225				if a_len > index {226					v.0.get_lazy(index)227				} else {228					v.1.get_lazy(index - a_len)229				}230			}231		}232	}233234	pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {235		Ok(match self {236			Self::Lazy(vec) => {237				let mut out = Vec::with_capacity(vec.len());238				for item in vec.iter() {239					out.push(item.evaluate()?);240				}241				Cc::new(out)242			}243			Self::Eager(vec) => vec.clone(),244			Self::Extended(_v) => {245				let mut out = Vec::with_capacity(self.len());246				for item in self.iter() {247					out.push(item?);248				}249				Cc::new(out)250			}251		})252	}253254	pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {255		(0..self.len()).map(move |idx| match self {256			Self::Lazy(l) => l[idx].evaluate(),257			Self::Eager(e) => Ok(e[idx].clone()),258			Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),259		})260	}261262	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {263		(0..self.len()).map(move |idx| match self {264			Self::Lazy(l) => l[idx].clone(),265			Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),266			Self::Extended(_) => self.get_lazy(idx).unwrap(),267		})268	}269270	pub fn reversed(self) -> Self {271		match self {272			Self::Lazy(vec) => {273				let mut out = (&vec as &Vec<_>).clone();274				out.reverse();275				Self::Lazy(Cc::new(out))276			}277			Self::Eager(vec) => {278				let mut out = (&vec as &Vec<_>).clone();279				out.reverse();280				Self::Eager(Cc::new(out))281			}282			Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),283		}284	}285286	pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {287		let mut out = Vec::with_capacity(self.len());288289		for value in self.iter() {290			out.push(mapper(value?)?);291		}292293		Ok(Self::Eager(Cc::new(out)))294	}295296	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {297		let mut out = Vec::with_capacity(self.len());298299		for value in self.iter() {300			let value = value?;301			if filter(&value)? {302				out.push(value);303			}304		}305306		Ok(Self::Eager(Cc::new(out)))307	}308309	pub fn ptr_eq(a: &Self, b: &Self) -> bool {310		match (a, b) {311			(Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),312			(Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),313			_ => false,314		}315	}316}317318impl From<Vec<LazyVal>> for ArrValue {319	fn from(v: Vec<LazyVal>) -> Self {320		Self::Lazy(Cc::new(v))321	}322}323324impl From<Vec<Val>> for ArrValue {325	fn from(v: Vec<Val>) -> Self {326		Self::Eager(Cc::new(v))327	}328}329330pub enum IndexableVal {331	Str(IStr),332	Arr(ArrValue),333}334335#[derive(Debug, Clone, Trace)]336pub enum Val {337	Bool(bool),338	Null,339	Str(IStr),340	Num(f64),341	Arr(ArrValue),342	Obj(ObjValue),343	Func(FuncVal),344}345346impl Val {347	pub const fn as_bool(&self) -> Option<bool> {348		match self {349			Val::Bool(v) => Some(*v),350			_ => None,351		}352	}353	pub const fn as_null(&self) -> Option<()> {354		match self {355			Val::Null => Some(()),356			_ => None,357		}358	}359	pub fn as_str(&self) -> Option<IStr> {360		match self {361			Val::Str(s) => Some(s.clone()),362			_ => None,363		}364	}365	pub const fn as_num(&self) -> Option<f64> {366		match self {367			Val::Num(n) => Some(*n),368			_ => None,369		}370	}371	pub fn as_arr(&self) -> Option<ArrValue> {372		match self {373			Val::Arr(a) => Some(a.clone()),374			_ => None,375		}376	}377	pub fn as_obj(&self) -> Option<ObjValue> {378		match self {379			Val::Obj(o) => Some(o.clone()),380			_ => None,381		}382	}383	pub fn as_func(&self) -> Option<FuncVal> {384		match self {385			Val::Func(f) => Some(f.clone()),386			_ => None,387		}388	}389390	/// Creates `Val::Num` after checking for numeric overflow.391	/// As numbers are `f64`, we can just check for their finity.392	pub fn new_checked_num(num: f64) -> Result<Self> {393		if num.is_finite() {394			Ok(Self::Num(num))395		} else {396			throw!(RuntimeError("overflow".into()))397		}398	}399400	pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {401		Ok(match self {402			Val::Null => None,403			Val::Num(num) => Some(num),404			_ => throw!(TypeMismatch(405				context,406				vec![ValType::Null, ValType::Num],407				self.value_type()408			)),409		})410	}411	pub const fn value_type(&self) -> ValType {412		match self {413			Self::Str(..) => ValType::Str,414			Self::Num(..) => ValType::Num,415			Self::Arr(..) => ValType::Arr,416			Self::Obj(..) => ValType::Obj,417			Self::Bool(_) => ValType::Bool,418			Self::Null => ValType::Null,419			Self::Func(..) => ValType::Func,420		}421	}422423	pub fn to_string(&self) -> Result<IStr> {424		Ok(match self {425			Self::Bool(true) => "true".into(),426			Self::Bool(false) => "false".into(),427			Self::Null => "null".into(),428			Self::Str(s) => s.clone(),429			v => manifest_json_ex(430				v,431				&ManifestJsonOptions {432					padding: "",433					mtype: ManifestType::ToString,434					newline: "\n",435					key_val_sep: ": ",436				},437			)?438			.into(),439		})440	}441442	/// Expects value to be object, outputs (key, manifested value) pairs443	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {444		let obj = match self {445			Self::Obj(obj) => obj,446			_ => throw!(MultiManifestOutputIsNotAObject),447		};448		let keys = obj.fields();449		let mut out = Vec::with_capacity(keys.len());450		for key in keys {451			let value = obj452				.get(key.clone())?453				.expect("item in object")454				.manifest(ty)?;455			out.push((key, value));456		}457		Ok(out)458	}459460	/// Expects value to be array, outputs manifested values461	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {462		let arr = match self {463			Self::Arr(a) => a,464			_ => throw!(StreamManifestOutputIsNotAArray),465		};466		let mut out = Vec::with_capacity(arr.len());467		for i in arr.iter() {468			out.push(i?.manifest(ty)?);469		}470		Ok(out)471	}472473	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {474		Ok(match ty {475			ManifestFormat::YamlStream(format) => {476				let arr = match self {477					Self::Arr(a) => a,478					_ => throw!(StreamManifestOutputIsNotAArray),479				};480				let mut out = String::new();481482				match format as &ManifestFormat {483					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),484					ManifestFormat::String => throw!(StreamManifestCannotNestString),485					_ => {}486				};487488				if !arr.is_empty() {489					for v in arr.iter() {490						out.push_str("---\n");491						out.push_str(&v?.manifest(format)?);492						out.push('\n');493					}494					out.push_str("...");495				}496497				out.into()498			}499			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,500			ManifestFormat::Json(padding) => self.to_json(*padding)?,501			ManifestFormat::ToString => self.to_string()?,502			ManifestFormat::String => match self {503				Self::Str(s) => s.clone(),504				_ => throw!(StringManifestOutputIsNotAString),505			},506		})507	}508509	/// For manifestification510	pub fn to_json(&self, padding: usize) -> Result<IStr> {511		manifest_json_ex(512			self,513			&ManifestJsonOptions {514				padding: &" ".repeat(padding),515				mtype: if padding == 0 {516					ManifestType::Minify517				} else {518					ManifestType::Manifest519				},520				newline: "\n",521				key_val_sep: ": ",522			},523		)524		.map(|s| s.into())525	}526527	/// Calls `std.manifestJson`528	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {529		manifest_json_ex(530			self,531			&ManifestJsonOptions {532				padding: &" ".repeat(padding),533				mtype: ManifestType::Std,534				newline: "\n",535				key_val_sep: ": ",536			},537		)538		.map(|s| s.into())539	}540541	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {542		let padding = &" ".repeat(padding);543		manifest_yaml_ex(544			self,545			&ManifestYamlOptions {546				padding,547				arr_element_padding: padding,548				quote_keys: false,549			},550		)551		.map(|s| s.into())552	}553	pub fn into_indexable(self) -> Result<IndexableVal> {554		Ok(match self {555			Val::Str(s) => IndexableVal::Str(s),556			Val::Arr(arr) => IndexableVal::Arr(arr),557			_ => throw!(ValueIsNotIndexable(self.value_type())),558		})559	}560}561562const fn is_function_like(val: &Val) -> bool {563	matches!(val, Val::Func(_))564}565566/// Native implementation of `std.primitiveEquals`567pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {568	Ok(match (val_a, val_b) {569		(Val::Bool(a), Val::Bool(b)) => a == b,570		(Val::Null, Val::Null) => true,571		(Val::Str(a), Val::Str(b)) => a == b,572		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,573		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(574			"primitiveEquals operates on primitive types, got array".into(),575		)),576		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(577			"primitiveEquals operates on primitive types, got object".into(),578		)),579		(a, b) if is_function_like(a) && is_function_like(b) => {580			throw!(RuntimeError("cannot test equality of functions".into()))581		}582		(_, _) => false,583	})584}585586/// Native implementation of `std.equals`587pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {588	if val_a.value_type() != val_b.value_type() {589		return Ok(false);590	}591	match (val_a, val_b) {592		(Val::Arr(a), Val::Arr(b)) => {593			if ArrValue::ptr_eq(a, b) {594				return Ok(true);595			}596			if a.len() != b.len() {597				return Ok(false);598			}599			for (a, b) in a.iter().zip(b.iter()) {600				if !equals(&a?, &b?)? {601					return Ok(false);602				}603			}604			Ok(true)605		}606		(Val::Obj(a), Val::Obj(b)) => {607			if ObjValue::ptr_eq(a, b) {608				return Ok(true);609			}610			let fields = a.fields();611			if fields != b.fields() {612				return Ok(false);613			}614			for field in fields {615				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {616					return Ok(false);617				}618			}619			Ok(true)620		}621		(a, b) => Ok(primitive_equals(a, b)?),622	}623}
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -35,7 +35,7 @@
 
 fn path_is(path: &Path, needed: &str) -> bool {
 	path.leading_colon.is_none()
-		&& path.segments.len() >= 1
+		&& !path.segments.is_empty()
 		&& path.segments.iter().last().unwrap().ident == needed
 }
 
@@ -119,7 +119,7 @@
 
 enum ArgInfo {
 	Normal {
-		ty: Type,
+		ty: Box<Type>,
 		is_option: bool,
 		name: String,
 		// ident: Ident,
@@ -147,27 +147,27 @@
 				))
 			}
 		};
-		let ty = &typed.ty as &Type;
-		if type_is_path(&ty, "CallLocation").is_some() {
+		let ty = &typed.ty;
+		if type_is_path(ty, "CallLocation").is_some() {
 			return Ok(Self::Location);
-		} else if type_is_path(&ty, "Self").is_some() {
+		} else if type_is_path(ty, "Self").is_some() {
 			return Ok(Self::This);
-		} else if type_is_path(&ty, "LazyVal").is_some() {
+		} else if type_is_path(ty, "LazyVal").is_some() {
 			return Ok(Self::Lazy {
 				is_option: false,
 				name: ident.to_string(),
 			});
 		}
 
-		let (is_option, ty) = if let Some(ty) = extract_type_from_option(&ty)? {
-			if type_is_path(&ty, "LazyVal").is_some() {
+		let (is_option, ty) = if let Some(ty) = extract_type_from_option(ty)? {
+			if type_is_path(ty, "LazyVal").is_some() {
 				return Ok(Self::Lazy {
 					is_option: true,
 					name: ident.to_string(),
 				});
 			}
 
-			(true, ty.clone())
+			(true, Box::new(ty.clone()))
 		} else {
 			(false, ty.clone())
 		};
@@ -210,7 +210,7 @@
 		.sig
 		.inputs
 		.iter()
-		.map(|a| ArgInfo::parse(a))
+		.map(ArgInfo::parse)
 		.collect::<Result<Vec<_>>>()?;
 
 	let params_desc = args.iter().flat_map(|a| match a {
@@ -380,8 +380,7 @@
 struct TypedField<'f>(&'f syn::Field, TypedAttr);
 impl<'f> TypedField<'f> {
 	fn try_new(field: &'f syn::Field) -> Result<Self> {
-		let attr =
-			parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_else(Default::default);
+		let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();
 		if field.ident.is_none() {
 			return Err(Error::new(
 				field.span(),
@@ -468,17 +467,15 @@
 					out.member(#name.into()).value(self.#ident.try_into()?);
 				}
 			}
+		} else if self.is_option() {
+			quote! {
+				if let Some(value) = self.#ident {
+					value.serialize(out)?;
+				}
+			}
 		} else {
-			if self.is_option() {
-				quote! {
-					if let Some(value) = self.#ident {
-						value.serialize(out)?;
-					}
-				}
-			} else {
-				quote! {
-					self.#ident.serialize(out)?;
-				}
+			quote! {
+				self.#ident.serialize(out)?;
 			}
 		}
 	}