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

difftreelog

doc: review issues

Yaroslav Bolyukin2022-10-15parent: #70f3783.patch.diff
in: master

19 files changed

modifiedbindings/jsonnet/src/import.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -93,7 +93,7 @@
 
 /// # Safety
 ///
-/// Caller should pass correct callback function
+/// It should be safe to call `cb` using valid values with passed `ctx`
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_import_callback(
 	vm: &State,
@@ -109,10 +109,10 @@
 
 /// # Safety
 ///
-/// Caller should pass correct path: it should contain correct utf-8, and be \0-terminated
+/// `path` should be a NUL-terminated string
 #[no_mangle]
-pub unsafe extern "C" fn jsonnet_jpath_add(vm: &State, v: *const c_char) {
-	let cstr = CStr::from_ptr(v);
+pub unsafe extern "C" fn jsonnet_jpath_add(vm: &State, path: *const c_char) {
+	let cstr = CStr::from_ptr(path);
 	let path = PathBuf::from(cstr.to_str().unwrap());
 	let any_resolver = vm.import_resolver();
 	let resolver = any_resolver
modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -41,17 +41,10 @@
 		let str = OsStr::from_bytes(input.to_bytes());
 		Cow::Borrowed(Path::new(str))
 	}
-	#[cfg(target_family = "windows")]
+	#[cfg(not(target_family = "unix"))]
 	{
-		use std::os::windows::ffi::OsStringExt;
-		let str = input.to_str().expect("input is not utf8");
-		let wide = str.encode_utf16().collect::<Vec<_>>();
-		let wide = OsString::from_wide(&wide);
-		Cow::Owned(PathBuf::new(wide))
-	}
-	#[cfg(not(any(target_family = "unix", target_family = "windows")))]
-	{
-		compile_error!("unsupported os")
+		let string = input.to_str().expect("bad utf-8");
+		Cow::Borrowed(string.as_ref())
 	}
 }
 
@@ -62,9 +55,11 @@
 		let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");
 		Cow::Owned(str)
 	}
-	#[cfg(not(any(target_family = "unix", target_family = "windows")))]
+	#[cfg(not(target_family = "unix"))]
 	{
-		compile_error!("unsupported os")
+		let str = input.as_os_str().to_str().expect("bad utf-8");
+		let cstr = CString::new(str).expect("input has NUL inside");
+		Cow::Owned(cstr)
 	}
 }
 
@@ -169,7 +164,7 @@
 ///
 /// # Safety
 ///
-/// `filename` should be a \0-terminated string
+/// `filename` should be a NUL-terminated string
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_evaluate_file(
 	vm: &State,
@@ -200,7 +195,7 @@
 ///
 /// # Safety
 ///
-/// `filename`, `snippet` should be a \0-terminated strings
+/// `filename`, `snippet` should be a NUL-terminated strings
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_evaluate_snippet(
 	vm: &State,
modifiedbindings/jsonnet/src/native.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -65,9 +65,9 @@
 /// # Safety
 ///
 /// `vm` should be a vm allocated by `jsonnet_make`
-/// `cb` should be a correct function pointer
-/// `raw_params` should point to a NULL-terminated string array
-/// `name`, `raw_params` elements should be a \0-terminated strings
+/// `name` should be a NUL-terminated string
+/// `cb` should be a function pointer
+/// `raw_params` should point to a NULL-terminated array of NUL-terminated strings
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_native_callback(
 	vm: &State,
modifiedbindings/jsonnet/src/val_make.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -12,7 +12,7 @@
 ///
 /// # Safety
 ///
-/// `v` should be a \0-terminated string
+/// `v` should be a NUL-terminated string
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_json_make_string(_vm: &State, val: *const c_char) -> *mut Val {
 	let val = CStr::from_ptr(val);
modifiedbindings/jsonnet/src/val_modify.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -11,8 +11,8 @@
 ///
 /// # Safety
 ///
-/// `arr` should be correct pointer to array value allocated by make_array, or returned by other library call
-/// `val` should be correct pointer to value allocated using this library
+/// `arr` should be a pointer to array value allocated by make_array, or returned by other library call
+/// `val` should be a pointer to value allocated using this library
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_json_array_append(_vm: &State, arr: &mut Val, val: &Val) {
 	match arr {
@@ -35,8 +35,8 @@
 ///
 /// # Safety
 ///
-/// `obj` should be a valid pointer to object value allocated by `make_object`, or returned by other library call
-/// `name` should be \0-terminated string
+/// `obj` should be a pointer to object value allocated by `make_object`, or returned by other library call
+/// `name` should be NUL-terminated string
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_json_object_append(
 	_vm: &State,
modifiedbindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -4,13 +4,13 @@
 
 use jrsonnet_evaluator::State;
 
-/// Bind a Jsonnet external var to the given string.
+/// Binds a Jsonnet external variable to the given string.
 ///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
 ///
 /// # Safety
 ///
-/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
+/// `name`, `code` should be a NUL-terminated strings
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_ext_var(vm: &State, name: *const c_char, value: *const c_char) {
 	let name = CStr::from_ptr(name);
@@ -27,13 +27,13 @@
 		)
 }
 
-/// Bind a Jsonnet external var to the given code.
+/// Binds a Jsonnet external variable to the given code.
 ///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
 ///
 /// # Safety
 ///
-/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
+/// `name`, `code` should be a NUL-terminated strings
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_ext_code(vm: &State, name: *const c_char, code: *const c_char) {
 	let name = CStr::from_ptr(name);
@@ -51,13 +51,13 @@
 		.expect("can't parse ext code")
 }
 
-/// Bind a string top-level argument for a top-level parameter.
+/// Binds a top-level string argument for a top-level parameter.
 ///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
 ///
 /// # Safety
 ///
-/// Caller should pass correct pointers as `name` and `value`, they need to be \0-terminated strings
+/// `name`, `value` should be a NUL-terminated strings
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_tla_var(vm: &State, name: *const c_char, value: *const c_char) {
 	let name = CStr::from_ptr(name);
@@ -68,13 +68,13 @@
 	)
 }
 
-/// Bind a code top-level argument for a top-level parameter.
+/// Binds a top-level code argument for a top-level parameter.
 ///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
 ///
 /// # Safety
 ///
-/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
+/// `name`, `code` should be a NUL-terminated strings
 #[no_mangle]
 pub unsafe extern "C" fn jsonnet_tla_code(vm: &State, name: *const c_char, code: *const c_char) {
 	let name = CStr::from_ptr(name);
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -20,6 +20,9 @@
 	}
 }
 
+/// Context keeps information about current lexical code location
+///
+/// This information includes local variables, top-level object (`$`), current object (`this`), and super object (`super`)
 #[derive(Debug, Clone, Trace)]
 pub struct Context(Cc<ContextInternals>);
 impl Context {
@@ -160,8 +163,11 @@
 			extend: Some(parent),
 		}
 	}
+	/// # Panics
+	/// If `name` is already bound
 	pub fn bind(&mut self, name: IStr, value: Thunk<Val>) -> &mut Self {
-		self.bindings.insert(name, value);
+		let old = self.bindings.insert(name, value);
+		assert!(old.is_none(), "variable bound twice in single context call");
 		self
 	}
 	pub fn build(self) -> Context {
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -67,7 +67,10 @@
 
 type FunctionSignature = Vec<(Option<IStr>, bool)>;
 
+/// Possible errors
+#[allow(missing_docs)]
 #[derive(Error, Debug, Clone, Trace)]
+#[non_exhaustive]
 pub enum Error {
 	#[error("intrinsic not found: {0}")]
 	IntrinsicNotFound(IStr),
@@ -217,9 +220,13 @@
 	}
 }
 
+/// Single stack trace frame
 #[derive(Clone, Debug, Trace)]
 pub struct StackTraceElement {
+	/// Source of this frame
+	/// Some frames only act as description, without attached source
 	pub location: Option<ExprLocation>,
+	/// Frame description
 	pub desc: String,
 }
 #[derive(Debug, Clone, Trace)]
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -269,9 +269,7 @@
 		}
 	}
 	let this = builder.build();
-	let _ctx = ctx
-		.extend(GcHashMap::new(), None, None, Some(this.clone()))
-		.into_future(fctx);
+	fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));
 	Ok(this)
 }
 
@@ -356,7 +354,7 @@
 	ctx: Context,
 	value: &LocExpr,
 	args: &ArgsDesc,
-	loc: CallLocation,
+	loc: CallLocation<'_>,
 	tailstrict: bool,
 ) -> Result<Val> {
 	let value = evaluate(s.clone(), ctx.clone(), value)?;
@@ -602,7 +600,7 @@
 		}
 		Slice(value, desc) => {
 			fn parse_idx<T: Typed>(
-				loc: CallLocation,
+				loc: CallLocation<'_>,
 				s: State,
 				ctx: &Context,
 				expr: &Option<LocExpr>,
modifiedcrates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -24,7 +24,13 @@
 	/// Parameter names for named calls
 	fn params(&self) -> &[BuiltinParam];
 	/// Call the builtin
-	fn call(&self, s: State, ctx: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val>;
+	fn call(
+		&self,
+		s: State,
+		ctx: Context,
+		loc: CallLocation<'_>,
+		args: &dyn ArgsLike,
+	) -> Result<Val>;
 }
 
 pub trait StaticBuiltin: Builtin + Send + Sync
@@ -70,7 +76,13 @@
 		&self.params
 	}
 
-	fn call(&self, s: State, ctx: Context, _loc: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
+	fn call(
+		&self,
+		s: State,
+		ctx: Context,
+		_loc: CallLocation<'_>,
+		args: &dyn ArgsLike,
+	) -> Result<Val> {
 		let args = parse_builtin_call(s.clone(), ctx, &self.params, args, true)?;
 		let args = args
 			.into_iter()
modifiedcrates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -18,43 +18,50 @@
 pub mod native;
 pub mod parse;
 
+/// Function callsite location.
+/// Either from other jsonnet code, specified by expression location, or from native (without location).
 #[derive(Clone, Copy)]
 pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);
 impl<'l> CallLocation<'l> {
+	/// Construct new location for calls coming from specified jsonnet expression location.
 	pub const fn new(loc: &'l ExprLocation) -> Self {
 		Self(Some(loc))
 	}
 }
 impl CallLocation<'static> {
+	/// Construct new location for calls coming from native code.
 	pub const fn native() -> Self {
 		Self(None)
 	}
 }
 
-/// Function implemented in jsonnet
+/// Represents Jsonnet function defined in code.
 #[derive(Debug, PartialEq, Trace)]
 pub struct FuncDesc {
-	/// In expressions like
+	/// # Example
+	///
+	/// In expressions like this, deducted to `a`, unspecified otherwise.
 	/// ```jsonnet
 	/// local a = function() ...
 	/// local a() ...
 	/// { a: function() ... }
 	/// { a() = ... }
 	/// ```
-	///
-	/// Deducted to `a`, unspecified otherwise
 	pub name: IStr,
-	/// Context, in which this function was evaluated
+	/// Context, in which this function was evaluated.
 	///
-	/// I.e in
+	/// # Example
+	/// In
 	/// ```jsonnet
 	/// local a = 2;
 	/// function() ...
 	/// ```
-	/// context will contain `a`
+	/// context will contain `a`.
 	pub ctx: Context,
 
+	/// Function parameter definition
 	pub params: ParamsDesc,
+	/// Function body
 	pub body: LocExpr,
 }
 impl FuncDesc {
@@ -82,17 +89,17 @@
 	}
 }
 
-/// Any possible function value, including plain functions and user-provided builtins
+/// Represents a Jsonnet function value, including plain functions and user-provided builtins.
 #[allow(clippy::module_name_repetitions)]
 #[derive(Trace, Clone)]
 pub enum FuncVal {
-	/// std.id
+	/// Identity function, kept this way for comparsions.
 	Id,
-	/// Plain function implemented in jsonnet
+	/// Plain function implemented in jsonnet.
 	Normal(Cc<FuncDesc>),
-	/// Standard library function
+	/// Standard library function.
 	StaticBuiltin(#[trace(skip)] &'static dyn StaticBuiltin),
-	/// User-provided function
+	/// User-provided function.
 	Builtin(Cc<TraceBox<dyn Builtin>>),
 }
 
@@ -110,9 +117,7 @@
 }
 
 impl FuncVal {
-	pub fn into_native<D: NativeDesc>(self) -> D::Value {
-		D::into_native(self)
-	}
+	/// Amount of non-default required arguments
 	pub fn params_len(&self) -> usize {
 		match self {
 			Self::Id => 1,
@@ -121,6 +126,7 @@
 			Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),
 		}
 	}
+	/// Function name, as defined in code.
 	pub fn name(&self) -> IStr {
 		match self {
 			Self::Id => "id".into(),
@@ -129,11 +135,14 @@
 			Self::Builtin(builtin) => builtin.name().into(),
 		}
 	}
+	/// Call function using arguments evaluated in specified `call_ctx` [`Context`].
+	///
+	/// If `tailstrict` is specified - then arguments will be evaluated before being passed to function body.
 	pub fn evaluate(
 		&self,
 		s: State,
 		call_ctx: Context,
-		loc: CallLocation,
+		loc: CallLocation<'_>,
 		args: &dyn ArgsLike,
 		tailstrict: bool,
 	) -> Result<Val> {
@@ -156,13 +165,22 @@
 			Self::Builtin(b) => b.call(s, call_ctx, loc, args),
 		}
 	}
+	/// Helper method, which calls [`Self::evaluate`] with sensible defaults for native code.
 	pub fn evaluate_simple(&self, s: State, args: &dyn ArgsLike) -> Result<Val> {
 		self.evaluate(s, Context::default(), CallLocation::native(), args, true)
 	}
+	/// Convert jsonnet function to plain `Fn` value.
+	pub fn into_native<D: NativeDesc>(self) -> D::Value {
+		D::into_native(self)
+	}
 
+	/// Is this function an indentity function.
+	///
+	/// Currently only works for builtin `std.id`, aka `Self::Id` value, `function(x) x` defined by jsonnet will not count as identity.
 	pub const fn is_identity(&self) -> bool {
 		matches!(self, Self::Id)
 	}
+	/// Identity function value.
 	pub const fn identity() -> Self {
 		Self::Id
 	}
modifiedcrates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -22,7 +22,7 @@
 }
 
 impl<T: ?Sized + Trace> Trace for TraceBox<T> {
-	fn trace(&self, tracer: &mut Tracer) {
+	fn trace(&self, tracer: &mut Tracer<'_>) {
 		self.0.trace(tracer);
 	}
 
@@ -92,7 +92,7 @@
 where
 	V: Trace,
 {
-	fn trace(&self, tracer: &mut jrsonnet_gcmodule::Tracer) {
+	fn trace(&self, tracer: &mut Tracer<'_>) {
 		for v in &self.0 {
 			v.trace(tracer);
 		}
@@ -133,7 +133,7 @@
 	K: Trace,
 	V: Trace,
 {
-	fn trace(&self, tracer: &mut jrsonnet_gcmodule::Tracer) {
+	fn trace(&self, tracer: &mut Tracer<'_>) {
 		for (k, v) in &self.0 {
 			k.trace(tracer);
 			v.trace(tracer);
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,4 +1,18 @@
-#![warn(clippy::all, clippy::nursery, clippy::pedantic)]
+//! jsonnet interpreter implementation
+
+#![deny(unsafe_op_in_unsafe_fn)]
+#![warn(
+	clippy::all,
+	clippy::nursery,
+	clippy::pedantic,
+	// missing_docs,
+	elided_lifetimes_in_paths,
+	explicit_outlives_requirements,
+	noop_method_call,
+	single_use_lifetimes,
+	variant_size_differences,
+	rustdoc::all
+)]
 #![allow(
 	macro_expanded_macro_exports_accessed_by_absolute_paths,
 	clippy::ptr_arg,
@@ -67,23 +81,32 @@
 use trace::{CompactFormat, TraceFormat};
 pub use val::{ManifestFormat, Thunk, Val};
 
+/// Thunk without bound `super`/`this`
+/// object inheritance may be overriden multiple times, and will be fixed only on field read
 pub trait Unbound: Trace {
+	/// Type of value after object context is bound
 	type Bound;
+	/// Create value bound to specified object context
 	fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;
 }
 
+/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code
+/// Standard jsonnet fields are always unbound
 #[derive(Clone, Trace)]
-pub enum LazyBinding {
-	Bindable(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),
+pub enum MaybeUnbound {
+	/// Value needs to be bound to `this`/`super`
+	Unbound(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),
+	/// Value is object-independent
 	Bound(Thunk<Val>),
 }
 
-impl Debug for LazyBinding {
+impl Debug for MaybeUnbound {
 	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-		write!(f, "LazyBinding")
+		write!(f, "MaybeUnbound")
 	}
 }
-impl LazyBinding {
+impl MaybeUnbound {
+	/// Attach object context to value, if required
 	pub fn evaluate(
 		&self,
 		s: State,
@@ -91,17 +114,19 @@
 		this: Option<ObjValue>,
 	) -> Result<Thunk<Val>> {
 		match self {
-			Self::Bindable(v) => v.bind(s, sup, this),
+			Self::Unbound(v) => v.bind(s, sup, this),
 			Self::Bound(v) => Ok(v.clone()),
 		}
 	}
 }
 
-/// During import, this trait will be called to create initial context for file
-/// It may initialize global variables, stdlib for example
+/// During import, this trait will be called to create initial context for file.
+/// It may initialize global variables, stdlib for example.
 pub trait ContextInitializer {
+	/// Initialize default file context.
 	fn initialize(&self, state: State, for_file: Source) -> Context;
-
+	/// Allows upcasting from abstract to concrete context initializer.
+	/// jrsonnet by itself doesn't use this method, it is allowed for it to panic.
 	fn as_any(&self) -> &dyn Any;
 }
 
@@ -116,6 +141,7 @@
 	}
 }
 
+/// Dynamically reconfigurable evaluation settings
 pub struct EvaluationSettings {
 	/// Limits recursion by limiting the number of stack frames
 	pub max_stack: usize,
@@ -401,7 +427,7 @@
 	/// Executes code creating a new stack frame
 	pub fn push<T>(
 		&self,
-		e: CallLocation,
+		e: CallLocation<'_>,
 		frame_desc: impl FnOnce() -> String,
 		f: impl FnOnce() -> Result<T>,
 	) -> Result<T> {
@@ -547,16 +573,13 @@
 
 /// Internals
 impl State {
-	// fn data(&self) -> Ref<EvaluationData> {
-	// 	self.0.data.borrow()
-	// }
-	fn data_mut(&self) -> RefMut<EvaluationData> {
+	fn data_mut(&self) -> RefMut<'_, EvaluationData> {
 		self.0.data.borrow_mut()
 	}
-	pub fn settings(&self) -> Ref<EvaluationSettings> {
+	pub fn settings(&self) -> Ref<'_, EvaluationSettings> {
 		self.0.settings.borrow()
 	}
-	pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {
+	pub fn settings_mut(&self) -> RefMut<'_, EvaluationSettings> {
 		self.0.settings.borrow_mut()
 	}
 }
@@ -623,13 +646,13 @@
 	pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {
 		self.import_resolver().resolve(path.as_ref())
 	}
-	pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {
+	pub fn import_resolver(&self) -> Ref<'_, dyn ImportResolver> {
 		Ref::map(self.settings(), |s| &*s.import_resolver)
 	}
 	pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {
 		self.settings_mut().import_resolver = resolver;
 	}
-	pub fn context_initializer(&self) -> Ref<dyn ContextInitializer> {
+	pub fn context_initializer(&self) -> Ref<'_, dyn ContextInitializer> {
 		Ref::map(self.settings(), |s| &*s.context_initializer)
 	}
 
@@ -640,7 +663,7 @@
 		self.settings_mut().manifest_format = format;
 	}
 
-	pub fn trace_format(&self) -> Ref<dyn TraceFormat> {
+	pub fn trace_format(&self) -> Ref<'_, dyn TraceFormat> {
 		Ref::map(self.settings(), |s| &*s.trace_format)
 	}
 	pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -15,7 +15,7 @@
 	function::CallLocation,
 	gc::{GcHashMap, GcHashSet, TraceBox},
 	operator::evaluate_add_op,
-	throw, LazyBinding, Result, State, Thunk, Unbound, Val,
+	throw, MaybeUnbound, Result, State, Thunk, Unbound, Val,
 };
 
 #[cfg(not(feature = "exp-preserve-order"))]
@@ -100,7 +100,7 @@
 	pub add: bool,
 	pub visibility: Visibility,
 	original_index: FieldIndex,
-	pub invoke: LazyBinding,
+	pub invoke: MaybeUnbound,
 	pub location: Option<ExprLocation>,
 }
 
@@ -208,7 +208,7 @@
 		new.insert(key, value);
 		Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))
 	}
-	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {
+	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {
 		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())
 	}
 
@@ -239,6 +239,8 @@
 	}
 
 	/// Run callback for every field found in object
+	///
+	/// Returns true if ended prematurely
 	pub(crate) fn enum_fields(
 		&self,
 		depth: SuperDepth,
@@ -500,7 +502,7 @@
 		self.assertions.push(assertion);
 		self
 	}
-	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder> {
+	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {
 		let field_index = self.next_field_index;
 		self.next_field_index = self.next_field_index.next();
 		ObjMemberBuilder::new(ValueBuilder(self), name, field_index)
@@ -558,7 +560,7 @@
 		self.location = Some(location);
 		self
 	}
-	fn build_member(self, binding: LazyBinding) -> (Kind, IStr, ObjMember) {
+	fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {
 		(
 			self.kind,
 			self.name,
@@ -574,18 +576,18 @@
 }
 
 pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
-impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {
+impl ObjMemberBuilder<ValueBuilder<'_>> {
 	pub fn value(self, s: State, value: Val) -> Result<()> {
-		self.binding(s, LazyBinding::Bound(Thunk::evaluated(value)))
+		self.binding(s, MaybeUnbound::Bound(Thunk::evaluated(value)))
 	}
 	pub fn bindable(
 		self,
 		s: State,
 		bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>,
 	) -> Result<()> {
-		self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))
+		self.binding(s, MaybeUnbound::Unbound(Cc::new(bindable)))
 	}
-	pub fn binding(self, s: State, binding: LazyBinding) -> Result<()> {
+	pub fn binding(self, s: State, binding: MaybeUnbound) -> Result<()> {
 		let (receiver, name, member) = self.build_member(binding);
 		let location = member.location.clone();
 		let old = receiver.0.map.insert(name.clone(), member);
@@ -601,14 +603,14 @@
 }
 
 pub struct ExtendBuilder<'v>(&'v mut ObjValue);
-impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {
+impl ObjMemberBuilder<ExtendBuilder<'_>> {
 	pub fn value(self, value: Val) {
-		self.binding(LazyBinding::Bound(Thunk::evaluated(value)));
+		self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));
 	}
 	pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {
-		self.binding(LazyBinding::Bindable(Cc::new(bindable)));
+		self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));
 	}
-	pub fn binding(self, binding: LazyBinding) {
+	pub fn binding(self, binding: MaybeUnbound) {
 		let (receiver, name, member) = self.build_member(binding);
 		let new = receiver.0.clone();
 		*receiver.0 = new.extend_with_raw_member(name, member);
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -36,7 +36,7 @@
 
 type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;
 
-pub fn try_parse_mapping_key(str: &str) -> ParseResult<&str> {
+pub fn try_parse_mapping_key(str: &str) -> ParseResult<'_, &str> {
 	if str.is_empty() {
 		return Err(TruncatedFormatCode);
 	}
@@ -96,7 +96,7 @@
 	pub sign: bool,
 }
 
-pub fn try_parse_cflags(str: &str) -> ParseResult<CFlags> {
+pub fn try_parse_cflags(str: &str) -> ParseResult<'_, CFlags> {
 	if str.is_empty() {
 		return Err(TruncatedFormatCode);
 	}
@@ -125,7 +125,7 @@
 	Star,
 	Fixed(usize),
 }
-pub fn try_parse_field_width(str: &str) -> ParseResult<Width> {
+pub fn try_parse_field_width(str: &str) -> ParseResult<'_, Width> {
 	if str.is_empty() {
 		return Err(TruncatedFormatCode);
 	}
@@ -146,7 +146,7 @@
 	Ok((Width::Fixed(out), &str[digits..]))
 }
 
-pub fn try_parse_precision(str: &str) -> ParseResult<Option<Width>> {
+pub fn try_parse_precision(str: &str) -> ParseResult<'_, Option<Width>> {
 	if str.is_empty() {
 		return Err(TruncatedFormatCode);
 	}
@@ -159,7 +159,7 @@
 }
 
 // Only skips
-pub fn try_parse_length_modifier(str: &str) -> ParseResult<()> {
+pub fn try_parse_length_modifier(str: &str) -> ParseResult<'_, ()> {
 	if str.is_empty() {
 		return Err(TruncatedFormatCode);
 	}
@@ -191,7 +191,7 @@
 	caps: bool,
 }
 
-pub fn parse_conversion_type(str: &str) -> ParseResult<ConvType> {
+pub fn parse_conversion_type(str: &str) -> ParseResult<'_, ConvType> {
 	if str.is_empty() {
 		return Err(TruncatedFormatCode);
 	}
@@ -226,7 +226,7 @@
 	convtype: ConvTypeV,
 	caps: bool,
 }
-pub fn parse_code(str: &str) -> ParseResult<Code> {
+pub fn parse_code(str: &str) -> ParseResult<'_, Code<'_>> {
 	if str.is_empty() {
 		return Err(TruncatedFormatCode);
 	}
@@ -255,7 +255,7 @@
 	String(&'s str),
 	Code(Code<'s>),
 }
-pub fn parse_codes(mut str: &str) -> Result<Vec<Element>> {
+pub fn parse_codes(mut str: &str) -> Result<Vec<Element<'_>>> {
 	let mut bytes = str.as_bytes();
 	let mut out = vec![];
 	let mut offset = 0;
@@ -475,7 +475,7 @@
 	s: State,
 	out: &mut String,
 	value: &Val,
-	code: &Code,
+	code: &Code<'_>,
 	width: usize,
 	precision: Option<usize>,
 ) -> Result<()> {
modifiedcrates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -116,7 +116,7 @@
 						|| {
 							let value = obj.get(s.clone(), field.clone())?.unwrap();
 							manifest_json_ex_buf(s.clone(), &value, buf, cur_padding, options)?;
-							Ok(Val::Null)
+							Ok(())
 						},
 					)?;
 				}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/val.rs
1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_types::ValType;67use crate::{8	error::{Error::*, LocError},9	function::FuncVal,10	gc::{GcHashMap, TraceBox},11	stdlib::manifest::{12		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,13	},14	throw,15	typed::BoundedUsize,16	ObjValue, Result, State, Unbound, WeakObjValue,17};1819pub trait ThunkValue: Trace {20	type Output;21	fn get(self: Box<Self>, s: State) -> Result<Self::Output>;22}2324#[derive(Trace)]25enum ThunkInner<T: Trace> {26	Computed(T),27	Errored(LocError),28	Waiting(TraceBox<dyn ThunkValue<Output = T>>),29	Pending,30}3132#[allow(clippy::module_name_repetitions)]33#[derive(Clone, Trace)]34pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);3536impl<T> Thunk<T>37where38	T: Clone + Trace,39{40	pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {41		Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))42	}43	pub fn evaluated(val: T) -> Self {44		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))45	}46	pub fn force(&self, s: State) -> Result<()> {47		self.evaluate(s)?;48		Ok(())49	}50	pub fn evaluate(&self, s: State) -> Result<T> {51		match &*self.0.borrow() {52			ThunkInner::Computed(v) => return Ok(v.clone()),53			ThunkInner::Errored(e) => return Err(e.clone()),54			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),55			ThunkInner::Waiting(..) => (),56		};57		let value = if let ThunkInner::Waiting(value) =58			std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)59		{60			value61		} else {62			unreachable!()63		};64		let new_value = match value.0.get(s) {65			Ok(v) => v,66			Err(e) => {67				*self.0.borrow_mut() = ThunkInner::Errored(e.clone());68				return Err(e);69			}70		};71		*self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());72		Ok(new_value)73	}74}7576type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);7778#[derive(Trace, Clone)]79pub struct CachedUnbound<I, T>80where81	I: Unbound<Bound = T>,82	T: Trace,83{84	cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,85	value: I,86}87impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {88	pub fn new(value: I) -> Self {89		Self {90			cache: Cc::new(RefCell::new(GcHashMap::new())),91			value,92		}93	}94}95impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {96	type Bound = T;97	fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {98		let cache_key = (99			sup.as_ref().map(|s| s.clone().downgrade()),100			this.as_ref().map(|t| t.clone().downgrade()),101		);102		{103			if let Some(t) = self.cache.borrow().get(&cache_key) {104				return Ok(t.clone());105			}106		}107		let bound = self.value.bind(s, sup, this)?;108109		{110			let mut cache = self.cache.borrow_mut();111			cache.insert(cache_key, bound.clone());112		}113114		Ok(bound)115	}116}117118impl<T: Debug + Trace> Debug for Thunk<T> {119	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {120		write!(f, "Lazy")121	}122}123impl<T: Trace> PartialEq for Thunk<T> {124	fn eq(&self, other: &Self) -> bool {125		Cc::ptr_eq(&self.0, &other.0)126	}127}128129#[derive(Clone)]130pub enum ManifestFormat {131	YamlStream(Box<ManifestFormat>),132	Yaml {133		padding: usize,134		#[cfg(feature = "exp-preserve-order")]135		preserve_order: bool,136	},137	Json {138		padding: usize,139		#[cfg(feature = "exp-preserve-order")]140		preserve_order: bool,141	},142	ToString,143	String,144}145impl ManifestFormat {146	#[cfg(feature = "exp-preserve-order")]147	fn preserve_order(&self) -> bool {148		match self {149			ManifestFormat::YamlStream(s) => s.preserve_order(),150			ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,151			ManifestFormat::Json { preserve_order, .. } => *preserve_order,152			ManifestFormat::ToString => false,153			ManifestFormat::String => false,154		}155	}156}157158#[derive(Debug, Clone, Trace)]159pub struct Slice {160	pub(crate) inner: ArrValue,161	pub(crate) from: u32,162	pub(crate) to: u32,163	pub(crate) step: u32,164}165impl Slice {166	const fn from(&self) -> usize {167		self.from as usize168	}169	const fn to(&self) -> usize {170		self.to as usize171	}172	const fn step(&self) -> usize {173		self.step as usize174	}175	const fn len(&self) -> usize {176		// TODO: use div_ceil177		let diff = self.to() - self.from();178		let rem = diff % self.step();179		let div = diff / self.step();180181		if rem == 0 {182			div183		} else {184			div + 1185		}186	}187}188189#[derive(Debug, Clone, Trace)]190// may contrain other ArrValue191#[trace(tracking(force))]192pub enum ArrValue {193	Bytes(#[trace(skip)] IBytes),194	Lazy(Cc<Vec<Thunk<Val>>>),195	Eager(Cc<Vec<Val>>),196	Extended(Box<(Self, Self)>),197	Range(i32, i32),198	Slice(Box<Slice>),199	Reversed(Box<Self>),200}201202#[cfg(target_pointer_width = "64")]203static_assertions::assert_eq_size!(ArrValue, [u8; 16]);204205impl ArrValue {206	pub fn new_eager() -> Self {207		Self::Eager(Cc::new(Vec::new()))208	}209	pub fn empty() -> Self {210		Self::new_range(0, 0)211	}212213	/// # Panics214	/// If a > b215	#[inline]216	pub fn new_range(a: i32, b: i32) -> Self {217		assert!(a <= b);218		Self::Range(a, b)219	}220221	/// # Panics222	/// If passed numbers are incorrect223	#[must_use]224	pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {225		let len = self.len();226		let from = from.unwrap_or(0);227		let to = to.unwrap_or(len).min(len);228		let step = step.unwrap_or(1);229		assert!(from < to);230		assert!(step > 0);231232		Self::Slice(Box::new(Slice {233			inner: self,234			from: from as u32,235			to: to as u32,236			step: step as u32,237		}))238	}239240	pub fn len(&self) -> usize {241		match self {242			Self::Bytes(i) => i.len(),243			Self::Lazy(l) => l.len(),244			Self::Eager(e) => e.len(),245			Self::Extended(v) => v.0.len() + v.1.len(),246			Self::Range(a, b) => a.abs_diff(*b) as usize + 1,247			Self::Reversed(i) => i.len(),248			Self::Slice(s) => s.len(),249		}250	}251252	pub fn is_empty(&self) -> bool {253		self.len() == 0254	}255256	pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {257		match self {258			Self::Bytes(i) => i259				.get(index)260				.map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),261			Self::Lazy(vec) => {262				if let Some(v) = vec.get(index) {263					Ok(Some(v.evaluate(s)?))264				} else {265					Ok(None)266				}267			}268			Self::Eager(vec) => Ok(vec.get(index).cloned()),269			Self::Extended(v) => {270				let a_len = v.0.len();271				if a_len > index {272					v.0.get(s, index)273				} else {274					v.1.get(s, index - a_len)275				}276			}277			Self::Range(a, _) => {278				if index >= self.len() {279					return Ok(None);280				}281				Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))282			}283			Self::Reversed(v) => {284				let len = v.len();285				if index >= len {286					return Ok(None);287				}288				v.get(s, len - index - 1)289			}290			Self::Slice(v) => {291				let index = v.from() + index * v.step();292				if index >= v.to() {293					return Ok(None);294				}295				v.inner.get(s, index)296			}297		}298	}299300	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {301		match self {302			Self::Bytes(i) => i303				.get(index)304				.map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),305			Self::Lazy(vec) => vec.get(index).cloned(),306			Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),307			Self::Extended(v) => {308				let a_len = v.0.len();309				if a_len > index {310					v.0.get_lazy(index)311				} else {312					v.1.get_lazy(index - a_len)313				}314			}315			Self::Range(a, _) => {316				if index >= self.len() {317					return None;318				}319				Some(Thunk::evaluated(Val::Num(320					((*a as isize) + index as isize) as f64,321				)))322			}323			Self::Reversed(v) => {324				let len = v.len();325				if index >= len {326					return None;327				}328				v.get_lazy(len - index - 1)329			}330			Self::Slice(s) => {331				let index = s.from() + index * s.step();332				if index >= s.to() {333					return None;334				}335				s.inner.get_lazy(index)336			}337		}338	}339340	pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {341		Ok(match self {342			Self::Bytes(i) => {343				let mut out = Vec::with_capacity(i.len());344				for v in i.iter() {345					out.push(Val::Num(f64::from(*v)));346				}347				Cc::new(out)348			}349			Self::Lazy(vec) => {350				let mut out = Vec::with_capacity(vec.len());351				for item in vec.iter() {352					out.push(item.evaluate(s.clone())?);353				}354				Cc::new(out)355			}356			Self::Eager(vec) => vec.clone(),357			Self::Extended(_v) => {358				let mut out = Vec::with_capacity(self.len());359				for item in self.iter(s) {360					out.push(item?);361				}362				Cc::new(out)363			}364			Self::Range(a, b) => {365				let mut out = Vec::with_capacity(self.len());366				for i in *a..*b {367					out.push(Val::Num(f64::from(i)));368				}369				Cc::new(out)370			}371			Self::Reversed(r) => {372				let mut r = r.evaluated(s)?;373				Cc::update_with(&mut r, |v| v.reverse());374				r375			}376			Self::Slice(v) => {377				let mut out = Vec::with_capacity(v.inner.len());378				for v in v379					.inner380					.iter_lazy()381					.skip(v.from())382					.take(v.to() - v.from())383					.step_by(v.step())384				{385					out.push(v.evaluate(s.clone())?);386				}387				Cc::new(out)388			}389		})390	}391392	pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {393		(0..self.len()).map(move |idx| match self {394			Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),395			Self::Lazy(l) => l[idx].evaluate(s.clone()),396			Self::Eager(e) => Ok(e[idx].clone()),397			Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {398				self.get(s.clone(), idx).map(|e| e.expect("idx < len"))399			}400		})401	}402403	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {404		(0..self.len()).map(move |idx| match self {405			Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),406			Self::Lazy(l) => l[idx].clone(),407			Self::Eager(e) => Thunk::evaluated(e[idx].clone()),408			Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {409				self.get_lazy(idx).expect("idx < len")410			}411		})412	}413414	#[must_use]415	pub fn reversed(self) -> Self {416		Self::Reversed(Box::new(self))417	}418419	pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {420		let mut out = Vec::with_capacity(self.len());421422		for value in self.iter(s) {423			out.push(mapper(value?)?);424		}425426		Ok(Self::Eager(Cc::new(out)))427	}428429	pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {430		let mut out = Vec::with_capacity(self.len());431432		for value in self.iter(s) {433			let value = value?;434			if filter(&value)? {435				out.push(value);436			}437		}438439		Ok(Self::Eager(Cc::new(out)))440	}441442	pub fn ptr_eq(a: &Self, b: &Self) -> bool {443		match (a, b) {444			(Self::Lazy(a), Self::Lazy(b)) => Cc::ptr_eq(a, b),445			(Self::Eager(a), Self::Eager(b)) => Cc::ptr_eq(a, b),446			_ => false,447		}448	}449}450451impl From<Vec<Thunk<Val>>> for ArrValue {452	fn from(v: Vec<Thunk<Val>>) -> Self {453		Self::Lazy(Cc::new(v))454	}455}456457impl From<Vec<Val>> for ArrValue {458	fn from(v: Vec<Val>) -> Self {459		Self::Eager(Cc::new(v))460	}461}462463#[allow(clippy::module_name_repetitions)]464pub enum IndexableVal {465	Str(IStr),466	Arr(ArrValue),467}468impl IndexableVal {469	pub fn slice(470		self,471		index: Option<BoundedUsize<0, { i32::MAX as usize }>>,472		end: Option<BoundedUsize<0, { i32::MAX as usize }>>,473		step: Option<BoundedUsize<1, { i32::MAX as usize }>>,474	) -> Result<Self> {475		match &self {476			IndexableVal::Str(s) => {477				let index = index.as_deref().copied().unwrap_or(0);478				let end = end.as_deref().copied().unwrap_or(usize::MAX);479				let step = step.as_deref().copied().unwrap_or(1);480481				if index >= end {482					return Ok(Self::Str("".into()));483				}484485				Ok(Self::Str(486					(s.chars()487						.skip(index)488						.take(end - index)489						.step_by(step)490						.collect::<String>())491					.into(),492				))493			}494			IndexableVal::Arr(arr) => {495				let index = index.as_deref().copied().unwrap_or(0);496				let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());497				let step = step.as_deref().copied().unwrap_or(1);498499				if index >= end {500					return Ok(Self::Arr(ArrValue::new_eager()));501				}502503				Ok(Self::Arr(ArrValue::Slice(Box::new(Slice {504					inner: arr.clone(),505					from: index as u32,506					to: end as u32,507					step: step as u32,508				}))))509			}510		}511	}512}513514#[derive(Debug, Clone, Trace)]515pub enum Val {516	Bool(bool),517	Null,518	Str(IStr),519	Num(f64),520	Arr(ArrValue),521	Obj(ObjValue),522	Func(FuncVal),523}524525impl From<IndexableVal> for Val {526	fn from(v: IndexableVal) -> Self {527		match v {528			IndexableVal::Str(s) => Self::Str(s),529			IndexableVal::Arr(a) => Self::Arr(a),530		}531	}532}533534// Broken between stable and nightly, as there is new layout size optimization535// #[cfg(target_pointer_width = "64")]536// static_assertions::assert_eq_size!(Val, [u8; 24]);537538impl Val {539	pub const fn as_bool(&self) -> Option<bool> {540		match self {541			Self::Bool(v) => Some(*v),542			_ => None,543		}544	}545	pub const fn as_null(&self) -> Option<()> {546		match self {547			Self::Null => Some(()),548			_ => None,549		}550	}551	pub fn as_str(&self) -> Option<IStr> {552		match self {553			Self::Str(s) => Some(s.clone()),554			_ => None,555		}556	}557	pub const fn as_num(&self) -> Option<f64> {558		match self {559			Self::Num(n) => Some(*n),560			_ => None,561		}562	}563	pub fn as_arr(&self) -> Option<ArrValue> {564		match self {565			Self::Arr(a) => Some(a.clone()),566			_ => None,567		}568	}569	pub fn as_obj(&self) -> Option<ObjValue> {570		match self {571			Self::Obj(o) => Some(o.clone()),572			_ => None,573		}574	}575	pub fn as_func(&self) -> Option<FuncVal> {576		match self {577			Self::Func(f) => Some(f.clone()),578			_ => None,579		}580	}581582	/// Creates `Val::Num` after checking for numeric overflow.583	/// As numbers are `f64`, we can just check for their finity.584	pub fn new_checked_num(num: f64) -> Result<Self> {585		if num.is_finite() {586			Ok(Self::Num(num))587		} else {588			throw!(RuntimeError("overflow".into()))589		}590	}591592	pub const fn value_type(&self) -> ValType {593		match self {594			Self::Str(..) => ValType::Str,595			Self::Num(..) => ValType::Num,596			Self::Arr(..) => ValType::Arr,597			Self::Obj(..) => ValType::Obj,598			Self::Bool(_) => ValType::Bool,599			Self::Null => ValType::Null,600			Self::Func(..) => ValType::Func,601		}602	}603604	pub fn to_string(&self, s: State) -> Result<IStr> {605		Ok(match self {606			Self::Bool(true) => "true".into(),607			Self::Bool(false) => "false".into(),608			Self::Null => "null".into(),609			Self::Str(s) => s.clone(),610			v => manifest_json_ex(611				s,612				v,613				&ManifestJsonOptions {614					padding: "",615					mtype: ManifestType::ToString,616					newline: "\n",617					key_val_sep: ": ",618					#[cfg(feature = "exp-preserve-order")]619					preserve_order: false,620				},621			)?622			.into(),623		})624	}625626	/// Expects value to be object, outputs (key, manifested value) pairs627	pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {628		let obj = match self {629			Self::Obj(obj) => obj,630			_ => throw!(MultiManifestOutputIsNotAObject),631		};632		let keys = obj.fields(633			#[cfg(feature = "exp-preserve-order")]634			ty.preserve_order(),635		);636		let mut out = Vec::with_capacity(keys.len());637		for key in keys {638			let value = obj639				.get(s.clone(), key.clone())?640				.expect("item in object")641				.manifest(s.clone(), ty)?;642			out.push((key, value));643		}644		Ok(out)645	}646647	/// Expects value to be array, outputs manifested values648	pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {649		let arr = match self {650			Self::Arr(a) => a,651			_ => throw!(StreamManifestOutputIsNotAArray),652		};653		let mut out = Vec::with_capacity(arr.len());654		for i in arr.iter(s.clone()) {655			out.push(i?.manifest(s.clone(), ty)?);656		}657		Ok(out)658	}659660	pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {661		Ok(match ty {662			ManifestFormat::YamlStream(format) => {663				let arr = match self {664					Self::Arr(a) => a,665					_ => throw!(StreamManifestOutputIsNotAArray),666				};667				let mut out = String::new();668669				match format as &ManifestFormat {670					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),671					ManifestFormat::String => throw!(StreamManifestCannotNestString),672					_ => {}673				};674675				if !arr.is_empty() {676					for v in arr.iter(s.clone()) {677						out.push_str("---\n");678						out.push_str(&v?.manifest(s.clone(), format)?);679						out.push('\n');680					}681					out.push_str("...");682				}683684				out.into()685			}686			ManifestFormat::Yaml {687				padding,688				#[cfg(feature = "exp-preserve-order")]689				preserve_order,690			} => self.to_yaml(691				s,692				*padding,693				#[cfg(feature = "exp-preserve-order")]694				*preserve_order,695			)?,696			ManifestFormat::Json {697				padding,698				#[cfg(feature = "exp-preserve-order")]699				preserve_order,700			} => self.to_json(701				s,702				*padding,703				#[cfg(feature = "exp-preserve-order")]704				*preserve_order,705			)?,706			ManifestFormat::ToString => self.to_string(s)?,707			ManifestFormat::String => match self {708				Self::Str(s) => s.clone(),709				_ => throw!(StringManifestOutputIsNotAString),710			},711		})712	}713714	/// For manifestification715	pub fn to_json(716		&self,717		s: State,718		padding: usize,719		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,720	) -> Result<IStr> {721		manifest_json_ex(722			s,723			self,724			&ManifestJsonOptions {725				padding: &" ".repeat(padding),726				mtype: if padding == 0 {727					ManifestType::Minify728				} else {729					ManifestType::Manifest730				},731				newline: "\n",732				key_val_sep: ": ",733				#[cfg(feature = "exp-preserve-order")]734				preserve_order,735			},736		)737		.map(Into::into)738	}739740	/// Calls `std.manifestJson`741	pub fn to_std_json(742		&self,743		s: State,744		padding: usize,745		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,746	) -> Result<Rc<str>> {747		manifest_json_ex(748			s,749			self,750			&ManifestJsonOptions {751				padding: &" ".repeat(padding),752				mtype: ManifestType::Std,753				newline: "\n",754				key_val_sep: ": ",755				#[cfg(feature = "exp-preserve-order")]756				preserve_order,757			},758		)759		.map(Into::into)760	}761762	pub fn to_yaml(763		&self,764		s: State,765		padding: usize,766		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,767	) -> Result<IStr> {768		let padding = &" ".repeat(padding);769		manifest_yaml_ex(770			s,771			self,772			&ManifestYamlOptions {773				padding,774				arr_element_padding: padding,775				quote_keys: false,776				#[cfg(feature = "exp-preserve-order")]777				preserve_order,778			},779		)780		.map(Into::into)781	}782	pub fn into_indexable(self) -> Result<IndexableVal> {783		Ok(match self {784			Val::Str(s) => IndexableVal::Str(s),785			Val::Arr(arr) => IndexableVal::Arr(arr),786			_ => throw!(ValueIsNotIndexable(self.value_type())),787		})788	}789}790791const fn is_function_like(val: &Val) -> bool {792	matches!(val, Val::Func(_))793}794795/// Native implementation of `std.primitiveEquals`796pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {797	Ok(match (val_a, val_b) {798		(Val::Bool(a), Val::Bool(b)) => a == b,799		(Val::Null, Val::Null) => true,800		(Val::Str(a), Val::Str(b)) => a == b,801		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,802		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(803			"primitiveEquals operates on primitive types, got array".into(),804		)),805		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(806			"primitiveEquals operates on primitive types, got object".into(),807		)),808		(a, b) if is_function_like(a) && is_function_like(b) => {809			throw!(RuntimeError("cannot test equality of functions".into()))810		}811		(_, _) => false,812	})813}814815/// Native implementation of `std.equals`816pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {817	if val_a.value_type() != val_b.value_type() {818		return Ok(false);819	}820	match (val_a, val_b) {821		(Val::Arr(a), Val::Arr(b)) => {822			if ArrValue::ptr_eq(a, b) {823				return Ok(true);824			}825			if a.len() != b.len() {826				return Ok(false);827			}828			for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {829				if !equals(s.clone(), &a?, &b?)? {830					return Ok(false);831				}832			}833			Ok(true)834		}835		(Val::Obj(a), Val::Obj(b)) => {836			if ObjValue::ptr_eq(a, b) {837				return Ok(true);838			}839			let fields = a.fields(840				#[cfg(feature = "exp-preserve-order")]841				false,842			);843			if fields844				!= b.fields(845					#[cfg(feature = "exp-preserve-order")]846					false,847				) {848				return Ok(false);849			}850			for field in fields {851				if !equals(852					s.clone(),853					&a.get(s.clone(), field.clone())?.expect("field exists"),854					&b.get(s.clone(), field)?.expect("field exists"),855				)? {856					return Ok(false);857				}858			}859			Ok(true)860		}861		(a, b) => Ok(primitive_equals(a, b)?),862	}863}
after · crates/jrsonnet-evaluator/src/val.rs
1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_types::ValType;67use crate::{8	error::{Error::*, LocError},9	function::FuncVal,10	gc::{GcHashMap, TraceBox},11	stdlib::manifest::{12		manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,13	},14	throw,15	typed::BoundedUsize,16	ObjValue, Result, State, Unbound, WeakObjValue,17};1819pub trait ThunkValue: Trace {20	type Output;21	fn get(self: Box<Self>, s: State) -> Result<Self::Output>;22}2324#[derive(Trace)]25enum ThunkInner<T: Trace> {26	Computed(T),27	Errored(LocError),28	Waiting(TraceBox<dyn ThunkValue<Output = T>>),29	Pending,30}3132#[allow(clippy::module_name_repetitions)]33#[derive(Clone, Trace)]34pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);3536impl<T> Thunk<T>37where38	T: Clone + Trace,39{40	pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {41		Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))42	}43	pub fn evaluated(val: T) -> Self {44		Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))45	}46	pub fn force(&self, s: State) -> Result<()> {47		self.evaluate(s)?;48		Ok(())49	}50	pub fn evaluate(&self, s: State) -> Result<T> {51		match &*self.0.borrow() {52			ThunkInner::Computed(v) => return Ok(v.clone()),53			ThunkInner::Errored(e) => return Err(e.clone()),54			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),55			ThunkInner::Waiting(..) => (),56		};57		let value = if let ThunkInner::Waiting(value) =58			std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)59		{60			value61		} else {62			unreachable!()63		};64		let new_value = match value.0.get(s) {65			Ok(v) => v,66			Err(e) => {67				*self.0.borrow_mut() = ThunkInner::Errored(e.clone());68				return Err(e);69			}70		};71		*self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());72		Ok(new_value)73	}74}7576type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);7778#[derive(Trace, Clone)]79pub struct CachedUnbound<I, T>80where81	I: Unbound<Bound = T>,82	T: Trace,83{84	cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,85	value: I,86}87impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {88	pub fn new(value: I) -> Self {89		Self {90			cache: Cc::new(RefCell::new(GcHashMap::new())),91			value,92		}93	}94}95impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {96	type Bound = T;97	fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {98		let cache_key = (99			sup.as_ref().map(|s| s.clone().downgrade()),100			this.as_ref().map(|t| t.clone().downgrade()),101		);102		{103			if let Some(t) = self.cache.borrow().get(&cache_key) {104				return Ok(t.clone());105			}106		}107		let bound = self.value.bind(s, sup, this)?;108109		{110			let mut cache = self.cache.borrow_mut();111			cache.insert(cache_key, bound.clone());112		}113114		Ok(bound)115	}116}117118impl<T: Debug + Trace> Debug for Thunk<T> {119	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {120		write!(f, "Lazy")121	}122}123impl<T: Trace> PartialEq for Thunk<T> {124	fn eq(&self, other: &Self) -> bool {125		Cc::ptr_eq(&self.0, &other.0)126	}127}128129#[derive(Clone)]130pub enum ManifestFormat {131	YamlStream(Box<ManifestFormat>),132	Yaml {133		padding: usize,134		#[cfg(feature = "exp-preserve-order")]135		preserve_order: bool,136	},137	Json {138		padding: usize,139		#[cfg(feature = "exp-preserve-order")]140		preserve_order: bool,141	},142	ToString,143	String,144}145impl ManifestFormat {146	#[cfg(feature = "exp-preserve-order")]147	fn preserve_order(&self) -> bool {148		match self {149			ManifestFormat::YamlStream(s) => s.preserve_order(),150			ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,151			ManifestFormat::Json { preserve_order, .. } => *preserve_order,152			ManifestFormat::ToString => false,153			ManifestFormat::String => false,154		}155	}156}157158#[derive(Debug, Clone, Trace)]159pub struct Slice {160	pub(crate) inner: ArrValue,161	pub(crate) from: u32,162	pub(crate) to: u32,163	pub(crate) step: u32,164}165impl Slice {166	const fn from(&self) -> usize {167		self.from as usize168	}169	const fn to(&self) -> usize {170		self.to as usize171	}172	const fn step(&self) -> usize {173		self.step as usize174	}175	const fn len(&self) -> usize {176		// TODO: use div_ceil177		let diff = self.to() - self.from();178		let rem = diff % self.step();179		let div = diff / self.step();180181		if rem == 0 {182			div183		} else {184			div + 1185		}186	}187}188189/// Represents a Jsonnet array value.190#[derive(Debug, Clone, Trace)]191// may contrain other ArrValue192#[trace(tracking(force))]193pub enum ArrValue {194	/// Layout optimized byte array.195	Bytes(#[trace(skip)] IBytes),196	/// Every element is lazy evaluated.197	Lazy(Cc<Vec<Thunk<Val>>>),198	/// Every field is already evaluated.199	Eager(Cc<Vec<Val>>),200	/// Concatenation of two arrays of any kind.201	Extended(Box<(Self, Self)>),202	/// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.203	/// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.204	Range(i32, i32),205	/// Sliced array view.206	Slice(Box<Slice>),207	/// Reversed array view.208	/// Returned by `std.reverse(other)` call209	Reversed(Box<Self>),210}211212#[cfg(target_pointer_width = "64")]213static_assertions::assert_eq_size!(ArrValue, [u8; 16]);214215impl ArrValue {216	pub fn new_eager() -> Self {217		Self::Eager(Cc::new(Vec::new()))218	}219	pub fn empty() -> Self {220		Self::new_range(0, 0)221	}222223	/// # Panics224	/// If a > b225	#[inline]226	pub fn new_range(a: i32, b: i32) -> Self {227		assert!(a <= b);228		Self::Range(a, b)229	}230231	/// # Panics232	/// If passed numbers are incorrect233	#[must_use]234	pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {235		let len = self.len();236		let from = from.unwrap_or(0);237		let to = to.unwrap_or(len).min(len);238		let step = step.unwrap_or(1);239		assert!(from < to);240		assert!(step > 0);241242		Self::Slice(Box::new(Slice {243			inner: self,244			from: from as u32,245			to: to as u32,246			step: step as u32,247		}))248	}249250	/// Array length.251	pub fn len(&self) -> usize {252		match self {253			Self::Bytes(i) => i.len(),254			Self::Lazy(l) => l.len(),255			Self::Eager(e) => e.len(),256			Self::Extended(v) => v.0.len() + v.1.len(),257			Self::Range(a, b) => a.abs_diff(*b) as usize + 1,258			Self::Reversed(i) => i.len(),259			Self::Slice(s) => s.len(),260		}261	}262263	/// Is array contains no elements?264	pub fn is_empty(&self) -> bool {265		self.len() == 0266	}267268	/// Get array element by index, evaluating it, if it is lazy.269	///270	/// Returns `None` on out-of-bounds condition.271	pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {272		match self {273			Self::Bytes(i) => i274				.get(index)275				.map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),276			Self::Lazy(vec) => {277				if let Some(v) = vec.get(index) {278					Ok(Some(v.evaluate(s)?))279				} else {280					Ok(None)281				}282			}283			Self::Eager(vec) => Ok(vec.get(index).cloned()),284			Self::Extended(v) => {285				let a_len = v.0.len();286				if a_len > index {287					v.0.get(s, index)288				} else {289					v.1.get(s, index - a_len)290				}291			}292			Self::Range(a, _) => {293				if index >= self.len() {294					return Ok(None);295				}296				Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))297			}298			Self::Reversed(v) => {299				let len = v.len();300				if index >= len {301					return Ok(None);302				}303				v.get(s, len - index - 1)304			}305			Self::Slice(v) => {306				let index = v.from() + index * v.step();307				if index >= v.to() {308					return Ok(None);309				}310				v.inner.get(s, index)311			}312		}313	}314315	/// Get array element by index, without evaluation.316	///317	/// Returns `None` on out-of-bounds condition.318	pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {319		match self {320			Self::Bytes(i) => i321				.get(index)322				.map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),323			Self::Lazy(vec) => vec.get(index).cloned(),324			Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),325			Self::Extended(v) => {326				let a_len = v.0.len();327				if a_len > index {328					v.0.get_lazy(index)329				} else {330					v.1.get_lazy(index - a_len)331				}332			}333			Self::Range(a, _) => {334				if index >= self.len() {335					return None;336				}337				Some(Thunk::evaluated(Val::Num(338					((*a as isize) + index as isize) as f64,339				)))340			}341			Self::Reversed(v) => {342				let len = v.len();343				if index >= len {344					return None;345				}346				v.get_lazy(len - index - 1)347			}348			Self::Slice(s) => {349				let index = s.from() + index * s.step();350				if index >= s.to() {351					return None;352				}353				s.inner.get_lazy(index)354			}355		}356	}357358	/// Evaluate all array elements, returning new array.359	pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {360		Ok(match self {361			Self::Bytes(i) => {362				let mut out = Vec::with_capacity(i.len());363				for v in i.iter() {364					out.push(Val::Num(f64::from(*v)));365				}366				Cc::new(out)367			}368			Self::Lazy(vec) => {369				let mut out = Vec::with_capacity(vec.len());370				for item in vec.iter() {371					out.push(item.evaluate(s.clone())?);372				}373				Cc::new(out)374			}375			Self::Eager(vec) => vec.clone(),376			Self::Extended(_v) => {377				let mut out = Vec::with_capacity(self.len());378				for item in self.iter(s) {379					out.push(item?);380				}381				Cc::new(out)382			}383			Self::Range(a, b) => {384				let mut out = Vec::with_capacity(self.len());385				for i in *a..*b {386					out.push(Val::Num(f64::from(i)));387				}388				Cc::new(out)389			}390			Self::Reversed(r) => {391				let mut r = r.evaluated(s)?;392				Cc::update_with(&mut r, |v| v.reverse());393				r394			}395			Self::Slice(v) => {396				let mut out = Vec::with_capacity(v.inner.len());397				for v in v398					.inner399					.iter_lazy()400					.skip(v.from())401					.take(v.to() - v.from())402					.step_by(v.step())403				{404					out.push(v.evaluate(s.clone())?);405				}406				Cc::new(out)407			}408		})409	}410411	/// Iterate over elements, evaluating them.412	pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {413		(0..self.len()).map(move |idx| match self {414			Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),415			Self::Lazy(l) => l[idx].evaluate(s.clone()),416			Self::Eager(e) => Ok(e[idx].clone()),417			Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {418				self.get(s.clone(), idx).map(|e| e.expect("idx < len"))419			}420		})421	}422423	/// Iterate over elements, returning lazy values.424	pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {425		(0..self.len()).map(move |idx| match self {426			Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),427			Self::Lazy(l) => l[idx].clone(),428			Self::Eager(e) => Thunk::evaluated(e[idx].clone()),429			Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {430				self.get_lazy(idx).expect("idx < len")431			}432		})433	}434435	/// Return a reversed view on current array.436	#[must_use]437	pub fn reversed(self) -> Self {438		Self::Reversed(Box::new(self))439	}440441	/// Return a new array, produced by passing every element of current array to specified callback function.442	pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {443		let mut out = Vec::with_capacity(self.len());444445		for value in self.iter(s) {446			out.push(mapper(value?)?);447		}448449		Ok(Self::Eager(Cc::new(out)))450	}451452	/// Return a new array, produced from current array by removing every value, for which specified callback function returns false.453	pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {454		let mut out = Vec::with_capacity(self.len());455456		for value in self.iter(s) {457			let value = value?;458			if filter(&value)? {459				out.push(value);460			}461		}462463		Ok(Self::Eager(Cc::new(out)))464	}465466	pub fn ptr_eq(a: &Self, b: &Self) -> bool {467		match (a, b) {468			(Self::Lazy(a), Self::Lazy(b)) => Cc::ptr_eq(a, b),469			(Self::Eager(a), Self::Eager(b)) => Cc::ptr_eq(a, b),470			_ => false,471		}472	}473}474475impl From<Vec<Thunk<Val>>> for ArrValue {476	fn from(v: Vec<Thunk<Val>>) -> Self {477		Self::Lazy(Cc::new(v))478	}479}480481impl From<Vec<Val>> for ArrValue {482	fn from(v: Vec<Val>) -> Self {483		Self::Eager(Cc::new(v))484	}485}486487/// Represents a Jsonnet value, which can be spliced or indexed (string or array).488#[allow(clippy::module_name_repetitions)]489pub enum IndexableVal {490	/// String.491	Str(IStr),492	/// Array.493	Arr(ArrValue),494}495impl IndexableVal {496	/// Slice the value.497	///498	/// # Implementation499	///500	/// For strings, will create a copy of specified interval.501	///502	/// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.503	pub fn slice(504		self,505		index: Option<BoundedUsize<0, { i32::MAX as usize }>>,506		end: Option<BoundedUsize<0, { i32::MAX as usize }>>,507		step: Option<BoundedUsize<1, { i32::MAX as usize }>>,508	) -> Result<Self> {509		match &self {510			IndexableVal::Str(s) => {511				let index = index.as_deref().copied().unwrap_or(0);512				let end = end.as_deref().copied().unwrap_or(usize::MAX);513				let step = step.as_deref().copied().unwrap_or(1);514515				if index >= end {516					return Ok(Self::Str("".into()));517				}518519				Ok(Self::Str(520					(s.chars()521						.skip(index)522						.take(end - index)523						.step_by(step)524						.collect::<String>())525					.into(),526				))527			}528			IndexableVal::Arr(arr) => {529				let index = index.as_deref().copied().unwrap_or(0);530				let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());531				let step = step.as_deref().copied().unwrap_or(1);532533				if index >= end {534					return Ok(Self::Arr(ArrValue::new_eager()));535				}536537				Ok(Self::Arr(ArrValue::Slice(Box::new(Slice {538					inner: arr.clone(),539					from: index as u32,540					to: end as u32,541					step: step as u32,542				}))))543			}544		}545	}546}547548/// Represents any valid Jsonnet value.549#[derive(Debug, Clone, Trace)]550pub enum Val {551	/// Represents a Jsonnet boolean.552	Bool(bool),553	/// Represents a Jsonnet null value.554	Null,555	/// Represents a Jsonnet string.556	Str(IStr),557	/// Represents a Jsonnet number.558	/// Should be finite, and not NaN559	/// This restriction isn't enforced by enum, as enum field can't be marked as private560	Num(f64),561	/// Represents a Jsonnet array.562	Arr(ArrValue),563	/// Represents a Jsonnet object.564	Obj(ObjValue),565	/// Represents a Jsonnet function.566	Func(FuncVal),567}568569impl From<IndexableVal> for Val {570	fn from(v: IndexableVal) -> Self {571		match v {572			IndexableVal::Str(s) => Self::Str(s),573			IndexableVal::Arr(a) => Self::Arr(a),574		}575	}576}577578// Broken between stable and nightly, as there is new layout size optimization579// #[cfg(target_pointer_width = "64")]580// static_assertions::assert_eq_size!(Val, [u8; 24]);581582impl Val {583	pub const fn as_bool(&self) -> Option<bool> {584		match self {585			Self::Bool(v) => Some(*v),586			_ => None,587		}588	}589	pub const fn as_null(&self) -> Option<()> {590		match self {591			Self::Null => Some(()),592			_ => None,593		}594	}595	pub fn as_str(&self) -> Option<IStr> {596		match self {597			Self::Str(s) => Some(s.clone()),598			_ => None,599		}600	}601	pub const fn as_num(&self) -> Option<f64> {602		match self {603			Self::Num(n) => Some(*n),604			_ => None,605		}606	}607	pub fn as_arr(&self) -> Option<ArrValue> {608		match self {609			Self::Arr(a) => Some(a.clone()),610			_ => None,611		}612	}613	pub fn as_obj(&self) -> Option<ObjValue> {614		match self {615			Self::Obj(o) => Some(o.clone()),616			_ => None,617		}618	}619	pub fn as_func(&self) -> Option<FuncVal> {620		match self {621			Self::Func(f) => Some(f.clone()),622			_ => None,623		}624	}625626	/// Creates `Val::Num` after checking for numeric overflow.627	/// As numbers are `f64`, we can just check for their finity.628	pub fn new_checked_num(num: f64) -> Result<Self> {629		if num.is_finite() {630			Ok(Self::Num(num))631		} else {632			throw!(RuntimeError("overflow".into()))633		}634	}635636	pub const fn value_type(&self) -> ValType {637		match self {638			Self::Str(..) => ValType::Str,639			Self::Num(..) => ValType::Num,640			Self::Arr(..) => ValType::Arr,641			Self::Obj(..) => ValType::Obj,642			Self::Bool(_) => ValType::Bool,643			Self::Null => ValType::Null,644			Self::Func(..) => ValType::Func,645		}646	}647648	pub fn to_string(&self, s: State) -> Result<IStr> {649		Ok(match self {650			Self::Bool(true) => "true".into(),651			Self::Bool(false) => "false".into(),652			Self::Null => "null".into(),653			Self::Str(s) => s.clone(),654			v => manifest_json_ex(655				s,656				v,657				&ManifestJsonOptions {658					padding: "",659					mtype: ManifestType::ToString,660					newline: "\n",661					key_val_sep: ": ",662					#[cfg(feature = "exp-preserve-order")]663					preserve_order: false,664				},665			)?666			.into(),667		})668	}669670	/// Expects value to be object, outputs (key, manifested value) pairs671	pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {672		let obj = match self {673			Self::Obj(obj) => obj,674			_ => throw!(MultiManifestOutputIsNotAObject),675		};676		let keys = obj.fields(677			#[cfg(feature = "exp-preserve-order")]678			ty.preserve_order(),679		);680		let mut out = Vec::with_capacity(keys.len());681		for key in keys {682			let value = obj683				.get(s.clone(), key.clone())?684				.expect("item in object")685				.manifest(s.clone(), ty)?;686			out.push((key, value));687		}688		Ok(out)689	}690691	/// Expects value to be array, outputs manifested values692	pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {693		let arr = match self {694			Self::Arr(a) => a,695			_ => throw!(StreamManifestOutputIsNotAArray),696		};697		let mut out = Vec::with_capacity(arr.len());698		for i in arr.iter(s.clone()) {699			out.push(i?.manifest(s.clone(), ty)?);700		}701		Ok(out)702	}703704	pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {705		Ok(match ty {706			ManifestFormat::YamlStream(format) => {707				let arr = match self {708					Self::Arr(a) => a,709					_ => throw!(StreamManifestOutputIsNotAArray),710				};711				let mut out = String::new();712713				match format as &ManifestFormat {714					ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),715					ManifestFormat::String => throw!(StreamManifestCannotNestString),716					_ => {}717				};718719				if !arr.is_empty() {720					for v in arr.iter(s.clone()) {721						out.push_str("---\n");722						out.push_str(&v?.manifest(s.clone(), format)?);723						out.push('\n');724					}725					out.push_str("...");726				}727728				out.into()729			}730			ManifestFormat::Yaml {731				padding,732				#[cfg(feature = "exp-preserve-order")]733				preserve_order,734			} => self.to_yaml(735				s,736				*padding,737				#[cfg(feature = "exp-preserve-order")]738				*preserve_order,739			)?,740			ManifestFormat::Json {741				padding,742				#[cfg(feature = "exp-preserve-order")]743				preserve_order,744			} => self.to_json(745				s,746				*padding,747				#[cfg(feature = "exp-preserve-order")]748				*preserve_order,749			)?,750			ManifestFormat::ToString => self.to_string(s)?,751			ManifestFormat::String => match self {752				Self::Str(s) => s.clone(),753				_ => throw!(StringManifestOutputIsNotAString),754			},755		})756	}757758	/// For manifestification759	pub fn to_json(760		&self,761		s: State,762		padding: usize,763		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,764	) -> Result<IStr> {765		manifest_json_ex(766			s,767			self,768			&ManifestJsonOptions {769				padding: &" ".repeat(padding),770				mtype: if padding == 0 {771					ManifestType::Minify772				} else {773					ManifestType::Manifest774				},775				newline: "\n",776				key_val_sep: ": ",777				#[cfg(feature = "exp-preserve-order")]778				preserve_order,779			},780		)781		.map(Into::into)782	}783784	/// Calls `std.manifestJson`785	pub fn to_std_json(786		&self,787		s: State,788		padding: usize,789		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,790	) -> Result<Rc<str>> {791		manifest_json_ex(792			s,793			self,794			&ManifestJsonOptions {795				padding: &" ".repeat(padding),796				mtype: ManifestType::Std,797				newline: "\n",798				key_val_sep: ": ",799				#[cfg(feature = "exp-preserve-order")]800				preserve_order,801			},802		)803		.map(Into::into)804	}805806	pub fn to_yaml(807		&self,808		s: State,809		padding: usize,810		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,811	) -> Result<IStr> {812		let padding = &" ".repeat(padding);813		manifest_yaml_ex(814			s,815			self,816			&ManifestYamlOptions {817				padding,818				arr_element_padding: padding,819				quote_keys: false,820				#[cfg(feature = "exp-preserve-order")]821				preserve_order,822			},823		)824		.map(Into::into)825	}826	pub fn into_indexable(self) -> Result<IndexableVal> {827		Ok(match self {828			Val::Str(s) => IndexableVal::Str(s),829			Val::Arr(arr) => IndexableVal::Arr(arr),830			_ => throw!(ValueIsNotIndexable(self.value_type())),831		})832	}833}834835const fn is_function_like(val: &Val) -> bool {836	matches!(val, Val::Func(_))837}838839/// Native implementation of `std.primitiveEquals`840pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {841	Ok(match (val_a, val_b) {842		(Val::Bool(a), Val::Bool(b)) => a == b,843		(Val::Null, Val::Null) => true,844		(Val::Str(a), Val::Str(b)) => a == b,845		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,846		(Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(847			"primitiveEquals operates on primitive types, got array".into(),848		)),849		(Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(850			"primitiveEquals operates on primitive types, got object".into(),851		)),852		(a, b) if is_function_like(a) && is_function_like(b) => {853			throw!(RuntimeError("cannot test equality of functions".into()))854		}855		(_, _) => false,856	})857}858859/// Native implementation of `std.equals`860pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {861	if val_a.value_type() != val_b.value_type() {862		return Ok(false);863	}864	match (val_a, val_b) {865		(Val::Arr(a), Val::Arr(b)) => {866			if ArrValue::ptr_eq(a, b) {867				return Ok(true);868			}869			if a.len() != b.len() {870				return Ok(false);871			}872			for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {873				if !equals(s.clone(), &a?, &b?)? {874					return Ok(false);875				}876			}877			Ok(true)878		}879		(Val::Obj(a), Val::Obj(b)) => {880			if ObjValue::ptr_eq(a, b) {881				return Ok(true);882			}883			let fields = a.fields(884				#[cfg(feature = "exp-preserve-order")]885				false,886			);887			if fields888				!= b.fields(889					#[cfg(feature = "exp-preserve-order")]890					false,891				) {892				return Ok(false);893			}894			for field in fields {895				if !equals(896					s.clone(),897					&a.get(s.clone(), field.clone())?.expect("field exists"),898					&b.get(s.clone(), field)?.expect("field exists"),899				)? {900					return Ok(false);901				}902			}903			Ok(true)904		}905		(a, b) => Ok(primitive_equals(a, b)?),906	}907}
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -52,91 +52,88 @@
 	builder.with_super(eval);
 
 	for (name, builtin) in [
-		("length".into(), builtin_length::INST),
+		("length", builtin_length::INST),
 		// Types
-		("type".into(), builtin_type::INST),
-		("isString".into(), builtin_is_string::INST),
-		("isNumber".into(), builtin_is_number::INST),
-		("isBoolean".into(), builtin_is_boolean::INST),
-		("isObject".into(), builtin_is_object::INST),
-		("isArray".into(), builtin_is_array::INST),
-		("isFunction".into(), builtin_is_function::INST),
+		("type", builtin_type::INST),
+		("isString", builtin_is_string::INST),
+		("isNumber", builtin_is_number::INST),
+		("isBoolean", builtin_is_boolean::INST),
+		("isObject", builtin_is_object::INST),
+		("isArray", builtin_is_array::INST),
+		("isFunction", builtin_is_function::INST),
 		// Arrays
-		("makeArray".into(), builtin_make_array::INST),
-		("slice".into(), builtin_slice::INST),
-		("map".into(), builtin_map::INST),
-		("flatMap".into(), builtin_flatmap::INST),
-		("filter".into(), builtin_filter::INST),
-		("foldl".into(), builtin_foldl::INST),
-		("foldr".into(), builtin_foldr::INST),
-		("range".into(), builtin_range::INST),
-		("join".into(), builtin_join::INST),
-		("reverse".into(), builtin_reverse::INST),
-		("any".into(), builtin_any::INST),
-		("all".into(), builtin_all::INST),
-		("member".into(), builtin_member::INST),
-		("count".into(), builtin_count::INST),
+		("makeArray", builtin_make_array::INST),
+		("slice", builtin_slice::INST),
+		("map", builtin_map::INST),
+		("flatMap", builtin_flatmap::INST),
+		("filter", builtin_filter::INST),
+		("foldl", builtin_foldl::INST),
+		("foldr", builtin_foldr::INST),
+		("range", builtin_range::INST),
+		("join", builtin_join::INST),
+		("reverse", builtin_reverse::INST),
+		("any", builtin_any::INST),
+		("all", builtin_all::INST),
+		("member", builtin_member::INST),
+		("count", builtin_count::INST),
 		// Math
-		("modulo".into(), builtin_modulo::INST),
-		("floor".into(), builtin_floor::INST),
-		("ceil".into(), builtin_ceil::INST),
-		("log".into(), builtin_log::INST),
-		("pow".into(), builtin_pow::INST),
-		("sqrt".into(), builtin_sqrt::INST),
-		("sin".into(), builtin_sin::INST),
-		("cos".into(), builtin_cos::INST),
-		("tan".into(), builtin_tan::INST),
-		("asin".into(), builtin_asin::INST),
-		("acos".into(), builtin_acos::INST),
-		("atan".into(), builtin_atan::INST),
-		("exp".into(), builtin_exp::INST),
-		("mantissa".into(), builtin_mantissa::INST),
-		("exponent".into(), builtin_exponent::INST),
+		("modulo", builtin_modulo::INST),
+		("floor", builtin_floor::INST),
+		("ceil", builtin_ceil::INST),
+		("log", builtin_log::INST),
+		("pow", builtin_pow::INST),
+		("sqrt", builtin_sqrt::INST),
+		("sin", builtin_sin::INST),
+		("cos", builtin_cos::INST),
+		("tan", builtin_tan::INST),
+		("asin", builtin_asin::INST),
+		("acos", builtin_acos::INST),
+		("atan", builtin_atan::INST),
+		("exp", builtin_exp::INST),
+		("mantissa", builtin_mantissa::INST),
+		("exponent", builtin_exponent::INST),
 		// Operator
-		("mod".into(), builtin_mod::INST),
-		("primitiveEquals".into(), builtin_primitive_equals::INST),
-		("equals".into(), builtin_equals::INST),
-		("format".into(), builtin_format::INST),
+		("mod", builtin_mod::INST),
+		("primitiveEquals", builtin_primitive_equals::INST),
+		("equals", builtin_equals::INST),
+		("format", builtin_format::INST),
 		// Sort
-		("sort".into(), builtin_sort::INST),
+		("sort", builtin_sort::INST),
 		// Hash
-		("md5".into(), builtin_md5::INST),
+		("md5", builtin_md5::INST),
 		// Encoding
-		("encodeUTF8".into(), builtin_encode_utf8::INST),
-		("decodeUTF8".into(), builtin_decode_utf8::INST),
-		("base64".into(), builtin_base64::INST),
-		("base64Decode".into(), builtin_base64_decode::INST),
-		(
-			"base64DecodeBytes".into(),
-			builtin_base64_decode_bytes::INST,
-		),
+		("encodeUTF8", builtin_encode_utf8::INST),
+		("decodeUTF8", builtin_decode_utf8::INST),
+		("base64", builtin_base64::INST),
+		("base64Decode", builtin_base64_decode::INST),
+		("base64DecodeBytes", builtin_base64_decode_bytes::INST),
 		// Objects
-		("objectFieldsEx".into(), builtin_object_fields_ex::INST),
-		("objectHasEx".into(), builtin_object_has_ex::INST),
+		("objectFieldsEx", builtin_object_fields_ex::INST),
+		("objectHasEx", builtin_object_has_ex::INST),
 		// Manifest
-		("escapeStringJson".into(), builtin_escape_string_json::INST),
-		("manifestJsonEx".into(), builtin_manifest_json_ex::INST),
-		("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),
+		("escapeStringJson", builtin_escape_string_json::INST),
+		("manifestJsonEx", builtin_manifest_json_ex::INST),
+		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),
 		// Parsing
-		("parseJson".into(), builtin_parse_json::INST),
-		("parseYaml".into(), builtin_parse_yaml::INST),
+		("parseJson", builtin_parse_json::INST),
+		("parseYaml", builtin_parse_yaml::INST),
 		// Misc
-		("codepoint".into(), builtin_codepoint::INST),
-		("substr".into(), builtin_substr::INST),
-		("char".into(), builtin_char::INST),
-		("strReplace".into(), builtin_str_replace::INST),
-		("splitLimit".into(), builtin_splitlimit::INST),
-		("asciiUpper".into(), builtin_ascii_upper::INST),
-		("asciiLower".into(), builtin_ascii_lower::INST),
-		("findSubstr".into(), builtin_find_substr::INST),
-		("startsWith".into(), builtin_starts_with::INST),
-		("endsWith".into(), builtin_ends_with::INST),
+		("codepoint", builtin_codepoint::INST),
+		("substr", builtin_substr::INST),
+		("char", builtin_char::INST),
+		("strReplace", builtin_str_replace::INST),
+		("splitLimit", builtin_splitlimit::INST),
+		("asciiUpper", builtin_ascii_upper::INST),
+		("asciiLower", builtin_ascii_lower::INST),
+		("findSubstr", builtin_find_substr::INST),
+		("startsWith", builtin_starts_with::INST),
+		("endsWith", builtin_ends_with::INST),
 	]
 	.iter()
 	.cloned()
 	{
 		builder
-			.member(name)
+			.member(name.into())
 			.hide()
 			.value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))
 			.expect("no conflict");
modifiedtests/src/lib.rsdiffbeforeafterboth
--- a/tests/src/lib.rs
+++ b/tests/src/lib.rs
@@ -1 +1 @@
-
+//! See tests/, suite/ and golden/ directories for tests