git.delta.rocks / jrsonnet / refs/commits / 89a650875ae4

difftreelog

perf move more stdlib functions to native

Yaroslav Bolyukin2023-08-13parent: #218d8cc.patch.diff
in: master

7 files changed

modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -103,6 +103,15 @@
 }
 
 #[builtin]
+pub fn builtin_filter_map(
+	filter_func: FuncVal,
+	map_func: FuncVal,
+	arr: ArrValue,
+) -> Result<ArrValue> {
+	Ok(builtin_filter(filter_func, arr)?.map(map_func))
+}
+
+#[builtin]
 pub fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Val) -> Result<Val> {
 	let mut acc = init;
 	for i in arr.iter() {
@@ -274,3 +283,22 @@
 	}
 	Ok(arr)
 }
+
+#[builtin]
+pub fn builtin_flatten_arrays(arrs: Vec<ArrValue>) -> ArrValue {
+	pub fn flatten_inner(values: &[ArrValue]) -> ArrValue {
+		if values.len() == 1 {
+			return values[0].clone();
+		} else if values.len() == 2 {
+			return ArrValue::extended(values[0].clone(), values[1].clone());
+		}
+		let (a, b) = values.split_at(values.len() / 2);
+		ArrValue::extended(flatten_inner(a), flatten_inner(b))
+	}
+	if arrs.is_empty() {
+		return ArrValue::empty();
+	} else if arrs.len() == 1 {
+		return arrs.into_iter().next().expect("single");
+	}
+	flatten_inner(&arrs)
+}
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/lib.rs
1use std::{2	cell::{Ref, RefCell, RefMut},3	collections::HashMap,4	rc::Rc,5};67use jrsonnet_evaluator::{8	error::{ErrorKind::*, Result},9	function::{CallLocation, FuncVal, TlaArg},10	tb,11	trace::PathResolver,12	ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,13};14use jrsonnet_gcmodule::Trace;15use jrsonnet_parser::Source;1617mod expr;18mod types;19pub use types::*;20mod arrays;21pub use arrays::*;22mod math;23pub use math::*;24mod operator;25pub use operator::*;26mod sort;27pub use sort::*;28mod hash;29pub use hash::*;30mod encoding;31pub use encoding::*;32mod objects;33pub use objects::*;34mod manifest;35pub use manifest::*;36mod parse;37pub use parse::*;38mod strings;39pub use strings::*;40mod misc;41pub use misc::*;42mod sets;43pub use sets::*;44mod compat;45pub use compat::*;4647pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {48	let mut builder = ObjValueBuilder::new();4950	let expr = expr::stdlib_expr();51	let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)52		.expect("stdlib.jsonnet should have no errors")53		.as_obj()54		.expect("stdlib.jsonnet should evaluate to object");5556	builder.with_super(eval);5758	for (name, builtin) in [59		// Types60		("type", builtin_type::INST),61		("isString", builtin_is_string::INST),62		("isNumber", builtin_is_number::INST),63		("isBoolean", builtin_is_boolean::INST),64		("isObject", builtin_is_object::INST),65		("isArray", builtin_is_array::INST),66		("isFunction", builtin_is_function::INST),67		// Arrays68		("makeArray", builtin_make_array::INST),69		("repeat", builtin_repeat::INST),70		("slice", builtin_slice::INST),71		("map", builtin_map::INST),72		("flatMap", builtin_flatmap::INST),73		("filter", builtin_filter::INST),74		("foldl", builtin_foldl::INST),75		("foldr", builtin_foldr::INST),76		("range", builtin_range::INST),77		("join", builtin_join::INST),78		("reverse", builtin_reverse::INST),79		("any", builtin_any::INST),80		("all", builtin_all::INST),81		("member", builtin_member::INST),82		("contains", builtin_contains::INST),83		("count", builtin_count::INST),84		("avg", builtin_avg::INST),85		("removeAt", builtin_remove_at::INST),86		("remove", builtin_remove::INST),87		// Math88		("abs", builtin_abs::INST),89		("sign", builtin_sign::INST),90		("max", builtin_max::INST),91		("min", builtin_min::INST),92		("sum", builtin_sum::INST),93		("modulo", builtin_modulo::INST),94		("floor", builtin_floor::INST),95		("ceil", builtin_ceil::INST),96		("log", builtin_log::INST),97		("pow", builtin_pow::INST),98		("sqrt", builtin_sqrt::INST),99		("sin", builtin_sin::INST),100		("cos", builtin_cos::INST),101		("tan", builtin_tan::INST),102		("asin", builtin_asin::INST),103		("acos", builtin_acos::INST),104		("atan", builtin_atan::INST),105		("exp", builtin_exp::INST),106		("mantissa", builtin_mantissa::INST),107		("exponent", builtin_exponent::INST),108		("round", builtin_round::INST),109		("isEven", builtin_is_even::INST),110		("isOdd", builtin_is_odd::INST),111		("isInteger", builtin_is_integer::INST),112		("isDecimal", builtin_is_decimal::INST),113		// Operator114		("mod", builtin_mod::INST),115		("primitiveEquals", builtin_primitive_equals::INST),116		("equals", builtin_equals::INST),117		("xor", builtin_xor::INST),118		("xnor", builtin_xnor::INST),119		("format", builtin_format::INST),120		// Sort121		("sort", builtin_sort::INST),122		("uniq", builtin_uniq::INST),123		("set", builtin_set::INST),124		("minArray", builtin_min_array::INST),125		("maxArray", builtin_max_array::INST),126		// Hash127		("md5", builtin_md5::INST),128		("sha1", builtin_sha1::INST),129		("sha256", builtin_sha256::INST),130		("sha512", builtin_sha512::INST),131		("sha3", builtin_sha3::INST),132		// Encoding133		("encodeUTF8", builtin_encode_utf8::INST),134		("decodeUTF8", builtin_decode_utf8::INST),135		("base64", builtin_base64::INST),136		("base64Decode", builtin_base64_decode::INST),137		("base64DecodeBytes", builtin_base64_decode_bytes::INST),138		// Objects139		("objectFieldsEx", builtin_object_fields_ex::INST),140		("objectValues", builtin_object_values::INST),141		("objectValuesAll", builtin_object_values_all::INST),142		("objectKeysValues", builtin_object_keys_values::INST),143		("objectKeysValuesAll", builtin_object_keys_values_all::INST),144		("objectHasEx", builtin_object_has_ex::INST),145		("objectRemoveKey", builtin_object_remove_key::INST),146		// Manifest147		("escapeStringJson", builtin_escape_string_json::INST),148		("manifestJsonEx", builtin_manifest_json_ex::INST),149		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),150		("manifestTomlEx", builtin_manifest_toml_ex::INST),151		// Parsing152		("parseJson", builtin_parse_json::INST),153		("parseYaml", builtin_parse_yaml::INST),154		// Strings155		("codepoint", builtin_codepoint::INST),156		("substr", builtin_substr::INST),157		("char", builtin_char::INST),158		("strReplace", builtin_str_replace::INST),159		("isEmpty", builtin_is_empty::INST),160		("equalsIgnoreCase", builtin_equals_ignore_case::INST),161		("splitLimit", builtin_splitlimit::INST),162		("asciiUpper", builtin_ascii_upper::INST),163		("asciiLower", builtin_ascii_lower::INST),164		("findSubstr", builtin_find_substr::INST),165		("parseInt", builtin_parse_int::INST),166		#[cfg(feature = "exp-bigint")]167		("bigint", builtin_bigint::INST),168		("parseOctal", builtin_parse_octal::INST),169		("parseHex", builtin_parse_hex::INST),170		// Misc171		("length", builtin_length::INST),172		("startsWith", builtin_starts_with::INST),173		("endsWith", builtin_ends_with::INST),174		// Sets175		("setMember", builtin_set_member::INST),176		("setInter", builtin_set_inter::INST),177		("setDiff", builtin_set_diff::INST),178		// Compat179		("__compare", builtin___compare::INST),180	]181	.iter()182	.cloned()183	{184		builder.method(name, builtin);185	}186187	builder.method(188		"extVar",189		builtin_ext_var {190			settings: settings.clone(),191		},192	);193	builder.method(194		"native",195		builtin_native {196			settings: settings.clone(),197		},198	);199	builder.method("trace", builtin_trace { settings });200201	builder.method("id", FuncVal::Id);202203	builder.build()204}205206pub trait TracePrinter {207	fn print_trace(&self, loc: CallLocation, value: IStr);208}209210pub struct StdTracePrinter {211	resolver: PathResolver,212}213impl StdTracePrinter {214	pub fn new(resolver: PathResolver) -> Self {215		Self { resolver }216	}217}218impl TracePrinter for StdTracePrinter {219	fn print_trace(&self, loc: CallLocation, value: IStr) {220		eprint!("TRACE:");221		if let Some(loc) = loc.0 {222			let locs = loc.0.map_source_locations(&[loc.1]);223			eprint!(224				" {}:{}",225				match loc.0.source_path().path() {226					Some(p) => self.resolver.resolve(p),227					None => loc.0.source_path().to_string(),228				},229				locs[0].line230			);231		}232		eprintln!(" {value}");233	}234}235236pub struct Settings {237	/// Used for `std.extVar`238	pub ext_vars: HashMap<IStr, TlaArg>,239	/// Used for `std.native`240	pub ext_natives: HashMap<IStr, FuncVal>,241	/// Used for `std.trace`242	pub trace_printer: Box<dyn TracePrinter>,243	/// Used for `std.thisFile`244	pub path_resolver: PathResolver,245}246247fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {248	let source_name = format!("<extvar:{name}>");249	Source::new_virtual(source_name.into(), code.into())250}251252#[derive(Trace, Clone)]253pub struct ContextInitializer {254	/// When we don't need to support legacy-this-file, we can reuse same context for all files255	#[cfg(not(feature = "legacy-this-file"))]256	context: jrsonnet_evaluator::Context,257	/// For `populate`258	#[cfg(not(feature = "legacy-this-file"))]259	stdlib_thunk: Thunk<Val>,260	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it261	#[cfg(feature = "legacy-this-file")]262	stdlib_obj: ObjValue,263	settings: Rc<RefCell<Settings>>,264}265impl ContextInitializer {266	pub fn new(_s: State, resolver: PathResolver) -> Self {267		let settings = Settings {268			ext_vars: Default::default(),269			ext_natives: Default::default(),270			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),271			path_resolver: resolver,272		};273		let settings = Rc::new(RefCell::new(settings));274		let stdlib_obj = stdlib_uncached(settings.clone());275		#[cfg(not(feature = "legacy-this-file"))]276		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));277		Self {278			#[cfg(not(feature = "legacy-this-file"))]279			context: {280				let mut context = ContextBuilder::with_capacity(_s, 1);281				context.bind("std", stdlib_thunk.clone());282				context.build()283			},284			#[cfg(not(feature = "legacy-this-file"))]285			stdlib_thunk,286			#[cfg(feature = "legacy-this-file")]287			stdlib_obj,288			settings,289		}290	}291	pub fn settings(&self) -> Ref<Settings> {292		self.settings.borrow()293	}294	pub fn settings_mut(&self) -> RefMut<Settings> {295		self.settings.borrow_mut()296	}297	pub fn add_ext_var(&self, name: IStr, value: Val) {298		self.settings_mut()299			.ext_vars300			.insert(name, TlaArg::Val(value));301	}302	pub fn add_ext_str(&self, name: IStr, value: IStr) {303		self.settings_mut()304			.ext_vars305			.insert(name, TlaArg::String(value));306	}307	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {308		let code = code.into();309		let source = extvar_source(name, code.clone());310		let parsed = jrsonnet_parser::parse(311			&code,312			&jrsonnet_parser::ParserSettings {313				source: source.clone(),314			},315		)316		.map_err(|e| ImportSyntaxError {317			path: source,318			error: Box::new(e),319		})?;320		// self.data_mut().volatile_files.insert(source_name, code);321		self.settings_mut()322			.ext_vars323			.insert(name.into(), TlaArg::Code(parsed));324		Ok(())325	}326	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {327		self.settings_mut()328			.ext_natives329			.insert(name.into(), cb.into());330	}331}332impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {333	fn reserve_vars(&self) -> usize {334		1335	}336	#[cfg(not(feature = "legacy-this-file"))]337	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {338		self.context.clone()339	}340	#[cfg(not(feature = "legacy-this-file"))]341	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {342		builder.bind("std", self.stdlib_thunk.clone());343	}344	#[cfg(feature = "legacy-this-file")]345	fn populate(&self, source: Source, builder: &mut ContextBuilder) {346		use jrsonnet_evaluator::val::StrValue;347348		let mut std = ObjValueBuilder::new();349		std.with_super(self.stdlib_obj.clone());350		std.field("thisFile".into())351			.hide()352			.value(Val::string(match source.source_path().path() {353				Some(p) => self.settings().path_resolver.resolve(p).into(),354				None => source.source_path().to_string().into(),355			}))356			.expect("this object builder is empty");357		let stdlib_with_this_file = std.build();358359		builder.bind(360			"std".into(),361			Thunk::evaluated(Val::Obj(stdlib_with_this_file)),362		);363	}364	fn as_any(&self) -> &dyn std::any::Any {365		self366	}367}368369pub trait StateExt {370	/// This method was previously implemented in jrsonnet-evaluator itself371	fn with_stdlib(&self);372}373374impl StateExt for State {375	fn with_stdlib(&self) {376		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());377		self.settings_mut().context_initializer = tb!(initializer)378	}379}
after · crates/jrsonnet-stdlib/src/lib.rs
1use std::{2	cell::{Ref, RefCell, RefMut},3	collections::HashMap,4	rc::Rc,5};67use jrsonnet_evaluator::{8	error::{ErrorKind::*, Result},9	function::{CallLocation, FuncVal, TlaArg},10	tb,11	trace::PathResolver,12	ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,13};14use jrsonnet_gcmodule::Trace;15use jrsonnet_parser::Source;1617mod expr;18mod types;19pub use types::*;20mod arrays;21pub use arrays::*;22mod math;23pub use math::*;24mod operator;25pub use operator::*;26mod sort;27pub use sort::*;28mod hash;29pub use hash::*;30mod encoding;31pub use encoding::*;32mod objects;33pub use objects::*;34mod manifest;35pub use manifest::*;36mod parse;37pub use parse::*;38mod strings;39pub use strings::*;40mod misc;41pub use misc::*;42mod sets;43pub use sets::*;44mod compat;45pub use compat::*;4647pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {48	let mut builder = ObjValueBuilder::new();4950	let expr = expr::stdlib_expr();51	let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)52		.expect("stdlib.jsonnet should have no errors")53		.as_obj()54		.expect("stdlib.jsonnet should evaluate to object");5556	builder.with_super(eval);5758	for (name, builtin) in [59		// Types60		("type", builtin_type::INST),61		("isString", builtin_is_string::INST),62		("isNumber", builtin_is_number::INST),63		("isBoolean", builtin_is_boolean::INST),64		("isObject", builtin_is_object::INST),65		("isArray", builtin_is_array::INST),66		("isFunction", builtin_is_function::INST),67		// Arrays68		("makeArray", builtin_make_array::INST),69		("repeat", builtin_repeat::INST),70		("slice", builtin_slice::INST),71		("map", builtin_map::INST),72		("flatMap", builtin_flatmap::INST),73		("filter", builtin_filter::INST),74		("foldl", builtin_foldl::INST),75		("foldr", builtin_foldr::INST),76		("range", builtin_range::INST),77		("join", builtin_join::INST),78		("reverse", builtin_reverse::INST),79		("any", builtin_any::INST),80		("all", builtin_all::INST),81		("member", builtin_member::INST),82		("contains", builtin_contains::INST),83		("count", builtin_count::INST),84		("avg", builtin_avg::INST),85		("removeAt", builtin_remove_at::INST),86		("remove", builtin_remove::INST),87		("flattenArrays", builtin_flatten_arrays::INST),88		("filterMap", builtin_filter_map::INST),89		// Math90		("abs", builtin_abs::INST),91		("sign", builtin_sign::INST),92		("max", builtin_max::INST),93		("min", builtin_min::INST),94		("sum", builtin_sum::INST),95		("modulo", builtin_modulo::INST),96		("floor", builtin_floor::INST),97		("ceil", builtin_ceil::INST),98		("log", builtin_log::INST),99		("pow", builtin_pow::INST),100		("sqrt", builtin_sqrt::INST),101		("sin", builtin_sin::INST),102		("cos", builtin_cos::INST),103		("tan", builtin_tan::INST),104		("asin", builtin_asin::INST),105		("acos", builtin_acos::INST),106		("atan", builtin_atan::INST),107		("exp", builtin_exp::INST),108		("mantissa", builtin_mantissa::INST),109		("exponent", builtin_exponent::INST),110		("round", builtin_round::INST),111		("isEven", builtin_is_even::INST),112		("isOdd", builtin_is_odd::INST),113		("isInteger", builtin_is_integer::INST),114		("isDecimal", builtin_is_decimal::INST),115		// Operator116		("mod", builtin_mod::INST),117		("primitiveEquals", builtin_primitive_equals::INST),118		("equals", builtin_equals::INST),119		("xor", builtin_xor::INST),120		("xnor", builtin_xnor::INST),121		("format", builtin_format::INST),122		// Sort123		("sort", builtin_sort::INST),124		("uniq", builtin_uniq::INST),125		("set", builtin_set::INST),126		("minArray", builtin_min_array::INST),127		("maxArray", builtin_max_array::INST),128		// Hash129		("md5", builtin_md5::INST),130		("sha1", builtin_sha1::INST),131		("sha256", builtin_sha256::INST),132		("sha512", builtin_sha512::INST),133		("sha3", builtin_sha3::INST),134		// Encoding135		("encodeUTF8", builtin_encode_utf8::INST),136		("decodeUTF8", builtin_decode_utf8::INST),137		("base64", builtin_base64::INST),138		("base64Decode", builtin_base64_decode::INST),139		("base64DecodeBytes", builtin_base64_decode_bytes::INST),140		// Objects141		("objectFieldsEx", builtin_object_fields_ex::INST),142		("objectFields", builtin_object_fields::INST),143		("objectFieldsAll", builtin_object_fields_all::INST),144		("objectValues", builtin_object_values::INST),145		("objectValuesAll", builtin_object_values_all::INST),146		("objectKeysValues", builtin_object_keys_values::INST),147		("objectKeysValuesAll", builtin_object_keys_values_all::INST),148		("objectHasEx", builtin_object_has_ex::INST),149		("objectHas", builtin_object_has::INST),150		("objectHasAll", builtin_object_has_all::INST),151		("objectRemoveKey", builtin_object_remove_key::INST),152		// Manifest153		("escapeStringJson", builtin_escape_string_json::INST),154		("manifestJsonEx", builtin_manifest_json_ex::INST),155		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),156		("manifestTomlEx", builtin_manifest_toml_ex::INST),157		("toString", builtin_to_string::INST),158		// Parsing159		("parseJson", builtin_parse_json::INST),160		("parseYaml", builtin_parse_yaml::INST),161		// Strings162		("codepoint", builtin_codepoint::INST),163		("substr", builtin_substr::INST),164		("char", builtin_char::INST),165		("strReplace", builtin_str_replace::INST),166		("isEmpty", builtin_is_empty::INST),167		("equalsIgnoreCase", builtin_equals_ignore_case::INST),168		("splitLimit", builtin_splitlimit::INST),169		("asciiUpper", builtin_ascii_upper::INST),170		("asciiLower", builtin_ascii_lower::INST),171		("findSubstr", builtin_find_substr::INST),172		("parseInt", builtin_parse_int::INST),173		#[cfg(feature = "exp-bigint")]174		("bigint", builtin_bigint::INST),175		("parseOctal", builtin_parse_octal::INST),176		("parseHex", builtin_parse_hex::INST),177		("stringChars", builtin_string_chars::INST),178		// Misc179		("length", builtin_length::INST),180		("startsWith", builtin_starts_with::INST),181		("endsWith", builtin_ends_with::INST),182		// Sets183		("setMember", builtin_set_member::INST),184		("setInter", builtin_set_inter::INST),185		("setDiff", builtin_set_diff::INST),186		("setUnion", builtin_set_union::INST),187		// Compat188		("__compare", builtin___compare::INST),189	]190	.iter()191	.cloned()192	{193		builder.method(name, builtin);194	}195196	builder.method(197		"extVar",198		builtin_ext_var {199			settings: settings.clone(),200		},201	);202	builder.method(203		"native",204		builtin_native {205			settings: settings.clone(),206		},207	);208	builder.method("trace", builtin_trace { settings });209210	builder.method("id", FuncVal::Id);211212	builder.build()213}214215pub trait TracePrinter {216	fn print_trace(&self, loc: CallLocation, value: IStr);217}218219pub struct StdTracePrinter {220	resolver: PathResolver,221}222impl StdTracePrinter {223	pub fn new(resolver: PathResolver) -> Self {224		Self { resolver }225	}226}227impl TracePrinter for StdTracePrinter {228	fn print_trace(&self, loc: CallLocation, value: IStr) {229		eprint!("TRACE:");230		if let Some(loc) = loc.0 {231			let locs = loc.0.map_source_locations(&[loc.1]);232			eprint!(233				" {}:{}",234				match loc.0.source_path().path() {235					Some(p) => self.resolver.resolve(p),236					None => loc.0.source_path().to_string(),237				},238				locs[0].line239			);240		}241		eprintln!(" {value}");242	}243}244245pub struct Settings {246	/// Used for `std.extVar`247	pub ext_vars: HashMap<IStr, TlaArg>,248	/// Used for `std.native`249	pub ext_natives: HashMap<IStr, FuncVal>,250	/// Used for `std.trace`251	pub trace_printer: Box<dyn TracePrinter>,252	/// Used for `std.thisFile`253	pub path_resolver: PathResolver,254}255256fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {257	let source_name = format!("<extvar:{name}>");258	Source::new_virtual(source_name.into(), code.into())259}260261#[derive(Trace, Clone)]262pub struct ContextInitializer {263	/// When we don't need to support legacy-this-file, we can reuse same context for all files264	#[cfg(not(feature = "legacy-this-file"))]265	context: jrsonnet_evaluator::Context,266	/// For `populate`267	#[cfg(not(feature = "legacy-this-file"))]268	stdlib_thunk: Thunk<Val>,269	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it270	#[cfg(feature = "legacy-this-file")]271	stdlib_obj: ObjValue,272	settings: Rc<RefCell<Settings>>,273}274impl ContextInitializer {275	pub fn new(_s: State, resolver: PathResolver) -> Self {276		let settings = Settings {277			ext_vars: Default::default(),278			ext_natives: Default::default(),279			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),280			path_resolver: resolver,281		};282		let settings = Rc::new(RefCell::new(settings));283		let stdlib_obj = stdlib_uncached(settings.clone());284		#[cfg(not(feature = "legacy-this-file"))]285		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));286		Self {287			#[cfg(not(feature = "legacy-this-file"))]288			context: {289				let mut context = ContextBuilder::with_capacity(_s, 1);290				context.bind("std", stdlib_thunk.clone());291				context.build()292			},293			#[cfg(not(feature = "legacy-this-file"))]294			stdlib_thunk,295			#[cfg(feature = "legacy-this-file")]296			stdlib_obj,297			settings,298		}299	}300	pub fn settings(&self) -> Ref<Settings> {301		self.settings.borrow()302	}303	pub fn settings_mut(&self) -> RefMut<Settings> {304		self.settings.borrow_mut()305	}306	pub fn add_ext_var(&self, name: IStr, value: Val) {307		self.settings_mut()308			.ext_vars309			.insert(name, TlaArg::Val(value));310	}311	pub fn add_ext_str(&self, name: IStr, value: IStr) {312		self.settings_mut()313			.ext_vars314			.insert(name, TlaArg::String(value));315	}316	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {317		let code = code.into();318		let source = extvar_source(name, code.clone());319		let parsed = jrsonnet_parser::parse(320			&code,321			&jrsonnet_parser::ParserSettings {322				source: source.clone(),323			},324		)325		.map_err(|e| ImportSyntaxError {326			path: source,327			error: Box::new(e),328		})?;329		// self.data_mut().volatile_files.insert(source_name, code);330		self.settings_mut()331			.ext_vars332			.insert(name.into(), TlaArg::Code(parsed));333		Ok(())334	}335	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {336		self.settings_mut()337			.ext_natives338			.insert(name.into(), cb.into());339	}340}341impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {342	fn reserve_vars(&self) -> usize {343		1344	}345	#[cfg(not(feature = "legacy-this-file"))]346	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {347		self.context.clone()348	}349	#[cfg(not(feature = "legacy-this-file"))]350	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {351		builder.bind("std", self.stdlib_thunk.clone());352	}353	#[cfg(feature = "legacy-this-file")]354	fn populate(&self, source: Source, builder: &mut ContextBuilder) {355		use jrsonnet_evaluator::val::StrValue;356357		let mut std = ObjValueBuilder::new();358		std.with_super(self.stdlib_obj.clone());359		std.field("thisFile")360			.hide()361			.value(match source.source_path().path() {362				Some(p) => self.settings().path_resolver.resolve(p),363				None => source.source_path().to_string(),364			});365		let stdlib_with_this_file = std.build();366367		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));368	}369	fn as_any(&self) -> &dyn std::any::Any {370		self371	}372}373374pub trait StateExt {375	/// This method was previously implemented in jrsonnet-evaluator itself376	fn with_stdlib(&self);377}378379impl StateExt for State {380	fn with_stdlib(&self) {381		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());382		self.settings_mut().context_initializer = tb!(initializer)383	}384}
modifiedcrates/jrsonnet-stdlib/src/manifest/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/mod.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/mod.rs
@@ -60,3 +60,8 @@
 		preserve_order.unwrap_or(false),
 	))
 }
+
+#[builtin]
+pub fn builtin_to_string(a: Val) -> Result<IStr> {
+	a.to_string()
+}
modifiedcrates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -1,6 +1,6 @@
 use jrsonnet_evaluator::{
 	function::builtin,
-	val::{ArrValue, StrValue, Val},
+	val::{ArrValue, Val},
 	IStr, ObjValue, ObjValueBuilder,
 };
 
@@ -17,12 +17,35 @@
 		#[cfg(feature = "exp-preserve-order")]
 		preserve_order,
 	);
-	out.into_iter()
-		.map(StrValue::Flat)
-		.map(Val::Str)
-		.collect::<Vec<_>>()
+	out.into_iter().map(Val::string).collect::<Vec<_>>()
+}
+
+#[builtin]
+pub fn builtin_object_fields(
+	o: ObjValue,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> Vec<Val> {
+	builtin_object_fields_ex(
+		o,
+		false,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	)
 }
 
+#[builtin]
+pub fn builtin_object_fields_all(
+	o: ObjValue,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> Vec<Val> {
+	builtin_object_fields_ex(
+		o,
+		true,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	)
+}
+
 pub fn builtin_object_values_ex(
 	o: ObjValue,
 	include_hidden: bool,
@@ -105,6 +128,16 @@
 }
 
 #[builtin]
+pub fn builtin_object_has(o: ObjValue, f: IStr) -> bool {
+	o.has_field(f)
+}
+
+#[builtin]
+pub fn builtin_object_has_all(o: ObjValue, f: IStr) -> bool {
+	o.has_field_include_hidden(f)
+}
+
+#[builtin]
 pub fn builtin_object_remove_key(
 	obj: ObjValue,
 	key: IStr,
modifiedcrates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -70,6 +70,7 @@
 	}
 	Ok(ArrValue::lazy(out))
 }
+
 #[builtin]
 #[allow(non_snake_case, clippy::redundant_closure)]
 pub fn builtin_set_diff(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
@@ -115,3 +116,57 @@
 	}
 	Ok(ArrValue::lazy(out))
 }
+
+#[builtin]
+#[allow(non_snake_case, clippy::redundant_closure)]
+pub fn builtin_set_union(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
+	let mut a = a.iter_lazy();
+	let mut b = b.iter_lazy();
+
+	let keyF = keyF
+		.unwrap_or(FuncVal::identity())
+		.into_native::<((Thunk<Val>,), Val)>();
+	let keyF = |v| keyF(v);
+
+	let mut av = a.next();
+	let mut bv = b.next();
+	let mut ak = av.clone().map(keyF).transpose()?;
+	let mut bk = bv.clone().map(keyF).transpose()?;
+
+	let mut out = Vec::new();
+	while let (Some(ac), Some(bc)) = (&ak, &bk) {
+		match evaluate_compare_op(ac, bc, BinaryOpType::Lt)? {
+			Ordering::Less => {
+				out.push(av.clone().expect("ak != None"));
+				av = a.next();
+				ak = av.clone().map(keyF).transpose()?;
+			}
+			Ordering::Greater => {
+				out.push(bv.clone().expect("bk != None"));
+				bv = b.next();
+				bk = bv.clone().map(keyF).transpose()?;
+			}
+			Ordering::Equal => {
+				// NOTE: order matters, values in `a` win
+				out.push(av.clone().expect("ak != None"));
+				av = a.next();
+				ak = av.clone().map(keyF).transpose()?;
+				bv = b.next();
+				bk = bv.clone().map(keyF).transpose()?;
+			}
+		};
+	}
+	// a.len() > b.len()
+	while let Some(_ac) = &ak {
+		out.push(av.clone().expect("ak != None"));
+		av = a.next();
+		ak = av.clone().map(keyF).transpose()?;
+	}
+	// b.len() > a.len()
+	while let Some(_bc) = &bk {
+		out.push(bv.clone().expect("ak != None"));
+		bv = b.next();
+		bk = bv.clone().map(keyF).transpose()?;
+	}
+	Ok(ArrValue::lazy(out))
+}
modifiedcrates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/std.jsonnet
+++ b/crates/jrsonnet-stdlib/src/std.jsonnet
@@ -4,8 +4,6 @@
 
   thisFile:: error 'std.thisFile is deprecated, to enable its support in jrsonnet - recompile it with "legacy-this-file" support.\nThis will slow down stdlib caching a bit, though',
 
-  toString(a):: '' + a,
-
   lstripChars(str, chars)::
     if std.length(str) > 0 && std.member(chars, str[0]) then
       std.lstripChars(str[1:], chars)
@@ -21,9 +19,6 @@
 
   stripChars(str, chars)::
     std.lstripChars(std.rstripChars(str, chars), chars),
-
-  stringChars(str)::
-    std.makeArray(std.length(str), function(i) str[i]),
 
   splitLimitR(str, c, maxsplits)::
     if maxsplits == -1 then
@@ -60,16 +55,6 @@
       std.join('', [std.deepJoin(x) for x in arr])
     else
       error 'Expected string or array, got %s' % std.type(arr),
-
-  filterMap(filter_func, map_func, arr)::
-    if !std.isFunction(filter_func) then
-      error ('std.filterMap first param must be function, got ' + std.type(filter_func))
-    else if !std.isFunction(map_func) then
-      error ('std.filterMap second param must be function, got ' + std.type(map_func))
-    else if !std.isArray(arr) then
-      error ('std.filterMap third param must be array, got ' + std.type(arr))
-    else
-      std.map(map_func, std.filter(filter_func, arr)),
 
   assertEqual(a, b)::
     if a == b then
@@ -81,9 +66,6 @@
     if x < minVal then minVal
     else if x > maxVal then maxVal
     else x,
-
-  flattenArrays(arrs)::
-    std.foldl(function(a, b) a + b, arrs, []),
 
   manifestIni(ini)::
     local body_lines(body) =
@@ -195,24 +177,6 @@
           std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);
 
       aux(value),
-
-  setUnion(a, b, keyF=id)::
-    // NOTE: order matters, values in `a` win
-    local aux(a, b, i, j, acc) =
-      if i >= std.length(a) then
-        acc + b[j:]
-      else if j >= std.length(b) then
-        acc + a[i:]
-      else
-        local ak = keyF(a[i]);
-        local bk = keyF(b[j]);
-        if ak == bk then
-          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict
-        else if ak < bk then
-          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict
-        else
-          aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;
-    aux(a, b, 0, 0, []),
 
   mergePatch(target, patch)::
     if std.isObject(patch) then
@@ -240,18 +204,6 @@
 
   get(o, f, default=null, inc_hidden=true)::
     if std.objectHasEx(o, f, inc_hidden) then o[f] else default,
-
-  objectFields(o)::
-    std.objectFieldsEx(o, false),
-
-  objectFieldsAll(o)::
-    std.objectFieldsEx(o, true),
-
-  objectHas(o, f)::
-    std.objectHasEx(o, f, false),
-
-  objectHasAll(o, f)::
-    std.objectHasEx(o, f, true),
 
   resolvePath(f, r)::
     local arr = std.split(f, '/');
modifiedcrates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -198,3 +198,8 @@
 		assert_eq!(parse_nat::<16>("BbC").unwrap(), 0xBBC as f64);
 	}
 }
+
+#[builtin]
+pub fn builtin_string_chars(str: IStr) -> ArrValue {
+	ArrValue::chars(str.chars())
+}