git.delta.rocks / jrsonnet / refs/commits / 6d7ca685fe74

difftreelog

refactor(stdlib) implement as a standalone crate

Yaroslav Bolyukin2022-07-23parent: #ab6ba99.patch.diff
in: master
New builtins system allows to split standard library to standalone crate

16 files changed

modifiedcrates/jrsonnet-stdlib/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/Cargo.toml
+++ b/crates/jrsonnet-stdlib/Cargo.toml
@@ -7,5 +7,46 @@
 edition = "2021"
 
 [features]
+default = []
+# Serializes standard library AST, and deserialize on start, instead of parsing it every run from text
+serialized-stdlib = ["bincode", "jrsonnet-parser/serde"]
+# Enables legacy `std.thisFile` support, at the cost of worse caching
+legacy-this-file = []
+# Add order preservation flag to some functions
+exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
+# Preserve order for files parsed via `std.parseJson`
+# Shame it isn't possible to enable per parse call, instead of globally
+exp-serde-preserve-order = [
+    "serde_json/preserve_order",
+    "jrsonnet-evaluator/exp-serde-preserve-order",
+]
 
 [dependencies]
+jrsonnet-evaluator = { path = "../jrsonnet-evaluator", features = [
+    # std.parseJson parses file via serde, then converts Value to evaluator Val
+    "serde_json",
+], version = "0.4.2" }
+jrsonnet-macros = { path = "../jrsonnet-macros", version = "0.4.2" }
+jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2" }
+jrsonnet-gcmodule = "0.3.4"
+
+# Used for stdlib AST serialization
+bincode = { version = "1.3", optional = true }
+# Used both for stdlib AST serialization and std.parseJson/std.parseYaml
+serde = "1.0"
+
+# std.md5
+md5 = "0.7.0"
+# std.base64
+base64 = "0.13.0"
+# std.parseJson
+serde_json = "1.0"
+# std.parseYaml, custom library fork is used for C++/golang compatibility
+serde_yaml_with_quirks = "0.8.24"
+
+[build-dependencies]
+jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2", features = [
+    "serde",
+] }
+serde = "1.0"
+bincode = "1.3"
deletedcrates/jrsonnet-stdlib/README.mddiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# jrsonnet-stdlib
-
-Jsonnet standard library packaged as crate
addedcrates/jrsonnet-stdlib/build.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/build.rs
@@ -0,0 +1,21 @@
+use std::{borrow::Cow, env, fs::File, io::Write, path::Path};
+
+use bincode::serialize;
+use jrsonnet_parser::{parse, ParserSettings, Source};
+
+fn main() {
+	let parsed = parse(
+		include_str!("./src/std.jsonnet"),
+		&ParserSettings {
+			file_name: Source::new_virtual(Cow::Borrowed("<std>")),
+		},
+	)
+	.expect("parse");
+
+	{
+		let out_dir = env::var("OUT_DIR").unwrap();
+		let dest_path = Path::new(&out_dir).join("stdlib.bincode");
+		let mut f = File::create(&dest_path).unwrap();
+		f.write_all(&serialize(&parsed).unwrap()).unwrap();
+	}
+}
addedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -0,0 +1,216 @@
+use jrsonnet_evaluator::{
+	error::Result,
+	function::{builtin, FuncVal},
+	throw_runtime,
+	typed::{Any, BoundedUsize, Typed, VecVal},
+	val::{equals, ArrValue, IndexableVal},
+	IStr, State, Val,
+};
+use jrsonnet_gcmodule::Cc;
+
+#[builtin]
+pub fn builtin_make_array(s: State, sz: usize, func: FuncVal) -> Result<VecVal> {
+	let mut out = Vec::with_capacity(sz);
+	for i in 0..sz {
+		out.push(func.evaluate_simple(s.clone(), &(i as f64,))?);
+	}
+	Ok(VecVal(Cc::new(out)))
+}
+
+#[builtin]
+pub fn builtin_slice(
+	indexable: IndexableVal,
+	index: Option<BoundedUsize<0, { i32::MAX as usize }>>,
+	end: Option<BoundedUsize<0, { i32::MAX as usize }>>,
+	step: Option<BoundedUsize<1, { i32::MAX as usize }>>,
+) -> Result<Any> {
+	indexable.slice(index, end, step).map(Val::from).map(Any)
+}
+
+#[builtin]
+pub fn builtin_map(s: State, func: FuncVal, arr: ArrValue) -> Result<ArrValue> {
+	arr.map(s.clone(), |val| {
+		func.evaluate_simple(s.clone(), &(Any(val),))
+	})
+}
+
+#[builtin]
+pub fn builtin_flatmap(s: State, func: FuncVal, arr: IndexableVal) -> Result<IndexableVal> {
+	match arr {
+		IndexableVal::Str(str) => {
+			let mut out = String::new();
+			for c in str.chars() {
+				match func.evaluate_simple(s.clone(), &(c.to_string(),))? {
+					Val::Str(o) => out.push_str(&o),
+					Val::Null => continue,
+					_ => throw_runtime!("in std.join all items should be strings"),
+				};
+			}
+			Ok(IndexableVal::Str(out.into()))
+		}
+		IndexableVal::Arr(a) => {
+			let mut out = Vec::new();
+			for el in a.iter(s.clone()) {
+				let el = el?;
+				match func.evaluate_simple(s.clone(), &(Any(el),))? {
+					Val::Arr(o) => {
+						for oe in o.iter(s.clone()) {
+							out.push(oe?);
+						}
+					}
+					Val::Null => continue,
+					_ => throw_runtime!("in std.join all items should be arrays"),
+				};
+			}
+			Ok(IndexableVal::Arr(out.into()))
+		}
+	}
+}
+
+#[builtin]
+pub fn builtin_filter(s: State, func: FuncVal, arr: ArrValue) -> Result<ArrValue> {
+	arr.filter(s.clone(), |val| {
+		bool::from_untyped(
+			func.evaluate_simple(s.clone(), &(Any(val.clone()),))?,
+			s.clone(),
+		)
+	})
+}
+
+#[builtin]
+pub fn builtin_foldl(s: State, func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {
+	let mut acc = init.0;
+	for i in arr.iter(s.clone()) {
+		acc = func.evaluate_simple(s.clone(), &(Any(acc), Any(i?)))?;
+	}
+	Ok(Any(acc))
+}
+
+#[builtin]
+pub fn builtin_foldr(s: State, func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {
+	let mut acc = init.0;
+	for i in arr.iter(s.clone()).rev() {
+		acc = func.evaluate_simple(s.clone(), &(Any(i?), Any(acc)))?;
+	}
+	Ok(Any(acc))
+}
+
+#[builtin]
+pub fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {
+	if to < from {
+		return Ok(ArrValue::new_eager());
+	}
+	Ok(ArrValue::new_range(from, to))
+}
+
+#[builtin]
+pub fn builtin_join(s: State, sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {
+	Ok(match sep {
+		IndexableVal::Arr(joiner_items) => {
+			let mut out = Vec::new();
+
+			let mut first = true;
+			for item in arr.iter(s.clone()) {
+				let item = item?.clone();
+				if let Val::Arr(items) = item {
+					if !first {
+						out.reserve(joiner_items.len());
+						// TODO: extend
+						for item in joiner_items.iter(s.clone()) {
+							out.push(item?);
+						}
+					}
+					first = false;
+					out.reserve(items.len());
+					for item in items.iter(s.clone()) {
+						out.push(item?);
+					}
+				} else if matches!(item, Val::Null) {
+					continue;
+				} else {
+					throw_runtime!("in std.join all items should be arrays");
+				}
+			}
+
+			IndexableVal::Arr(out.into())
+		}
+		IndexableVal::Str(sep) => {
+			let mut out = String::new();
+
+			let mut first = true;
+			for item in arr.iter(s) {
+				let item = item?.clone();
+				if let Val::Str(item) = item {
+					if !first {
+						out += &sep;
+					}
+					first = false;
+					out += &item;
+				} else if matches!(item, Val::Null) {
+					continue;
+				} else {
+					throw_runtime!("in std.join all items should be strings");
+				}
+			}
+
+			IndexableVal::Str(out.into())
+		}
+	})
+}
+
+#[builtin]
+pub fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {
+	Ok(value.reversed())
+}
+
+#[builtin]
+pub fn builtin_any(s: State, arr: ArrValue) -> Result<bool> {
+	for v in arr.iter(s.clone()) {
+		let v = bool::from_untyped(v?, s.clone())?;
+		if v {
+			return Ok(true);
+		}
+	}
+	Ok(false)
+}
+
+#[builtin]
+pub fn builtin_all(s: State, arr: ArrValue) -> Result<bool> {
+	for v in arr.iter(s.clone()) {
+		let v = bool::from_untyped(v?, s.clone())?;
+		if !v {
+			return Ok(false);
+		}
+	}
+	Ok(true)
+}
+
+#[builtin]
+pub fn builtin_member(s: State, arr: IndexableVal, x: Any) -> Result<bool> {
+	match arr {
+		IndexableVal::Str(str) => {
+			let x: IStr = IStr::from_untyped(x.0, s)?;
+			Ok(!x.is_empty() && str.contains(&*x))
+		}
+		IndexableVal::Arr(a) => {
+			for item in a.iter(s.clone()) {
+				let item = item?;
+				if equals(s.clone(), &item, &x.0)? {
+					return Ok(true);
+				}
+			}
+			Ok(false)
+		}
+	}
+}
+
+#[builtin]
+pub fn builtin_count(s: State, arr: Vec<Any>, v: Any) -> Result<usize> {
+	let mut count = 0;
+	for item in &arr {
+		if equals(s.clone(), &item.0, &v.0)? {
+			count += 1;
+		}
+	}
+	Ok(count)
+}
addedcrates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -0,0 +1,41 @@
+use jrsonnet_evaluator::{
+	error::{Error::RuntimeError, Result},
+	function::builtin,
+	typed::{Either, Either2},
+	IBytes, IStr,
+};
+
+#[builtin]
+pub fn builtin_encode_utf8(str: IStr) -> Result<IBytes> {
+	Ok(str.cast_bytes())
+}
+
+#[builtin]
+pub fn builtin_decode_utf8(arr: IBytes) -> Result<IStr> {
+	Ok(arr
+		.cast_str()
+		.ok_or_else(|| RuntimeError("bad utf8".into()))?)
+}
+
+#[builtin]
+pub fn builtin_base64(input: Either![IBytes, IStr]) -> Result<String> {
+	use Either2::*;
+	Ok(match input {
+		A(a) => base64::encode(a.as_slice()),
+		B(l) => base64::encode(l.bytes().collect::<Vec<_>>()),
+	})
+}
+
+#[builtin]
+pub fn builtin_base64_decode_bytes(input: IStr) -> Result<IBytes> {
+	Ok(base64::decode(&input.as_bytes())
+		.map_err(|_| RuntimeError("bad base64".into()))?
+		.as_slice()
+		.into())
+}
+
+#[builtin]
+pub fn builtin_base64_decode(input: IStr) -> Result<String> {
+	let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
+	Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)
+}
addedcrates/jrsonnet-stdlib/src/expr.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/expr.rs
@@ -0,0 +1,22 @@
+use std::borrow::Cow;
+
+use jrsonnet_parser::{LocExpr, ParserSettings, Source};
+
+pub const STDLIB_STR: &str = include_str!("./std.jsonnet");
+
+pub fn stdlib_expr() -> LocExpr {
+	#[cfg(feature = "serialized-stdlib")]
+	{
+		// Should not panic, stdlib.bincode is generated in build.rs
+		return bincode::deserialize(include_bytes!(concat!(env!("OUT_DIR"), "/stdlib.bincode")))
+			.unwrap();
+	}
+
+	jrsonnet_parser::parse(
+		STDLIB_STR,
+		&ParserSettings {
+			file_name: Source::new_virtual(Cow::Borrowed("<std>")),
+		},
+	)
+	.unwrap()
+}
addedcrates/jrsonnet-stdlib/src/hash.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/hash.rs
@@ -0,0 +1,6 @@
+use jrsonnet_evaluator::{error::Result, function::builtin, IStr};
+
+#[builtin]
+pub fn builtin_md5(str: IStr) -> Result<String> {
+	Ok(format!("{:x}", md5::compute(&str.as_bytes())))
+}
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -1 +1,420 @@
-pub const STDLIB_STR: &str = include_str!("./std.jsonnet");
+use std::{
+	borrow::Cow,
+	cell::{Ref, RefCell, RefMut},
+	collections::HashMap,
+	rc::Rc,
+};
+
+use jrsonnet_evaluator::{
+	error::{Error::*, Result},
+	function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},
+	gc::TraceBox,
+	tb,
+	typed::{Any, Either, Either2, Either4, VecVal, M1},
+	val::ArrValue,
+	Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,
+};
+use jrsonnet_gcmodule::Cc;
+use jrsonnet_macros::builtin;
+use jrsonnet_parser::Source;
+
+mod expr;
+mod types;
+pub use types::*;
+mod arrays;
+pub use arrays::*;
+mod math;
+pub use math::*;
+mod operator;
+pub use operator::*;
+mod sort;
+pub use sort::*;
+mod hash;
+pub use hash::*;
+mod encoding;
+pub use encoding::*;
+mod objects;
+pub use objects::*;
+mod manifest;
+pub use manifest::*;
+mod parse;
+pub use parse::*;
+
+pub fn stdlib_uncached(s: State, settings: Rc<RefCell<Settings>>) -> ObjValue {
+	let mut builder = ObjValueBuilder::new();
+
+	let expr = expr::stdlib_expr();
+	let eval = jrsonnet_evaluator::evaluate(s.clone(), Context::default(), &expr)
+		.expect("stdlib.jsonnet should have no errors")
+		.as_obj()
+		.expect("stdlib.jsonnet should evaluate to object");
+
+	builder.with_super(eval);
+
+	for (name, builtin) in [
+		("length".into(), 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),
+		// 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),
+		// 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),
+		// Operator
+		("mod".into(), builtin_mod::INST),
+		("primitiveEquals".into(), builtin_primitive_equals::INST),
+		("equals".into(), builtin_equals::INST),
+		("format".into(), builtin_format::INST),
+		// Sort
+		("sort".into(), builtin_sort::INST),
+		// Hash
+		("md5".into(), 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,
+		),
+		// Objects
+		("objectFieldsEx".into(), builtin_object_fields_ex::INST),
+		("objectHasEx".into(), 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),
+		// Parsing
+		("parseJson".into(), builtin_parse_json::INST),
+		("parseYaml".into(), 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),
+	]
+	.iter()
+	.cloned()
+	{
+		builder
+			.member(name)
+			.hide()
+			.value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))
+			.expect("no conflict");
+	}
+
+	builder
+		.member("extVar".into())
+		.hide()
+		.value(
+			s.clone(),
+			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {
+				settings: settings.clone()
+			})))),
+		)
+		.expect("no conflict");
+	builder
+		.member("native".into())
+		.hide()
+		.value(
+			s.clone(),
+			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {
+				settings: settings.clone()
+			})))),
+		)
+		.expect("no conflict");
+	builder
+		.member("trace".into())
+		.hide()
+		.value(
+			s.clone(),
+			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace { settings })))),
+		)
+		.expect("no conflict");
+
+	builder
+		.member("id".into())
+		.hide()
+		.value(s, Val::Func(FuncVal::Id))
+		.expect("no conflict");
+
+	builder.build()
+}
+
+pub trait TracePrinter {
+	fn print_trace(&self, s: State, loc: CallLocation, value: IStr);
+}
+
+pub struct StdTracePrinter;
+impl TracePrinter for StdTracePrinter {
+	fn print_trace(&self, s: State, loc: CallLocation, value: IStr) {
+		eprint!("TRACE:");
+		if let Some(loc) = loc.0 {
+			let locs = s.map_source_locations(loc.0.clone(), &[loc.1]);
+			eprint!(" {}:{}", loc.0.short_display(), locs[0].line);
+		}
+		eprintln!(" {}", value);
+	}
+}
+
+pub struct Settings {
+	/// Used for `std.extVar`
+	pub ext_vars: HashMap<IStr, TlaArg>,
+	/// Used for `std.native`
+	pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,
+	/// Used for `std.trace`
+	pub trace_printer: Box<dyn TracePrinter>,
+}
+
+impl Default for Settings {
+	fn default() -> Self {
+		Self {
+			ext_vars: Default::default(),
+			ext_natives: Default::default(),
+			trace_printer: Box::new(StdTracePrinter),
+		}
+	}
+}
+
+pub fn extvar_source(name: &str) -> Source {
+	let source_name = format!("<extvar:{}>", name);
+	Source::new_virtual(Cow::Owned(source_name))
+}
+
+pub struct ContextInitializer {
+	// When we don't need to support legacy-this-file, we can reuse same context for all files
+	#[cfg(not(feature = "legacy-this-file"))]
+	context: Context,
+	// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it
+	#[cfg(feature = "legacy-this-file")]
+	stdlib_obj: ObjValue,
+	settings: Rc<RefCell<Settings>>,
+}
+impl ContextInitializer {
+	pub fn new(s: State) -> Self {
+		let settings = Rc::new(RefCell::new(Settings::default()));
+		Self {
+			#[cfg(not(feature = "legacy-this-file"))]
+			context: {
+				let mut context = ContextBuilder::with_capacity(1);
+				context.bind(
+					"std".into(),
+					Thunk::evaluated(Val::Obj(stdlib_uncached(s, settings.clone()))),
+				);
+				context.build()
+			},
+			#[cfg(feature = "legacy-this-file")]
+			stdlib_obj: stdlib_uncached(s, settings.clone()),
+			settings,
+		}
+	}
+	pub fn settings(&self) -> Ref<Settings> {
+		self.settings.borrow()
+	}
+	pub fn settings_mut(&self) -> RefMut<Settings> {
+		self.settings.borrow_mut()
+	}
+	pub fn add_ext_var(&self, name: IStr, value: Val) {
+		self.settings_mut()
+			.ext_vars
+			.insert(name, TlaArg::Val(value));
+	}
+	pub fn add_ext_str(&self, name: IStr, value: IStr) {
+		self.settings_mut()
+			.ext_vars
+			.insert(name, TlaArg::String(value));
+	}
+	pub fn add_ext_code(&self, name: &str, code: String) -> Result<()> {
+		let source = extvar_source(name);
+		let parsed = jrsonnet_parser::parse(
+			&code,
+			&jrsonnet_parser::ParserSettings {
+				file_name: source.clone(),
+			},
+		)
+		.map_err(|e| ImportSyntaxError {
+			path: source,
+			source_code: code.clone().into(),
+			error: Box::new(e),
+		})?;
+		// self.data_mut().volatile_files.insert(source_name, code);
+		self.settings_mut()
+			.ext_vars
+			.insert(name.into(), TlaArg::Code(parsed));
+		Ok(())
+	}
+	pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {
+		self.settings_mut().ext_natives.insert(name, cb);
+	}
+}
+impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {
+	#[cfg(not(feature = "legacy-this-file"))]
+	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {
+		self.context.clone()
+	}
+	#[cfg(feature = "legacy-this-file")]
+	fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {
+		let mut builder = ObjValueBuilder::new();
+		builder.with_super(self.stdlib_obj.clone());
+		builder
+			.member("thisFile".into())
+			.hide()
+			.value(
+				s,
+				Val::Str(match source.repr() {
+					Ok(p) => p.display().to_string().into(),
+					// Virtual files end up as empty strings in std.thisFile
+					Err(_e) => "".into(),
+				}),
+			)
+			.expect("this object builder is empty");
+		let stdlib_with_this_file = builder.build();
+
+		let mut context = ContextBuilder::with_capacity(1);
+		context.bind(
+			"std".into(),
+			Thunk::evaluated(Val::Obj(stdlib_with_this_file)),
+		);
+		context.build()
+	}
+	unsafe fn as_any(&self) -> &dyn std::any::Any {
+		self
+	}
+}
+
+#[builtin]
+fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {
+	use Either4::*;
+	Ok(match x {
+		A(x) => x.chars().count(),
+		B(x) => x.len(),
+		C(x) => x.len(),
+		D(f) => f.params_len(),
+	})
+}
+
+#[builtin]
+const fn builtin_codepoint(str: char) -> Result<u32> {
+	Ok(str as u32)
+}
+
+#[builtin]
+fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {
+	Ok(str.chars().skip(from as usize).take(len as usize).collect())
+}
+
+#[builtin(fields(
+	settings: Rc<RefCell<Settings>>,
+))]
+fn builtin_ext_var(this: &builtin_ext_var, s: State, x: IStr) -> Result<Any> {
+	let ctx = s.create_default_context(extvar_source(&x));
+	Ok(Any(this
+		.settings
+		.borrow()
+		.ext_vars
+		.get(&x)
+		.cloned()
+		.ok_or(UndefinedExternalVariable(x))?
+		.evaluate_arg(s.clone(), ctx, true)?
+		.evaluate(s)?))
+}
+
+#[builtin(fields(
+	settings: Rc<RefCell<Settings>>,
+))]
+fn builtin_native(this: &builtin_native, name: IStr) -> Result<Any> {
+	Ok(Any(this
+		.settings
+		.borrow()
+		.ext_natives
+		.get(&name)
+		.cloned()
+		.map_or(Val::Null, |v| {
+			Val::Func(FuncVal::Builtin(v.clone()))
+		})))
+}
+
+#[builtin]
+fn builtin_char(n: u32) -> Result<char> {
+	Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)
+}
+
+#[builtin(fields(
+	settings: Rc<RefCell<Settings>>,
+))]
+fn builtin_trace(
+	this: &builtin_trace,
+	s: State,
+	loc: CallLocation,
+	str: IStr,
+	rest: Any,
+) -> Result<Any> {
+	this.settings
+		.borrow()
+		.trace_printer
+		.print_trace(s, loc, str);
+	Ok(rest) as Result<Any>
+}
+
+#[builtin]
+fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {
+	Ok(str.replace(&from as &str, &to as &str))
+}
+
+#[builtin]
+fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {
+	use Either2::*;
+	Ok(VecVal(Cc::new(match maxsplits {
+		A(n) => str
+			.splitn(n + 1, &c as &str)
+			.map(|s| Val::Str(s.into()))
+			.collect(),
+		B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),
+	})))
+}
+
+#[builtin]
+fn builtin_ascii_upper(str: IStr) -> Result<String> {
+	Ok(str.to_ascii_uppercase())
+}
+
+#[builtin]
+fn builtin_ascii_lower(str: IStr) -> Result<String> {
+	Ok(str.to_ascii_lowercase())
+}
addedcrates/jrsonnet-stdlib/src/manifest.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/manifest.rs
@@ -0,0 +1,65 @@
+use jrsonnet_evaluator::{
+	error::Result,
+	function::builtin,
+	stdlib::manifest::{
+		escape_string_json, manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType,
+		ManifestYamlOptions,
+	},
+	typed::Any,
+	IStr, State,
+};
+
+#[builtin]
+pub fn builtin_escape_string_json(str_: IStr) -> Result<String> {
+	Ok(escape_string_json(&str_))
+}
+
+#[builtin]
+pub fn builtin_manifest_json_ex(
+	s: State,
+	value: Any,
+	indent: IStr,
+	newline: Option<IStr>,
+	key_val_sep: Option<IStr>,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> Result<String> {
+	let newline = newline.as_deref().unwrap_or("\n");
+	let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");
+	manifest_json_ex(
+		s,
+		&value.0,
+		&ManifestJsonOptions {
+			padding: &indent,
+			mtype: ManifestType::Std,
+			newline,
+			key_val_sep,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order: preserve_order.unwrap_or(false),
+		},
+	)
+}
+
+#[builtin]
+pub fn builtin_manifest_yaml_doc(
+	s: State,
+	value: Any,
+	indent_array_in_object: Option<bool>,
+	quote_keys: Option<bool>,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> Result<String> {
+	manifest_yaml_ex(
+		s,
+		&value.0,
+		&ManifestYamlOptions {
+			padding: "  ",
+			arr_element_padding: if indent_array_in_object.unwrap_or(false) {
+				"  "
+			} else {
+				""
+			},
+			quote_keys: quote_keys.unwrap_or(true),
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order: preserve_order.unwrap_or(false),
+		},
+	)
+}
addedcrates/jrsonnet-stdlib/src/math.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/math.rs
@@ -0,0 +1,87 @@
+use jrsonnet_evaluator::{error::Result, function::builtin, typed::PositiveF64};
+
+#[builtin]
+pub fn builtin_modulo(a: f64, b: f64) -> Result<f64> {
+	Ok(a % b)
+}
+
+#[builtin]
+pub fn builtin_floor(x: f64) -> Result<f64> {
+	Ok(x.floor())
+}
+
+#[builtin]
+pub fn builtin_ceil(x: f64) -> Result<f64> {
+	Ok(x.ceil())
+}
+
+#[builtin]
+pub fn builtin_log(n: f64) -> Result<f64> {
+	Ok(n.ln())
+}
+
+#[builtin]
+pub fn builtin_pow(x: f64, n: f64) -> Result<f64> {
+	Ok(x.powf(n))
+}
+
+#[builtin]
+pub fn builtin_sqrt(x: PositiveF64) -> Result<f64> {
+	Ok(x.0.sqrt())
+}
+
+#[builtin]
+pub fn builtin_sin(x: f64) -> Result<f64> {
+	Ok(x.sin())
+}
+
+#[builtin]
+pub fn builtin_cos(x: f64) -> Result<f64> {
+	Ok(x.cos())
+}
+
+#[builtin]
+pub fn builtin_tan(x: f64) -> Result<f64> {
+	Ok(x.tan())
+}
+
+#[builtin]
+pub fn builtin_asin(x: f64) -> Result<f64> {
+	Ok(x.asin())
+}
+
+#[builtin]
+pub fn builtin_acos(x: f64) -> Result<f64> {
+	Ok(x.acos())
+}
+
+#[builtin]
+pub fn builtin_atan(x: f64) -> Result<f64> {
+	Ok(x.atan())
+}
+
+#[builtin]
+pub fn builtin_exp(x: f64) -> Result<f64> {
+	Ok(x.exp())
+}
+
+fn frexp(s: f64) -> (f64, i16) {
+	if 0.0 == s {
+		(s, 0)
+	} else {
+		let lg = s.abs().log2();
+		let x = (lg - lg.floor() - 1.0).exp2();
+		let exp = lg.floor() + 1.0;
+		(s.signum() * x, exp as i16)
+	}
+}
+
+#[builtin]
+pub fn builtin_mantissa(x: f64) -> Result<f64> {
+	Ok(frexp(x).0)
+}
+
+#[builtin]
+pub fn builtin_exponent(x: f64) -> Result<i16> {
+	Ok(frexp(x).1)
+}
addedcrates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -0,0 +1,27 @@
+use jrsonnet_evaluator::{
+	error::Result, function::builtin, typed::VecVal, val::Val, IStr, ObjValue,
+};
+use jrsonnet_gcmodule::Cc;
+
+#[builtin]
+pub fn builtin_object_fields_ex(
+	obj: ObjValue,
+	inc_hidden: bool,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> Result<VecVal> {
+	#[cfg(feature = "exp-preserve-order")]
+	let preserve_order = preserve_order.unwrap_or(false);
+	let out = obj.fields_ex(
+		inc_hidden,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	);
+	Ok(VecVal(Cc::new(
+		out.into_iter().map(Val::Str).collect::<Vec<_>>(),
+	)))
+}
+
+#[builtin]
+pub fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {
+	Ok(obj.has_field_ex(f, inc_hidden))
+}
addedcrates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -0,0 +1,40 @@
+//! Some jsonnet operations are desugared to stdlib functions...
+//! However, in our case we instead implement them in native, and implement native functions on top of core for backwards compatibility
+
+use jrsonnet_evaluator::{
+	error::Result,
+	function::builtin,
+	operator::evaluate_mod_op,
+	stdlib::std_format,
+	typed::{Any, Either, Either2},
+	val::{equals, primitive_equals},
+	IStr, State, Val,
+};
+
+#[builtin]
+pub fn builtin_mod(s: State, a: Either![f64, IStr], b: Any) -> Result<Any> {
+	use Either2::*;
+	Ok(Any(evaluate_mod_op(
+		s,
+		&match a {
+			A(v) => Val::Num(v),
+			B(s) => Val::Str(s),
+		},
+		&b.0,
+	)?))
+}
+
+#[builtin]
+pub fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {
+	primitive_equals(&a.0, &b.0)
+}
+
+#[builtin]
+pub fn builtin_equals(s: State, a: Any, b: Any) -> Result<bool> {
+	equals(s, &a.0, &b.0)
+}
+
+#[builtin]
+pub fn builtin_format(s: State, str: IStr, vals: Any) -> Result<String> {
+	std_format(s, str, vals.0)
+}
addedcrates/jrsonnet-stdlib/src/parse.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/parse.rs
@@ -0,0 +1,39 @@
+use jrsonnet_evaluator::{
+	error::{Error::RuntimeError, Result},
+	function::builtin,
+	typed::{Any, Typed},
+	IStr, State, Val,
+};
+use serde::Deserialize;
+
+#[builtin]
+pub fn builtin_parse_json(st: State, s: IStr) -> Result<Any> {
+	use serde_json::Value;
+	let value: Value = serde_json::from_str(&s)
+		.map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;
+	Ok(Any(Value::into_untyped(value, st)?))
+}
+
+#[builtin]
+pub fn builtin_parse_yaml(st: State, s: IStr) -> Result<Any> {
+	use serde_json::Value;
+	use serde_yaml_with_quirks::DeserializingQuirks;
+	let value = serde_yaml_with_quirks::Deserializer::from_str_with_quirks(
+		&s,
+		DeserializingQuirks { old_octals: true },
+	);
+	let mut out = vec![];
+	for item in value {
+		let value = Value::deserialize(item)
+			.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
+		let val = Value::into_untyped(value, st.clone())?;
+		out.push(val);
+	}
+	Ok(Any(if out.is_empty() {
+		Val::Null
+	} else if out.len() == 1 {
+		out.into_iter().next().unwrap()
+	} else {
+		Val::Arr(out.into())
+	}))
+}
addedcrates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -0,0 +1,109 @@
+use jrsonnet_evaluator::{
+	error::Result,
+	function::{builtin, FuncVal},
+	throw_runtime,
+	typed::Any,
+	val::ArrValue,
+	State, Val,
+};
+use jrsonnet_gcmodule::Cc;
+
+#[derive(Copy, Clone)]
+enum SortKeyType {
+	Number,
+	String,
+	Unknown,
+}
+
+#[derive(PartialEq)]
+struct NonNaNf64(f64);
+impl PartialOrd for NonNaNf64 {
+	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+		self.0.partial_cmp(&other.0)
+	}
+}
+impl Eq for NonNaNf64 {}
+impl Ord for NonNaNf64 {
+	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+		self.partial_cmp(other).expect("non nan")
+	}
+}
+
+fn get_sort_type<T>(
+	values: &mut [T],
+	key_getter: impl Fn(&mut T) -> &mut Val,
+) -> Result<SortKeyType> {
+	let mut sort_type = SortKeyType::Unknown;
+	for i in values.iter_mut() {
+		let i = key_getter(i);
+		match (i, sort_type) {
+			(Val::Str(_), SortKeyType::Unknown) => sort_type = SortKeyType::String,
+			(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
+			(Val::Str(_), SortKeyType::String) | (Val::Num(_), SortKeyType::Number) => {}
+			(Val::Str(_) | Val::Num(_), _) => {
+				throw_runtime!("sort elements should have same types")
+			}
+			_ => throw_runtime!("sort key should be string or number"),
+		}
+	}
+	Ok(sort_type)
+}
+
+/// * `key_getter` - None, if identity sort required
+pub fn sort(s: State, values: Cc<Vec<Val>>, key_getter: FuncVal) -> Result<Cc<Vec<Val>>> {
+	if values.len() <= 1 {
+		return Ok(values);
+	}
+	if key_getter.is_identity() {
+		// Fast path, identity key getter
+		let mut values = (*values).clone();
+		let sort_type = get_sort_type(&mut values, |k| k)?;
+		match sort_type {
+			SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
+				Val::Num(n) => NonNaNf64(*n),
+				_ => unreachable!(),
+			}),
+			SortKeyType::String => values.sort_unstable_by_key(|v| match v {
+				Val::Str(s) => s.clone(),
+				_ => unreachable!(),
+			}),
+			SortKeyType::Unknown => unreachable!(),
+		};
+		Ok(Cc::new(values))
+	} else {
+		// Slow path, user provided key getter
+		let mut vk = Vec::with_capacity(values.len());
+		for value in values.iter() {
+			vk.push((
+				value.clone(),
+				key_getter.evaluate_simple(s.clone(), &(Any(value.clone()),))?,
+			));
+		}
+		let sort_type = get_sort_type(&mut vk, |v| &mut v.1)?;
+		match sort_type {
+			SortKeyType::Number => vk.sort_by_key(|v| match v.1 {
+				Val::Num(n) => NonNaNf64(n),
+				_ => unreachable!(),
+			}),
+			SortKeyType::String => vk.sort_by_key(|v| match &v.1 {
+				Val::Str(s) => s.clone(),
+				_ => unreachable!(),
+			}),
+			SortKeyType::Unknown => unreachable!(),
+		};
+		Ok(Cc::new(vk.into_iter().map(|v| v.0).collect()))
+	}
+}
+
+#[builtin]
+#[allow(non_snake_case)]
+pub fn builtin_sort(s: State, arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
+	if arr.len() <= 1 {
+		return Ok(arr);
+	}
+	Ok(ArrValue::Eager(super::sort::sort(
+		s.clone(),
+		arr.evaluated(s)?,
+		keyF.unwrap_or_else(FuncVal::identity),
+	)?))
+}
modifiedcrates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth
after · crates/jrsonnet-stdlib/src/std.jsonnet
1{2  local std = self,3  local id = std.id,45  thisFile:: error 'std.thisFile is deprecated, to enable its support in jrsonnet - recompile it with "legacy-this-file" support. This will slow down stdlib caching a bit, though',67  toString(a)::8    if std.type(a) == 'string' then a else '' + a,910  startsWith(a, b)::11    if std.length(a) < std.length(b) then12      false13    else14      std.substr(a, 0, std.length(b)) == b,1516  endsWith(a, b)::17    if std.length(a) < std.length(b) then18      false19    else20      std.substr(a, std.length(a) - std.length(b), std.length(b)) == b,2122  lstripChars(str, chars)::23    if std.length(str) > 0 && std.member(chars, str[0]) then24      std.lstripChars(str[1:], chars)25    else26      str,2728  rstripChars(str, chars)::29    local len = std.length(str);30    if len > 0 && std.member(chars, str[len - 1]) then31      std.rstripChars(str[:len - 1], chars)32    else33      str,3435  stripChars(str, chars)::36    std.lstripChars(std.rstripChars(str, chars), chars),3738  stringChars(str)::39    std.makeArray(std.length(str), function(i) str[i]),4041  local parse_nat(str, base) =42    assert base > 0 && base <= 16 : 'integer base %d invalid' % base;43    // These codepoints are in ascending order:44    local zero_code = std.codepoint('0');45    local upper_a_code = std.codepoint('A');46    local lower_a_code = std.codepoint('a');47    local addDigit(aggregate, char) =48      local code = std.codepoint(char);49      local digit = if code >= lower_a_code then50        code - lower_a_code + 1051      else if code >= upper_a_code then52        code - upper_a_code + 1053      else54        code - zero_code;55      assert digit >= 0 && digit < base : '%s is not a base %d integer' % [str, base];56      base * aggregate + digit;57    std.foldl(addDigit, std.stringChars(str), 0),5859  parseInt(str)::60    assert std.isString(str) : 'Expected string, got ' + std.type(str);61    assert std.length(str) > 0 && str != '-' : 'Not an integer: "%s"' % [str];62    if str[0] == '-' then63      -parse_nat(str[1:], 10)64    else65      parse_nat(str, 10),6667  parseOctal(str)::68    assert std.isString(str) : 'Expected string, got ' + std.type(str);69    assert std.length(str) > 0 : 'Not an octal number: ""';70    parse_nat(str, 8),7172  parseHex(str)::73    assert std.isString(str) : 'Expected string, got ' + std.type(str);74    assert std.length(str) > 0 : 'Not hexadecimal: ""';75    parse_nat(str, 16),7677  split(str, c):: std.splitLimit(str, c, -1),7879  repeat(what, count)::80    local joiner =81      if std.isString(what) then ''82      else if std.isArray(what) then []83      else error 'std.repeat first argument must be an array or a string';84    std.join(joiner, std.makeArray(count, function(i) what)),8586  mapWithIndex(func, arr)::87    if !std.isFunction(func) then88      error ('std.mapWithIndex first param must be function, got ' + std.type(func))89    else if !std.isArray(arr) && !std.isString(arr) then90      error ('std.mapWithIndex second param must be array, got ' + std.type(arr))91    else92      std.makeArray(std.length(arr), function(i) func(i, arr[i])),9394  mapWithKey(func, obj)::95    if !std.isFunction(func) then96      error ('std.mapWithKey first param must be function, got ' + std.type(func))97    else if !std.isObject(obj) then98      error ('std.mapWithKey second param must be object, got ' + std.type(obj))99    else100      { [k]: func(k, obj[k]) for k in std.objectFields(obj) },101102  lines(arr)::103    std.join('\n', arr + ['']),104105  deepJoin(arr)::106    if std.isString(arr) then107      arr108    else if std.isArray(arr) then109      std.join('', [std.deepJoin(x) for x in arr])110    else111      error 'Expected string or array, got %s' % std.type(arr),112113  filterMap(filter_func, map_func, arr)::114    if !std.isFunction(filter_func) then115      error ('std.filterMap first param must be function, got ' + std.type(filter_func))116    else if !std.isFunction(map_func) then117      error ('std.filterMap second param must be function, got ' + std.type(map_func))118    else if !std.isArray(arr) then119      error ('std.filterMap third param must be array, got ' + std.type(arr))120    else121      std.map(map_func, std.filter(filter_func, arr)),122123  assertEqual(a, b)::124    if a == b then125      true126    else127      error 'Assertion failed. ' + a + ' != ' + b,128129  abs(n)::130    if !std.isNumber(n) then131      error 'std.abs expected number, got ' + std.type(n)132    else133      if n > 0 then n else -n,134135  sign(n)::136    if !std.isNumber(n) then137      error 'std.sign expected number, got ' + std.type(n)138    else139      if n > 0 then140        1141      else if n < 0 then142        -1143      else 0,144145  max(a, b)::146    if !std.isNumber(a) then147      error 'std.max first param expected number, got ' + std.type(a)148    else if !std.isNumber(b) then149      error 'std.max second param expected number, got ' + std.type(b)150    else151      if a > b then a else b,152153  min(a, b)::154    if !std.isNumber(a) then155      error 'std.min first param expected number, got ' + std.type(a)156    else if !std.isNumber(b) then157      error 'std.min second param expected number, got ' + std.type(b)158    else159      if a < b then a else b,160161  clamp(x, minVal, maxVal)::162    if x < minVal then minVal163    else if x > maxVal then maxVal164    else x,165166  flattenArrays(arrs)::167    std.foldl(function(a, b) a + b, arrs, []),168169  manifestIni(ini)::170    local body_lines(body) =171      std.join([], [172        local value_or_values = body[k];173        if std.isArray(value_or_values) then174          ['%s = %s' % [k, value] for value in value_or_values]175        else176          ['%s = %s' % [k, value_or_values]]177178        for k in std.objectFields(body)179      ]);180181    local section_lines(sname, sbody) = ['[%s]' % [sname]] + body_lines(sbody),182          main_body = if std.objectHas(ini, 'main') then body_lines(ini.main) else [],183          all_sections = [184      section_lines(k, ini.sections[k])185      for k in std.objectFields(ini.sections)186    ];187    std.join('\n', main_body + std.flattenArrays(all_sections) + ['']),188189  manifestToml(value):: std.manifestTomlEx(value, '  '),190191  manifestTomlEx(value, indent)::192    local193      escapeStringToml = std.escapeStringJson,194      escapeKeyToml(key) =195        local bare_allowed = std.set(std.stringChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'));196        if std.setUnion(std.set(std.stringChars(key)), bare_allowed) == bare_allowed then key else escapeStringToml(key),197      isTableArray(v) = std.isArray(v) && std.length(v) > 0 && std.foldl(function(a, b) a && std.isObject(b), v, true),198      isSection(v) = std.isObject(v) || isTableArray(v),199      renderValue(v, indexedPath, inline, cindent) =200        if v == true then201          'true'202        else if v == false then203          'false'204        else if v == null then205          error 'Tried to manifest "null" at ' + indexedPath206        else if std.isNumber(v) then207          '' + v208        else if std.isString(v) then209          escapeStringToml(v)210        else if std.isFunction(v) then211          error 'Tried to manifest function at ' + indexedPath212        else if std.isArray(v) then213          if std.length(v) == 0 then214            '[]'215          else216            local range = std.range(0, std.length(v) - 1);217            local new_indent = if inline then '' else cindent + indent;218            local separator = if inline then ' ' else '\n';219            local lines = ['[' + separator]220                          + std.join([',' + separator],221                                     [222                                       [new_indent + renderValue(v[i], indexedPath + [i], true, '')]223                                       for i in range224                                     ])225                          + [separator + (if inline then '' else cindent) + ']'];226            std.join('', lines)227        else if std.isObject(v) then228          local lines = ['{ ']229                        + std.join([', '],230                                   [231                                     [escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], true, '')]232                                     for k in std.objectFields(v)233                                   ])234                        + [' }'];235          std.join('', lines),236      renderTableInternal(v, path, indexedPath, cindent) =237        local kvp = std.flattenArrays([238          [cindent + escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], false, cindent)]239          for k in std.objectFields(v)240          if !isSection(v[k])241        ]);242        local sections = [std.join('\n', kvp)] + [243          (244            if std.isObject(v[k]) then245              renderTable(v[k], path + [k], indexedPath + [k], cindent)246            else247              renderTableArray(v[k], path + [k], indexedPath + [k], cindent)248          )249          for k in std.objectFields(v)250          if isSection(v[k])251        ];252        std.join('\n\n', sections),253      renderTable(v, path, indexedPath, cindent) =254        cindent + '[' + std.join('.', std.map(escapeKeyToml, path)) + ']'255        + (if v == {} then '' else '\n')256        + renderTableInternal(v, path, indexedPath, cindent + indent),257      renderTableArray(v, path, indexedPath, cindent) =258        local range = std.range(0, std.length(v) - 1);259        local sections = [260          (cindent + '[[' + std.join('.', std.map(escapeKeyToml, path)) + ']]'261           + (if v[i] == {} then '' else '\n')262           + renderTableInternal(v[i], path, indexedPath + [i], cindent + indent))263          for i in range264        ];265        std.join('\n\n', sections);266    if std.isObject(value) then267      renderTableInternal(value, [], [], '')268    else269      error 'TOML body must be an object. Got ' + std.type(value),270271  escapeStringPython(str)::272    std.escapeStringJson(str),273274  escapeStringBash(str_)::275    local str = std.toString(str_);276    local trans(ch) =277      if ch == "'" then278        "'\"'\"'"279      else280        ch;281    "'%s'" % std.join('', [trans(ch) for ch in std.stringChars(str)]),282283  escapeStringDollars(str_)::284    local str = std.toString(str_);285    local trans(ch) =286      if ch == '$' then287        '$$'288      else289        ch;290    std.foldl(function(a, b) a + trans(b), std.stringChars(str), ''),291292  manifestJson(value):: std.manifestJsonEx(value, '    ') tailstrict,293294  manifestJsonMinified(value):: std.manifestJsonEx(value, '', '', ':'),295296  manifestYamlStream(value, indent_array_in_object=false, c_document_end=true)::297    if !std.isArray(value) then298      error 'manifestYamlStream only takes arrays, got ' + std.type(value)299    else300      '---\n' + std.join(301        '\n---\n', [std.manifestYamlDoc(e, indent_array_in_object) for e in value]302      ) + if c_document_end then '\n...\n' else '\n',303304305  manifestPython(v)::306    if std.isObject(v) then307      local fields = [308        '%s: %s' % [std.escapeStringPython(k), std.manifestPython(v[k])]309        for k in std.objectFields(v)310      ];311      '{%s}' % [std.join(', ', fields)]312    else if std.isArray(v) then313      '[%s]' % [std.join(', ', [std.manifestPython(v2) for v2 in v])]314    else if std.isString(v) then315      '%s' % [std.escapeStringPython(v)]316    else if std.isFunction(v) then317      error 'cannot manifest function'318    else if std.isNumber(v) then319      std.toString(v)320    else if v == true then321      'True'322    else if v == false then323      'False'324    else if v == null then325      'None',326327  manifestPythonVars(conf)::328    local vars = ['%s = %s' % [k, std.manifestPython(conf[k])] for k in std.objectFields(conf)];329    std.join('\n', vars + ['']),330331  manifestXmlJsonml(value)::332    if !std.isArray(value) then333      error 'Expected a JSONML value (an array), got %s' % std.type(value)334    else335      local aux(v) =336        if std.isString(v) then337          v338        else339          local tag = v[0];340          local has_attrs = std.length(v) > 1 && std.isObject(v[1]);341          local attrs = if has_attrs then v[1] else {};342          local children = if has_attrs then v[2:] else v[1:];343          local attrs_str =344            std.join('', [' %s="%s"' % [k, attrs[k]] for k in std.objectFields(attrs)]);345          std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);346347      aux(value),348349  uniq(arr, keyF=id)::350    local f(a, b) =351      if std.length(a) == 0 then352        [b]353      else if keyF(a[std.length(a) - 1]) == keyF(b) then354        a355      else356        a + [b];357    std.foldl(f, arr, []),358359  set(arr, keyF=id)::360    std.uniq(std.sort(arr, keyF), keyF),361362  setMember(x, arr, keyF=id)::363    // TODO(dcunnin): Binary chop for O(log n) complexity364    std.length(std.setInter([x], arr, keyF)) > 0,365366  setUnion(a, b, keyF=id)::367    // NOTE: order matters, values in `a` win368    local aux(a, b, i, j, acc) =369      if i >= std.length(a) then370        acc + b[j:]371      else if j >= std.length(b) then372        acc + a[i:]373      else374        local ak = keyF(a[i]);375        local bk = keyF(b[j]);376        if ak == bk then377          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict378        else if ak < bk then379          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict380        else381          aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;382    aux(a, b, 0, 0, []),383384  setInter(a, b, keyF=id)::385    local aux(a, b, i, j, acc) =386      if i >= std.length(a) || j >= std.length(b) then387        acc388      else389        if keyF(a[i]) == keyF(b[j]) then390          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict391        else if keyF(a[i]) < keyF(b[j]) then392          aux(a, b, i + 1, j, acc) tailstrict393        else394          aux(a, b, i, j + 1, acc) tailstrict;395    aux(a, b, 0, 0, []) tailstrict,396397  setDiff(a, b, keyF=id)::398    local aux(a, b, i, j, acc) =399      if i >= std.length(a) then400        acc401      else if j >= std.length(b) then402        acc + a[i:]403      else404        if keyF(a[i]) == keyF(b[j]) then405          aux(a, b, i + 1, j + 1, acc) tailstrict406        else if keyF(a[i]) < keyF(b[j]) then407          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict408        else409          aux(a, b, i, j + 1, acc) tailstrict;410    aux(a, b, 0, 0, []) tailstrict,411412  mergePatch(target, patch)::413    if std.isObject(patch) then414      local target_object =415        if std.isObject(target) then target else {};416417      local target_fields =418        if std.isObject(target_object) then std.objectFields(target_object) else [];419420      local null_fields = [k for k in std.objectFields(patch) if patch[k] == null];421      local both_fields = std.setUnion(target_fields, std.objectFields(patch));422423      {424        [k]:425          if !std.objectHas(patch, k) then426            target_object[k]427          else if !std.objectHas(target_object, k) then428            std.mergePatch(null, patch[k]) tailstrict429          else430            std.mergePatch(target_object[k], patch[k]) tailstrict431        for k in std.setDiff(both_fields, null_fields)432      }433    else434      patch,435436  get(o, f, default=null, inc_hidden=true)::437    if std.objectHasEx(o, f, inc_hidden) then o[f] else default,438439  objectFields(o)::440    std.objectFieldsEx(o, false),441442  objectFieldsAll(o)::443    std.objectFieldsEx(o, true),444445  objectHas(o, f)::446    std.objectHasEx(o, f, false),447448  objectHasAll(o, f)::449    std.objectHasEx(o, f, true),450451  objectValues(o)::452    [o[k] for k in std.objectFields(o)],453454  objectValuesAll(o)::455    [o[k] for k in std.objectFieldsAll(o)],456457  resolvePath(f, r)::458    local arr = std.split(f, '/');459    std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),460461  prune(a)::462    local isContent(b) =463      if b == null then464        false465      else if std.isArray(b) then466        std.length(b) > 0467      else if std.isObject(b) then468        std.length(b) > 0469      else470        true;471    if std.isArray(a) then472      [std.prune(x) for x in a if isContent($.prune(x))]473    else if std.isObject(a) then {474      [x]: $.prune(a[x])475      for x in std.objectFields(a)476      if isContent(std.prune(a[x]))477    } else478      a,479480  findSubstr(pat, str)::481    if !std.isString(pat) then482      error 'findSubstr first parameter should be a string, got ' + std.type(pat)483    else if !std.isString(str) then484      error 'findSubstr second parameter should be a string, got ' + std.type(str)485    else486      local pat_len = std.length(pat);487      local str_len = std.length(str);488      if pat_len == 0 || str_len == 0 || pat_len > str_len then489        []490      else491        std.filter(function(i) str[i:i + pat_len] == pat, std.range(0, str_len - pat_len)),492493  find(value, arr)::494    if !std.isArray(arr) then495      error 'find second parameter should be an array, got ' + std.type(arr)496    else497      std.filter(function(i) arr[i] == value, std.range(0, std.length(arr) - 1)),498}
addedcrates/jrsonnet-stdlib/src/types.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/types.rs
@@ -0,0 +1,31 @@
+use jrsonnet_evaluator::{error::Result, function::builtin, typed::Any, IStr, Val};
+
+#[builtin]
+pub fn builtin_type(x: Any) -> Result<IStr> {
+	Ok(x.0.value_type().name().into())
+}
+
+#[builtin]
+pub fn builtin_is_string(x: Any) -> Result<bool> {
+	Ok(matches!(x.0, Val::Str(_)))
+}
+#[builtin]
+pub fn builtin_is_number(x: Any) -> Result<bool> {
+	Ok(matches!(x.0, Val::Num(_)))
+}
+#[builtin]
+pub fn builtin_is_boolean(x: Any) -> Result<bool> {
+	Ok(matches!(x.0, Val::Bool(_)))
+}
+#[builtin]
+pub fn builtin_is_object(x: Any) -> Result<bool> {
+	Ok(matches!(x.0, Val::Obj(_)))
+}
+#[builtin]
+pub fn builtin_is_array(x: Any) -> Result<bool> {
+	Ok(matches!(x.0, Val::Arr(_)))
+}
+#[builtin]
+pub fn builtin_is_function(x: Any) -> Result<bool> {
+	Ok(matches!(x.0, Val::Func(_)))
+}