git.delta.rocks / jrsonnet / refs/commits / 0ae36baea489

difftreelog

perf move mapWithKey to native

Yaroslav Bolyukin2024-05-19parent: #57f709a.patch.diff
in: master

3 files changed

modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -6,7 +6,7 @@
 	runtime_error,
 	typed::{BoundedI32, BoundedUsize, Either2, NativeFn, Typed},
 	val::{equals, ArrValue, IndexableVal},
-	Either, IStr, ObjValueBuilder, Result, ResultExt, Thunk, Val,
+	Either, IStr, ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,
 };
 
 pub fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
@@ -68,6 +68,16 @@
 }
 
 #[builtin]
+pub fn builtin_map_with_key(func: FuncVal, obj: ObjValue) -> Result<ObjValue> {
+	let mut out = ObjValueBuilder::new();
+	for (k, v) in obj.iter() {
+		let v = v?;
+		out.field(k).value(func.evaluate_simple(&(v,), false)?);
+	}
+	Ok(out.build())
+}
+
+#[builtin]
 pub fn builtin_flatmap(
 	func: NativeFn<((Either![String, Val],), Val)>,
 	arr: IndexableVal,
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/lib.rs
1#![allow(clippy::similar_names)]23use std::{4	cell::{Ref, RefCell, RefMut},5	collections::HashMap,6	rc::Rc,7};89pub use arrays::*;10pub use compat::*;11pub use encoding::*;12pub use hash::*;13use jrsonnet_evaluator::{14	error::{ErrorKind::*, Result},15	function::{CallLocation, FuncVal, TlaArg},16	tb,17	trace::PathResolver,18	ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,19};20use jrsonnet_gcmodule::Trace;21use jrsonnet_parser::Source;22pub use manifest::*;23pub use math::*;24pub use misc::*;25pub use objects::*;26pub use operator::*;27pub use parse::*;28pub use sets::*;29pub use sort::*;30pub use strings::*;31pub use types::*;3233#[cfg(feature = "exp-regex")]34pub use crate::regex::*;3536mod arrays;37mod compat;38mod encoding;39mod expr;40mod hash;41mod manifest;42mod math;43mod misc;44mod objects;45mod operator;46mod parse;47#[cfg(feature = "exp-regex")]48mod regex;49mod sets;50mod sort;51mod strings;52mod types;5354#[allow(clippy::too_many_lines)]55pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {56	let mut builder = ObjValueBuilder::new();5758	let expr = expr::stdlib_expr();59	let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)60		.expect("stdlib.jsonnet should have no errors")61		.as_obj()62		.expect("stdlib.jsonnet should evaluate to object");6364	builder.with_super(eval);6566	// FIXME: Use PHF67	for (name, builtin) in [68		// Types69		("type", builtin_type::INST),70		("isString", builtin_is_string::INST),71		("isNumber", builtin_is_number::INST),72		("isBoolean", builtin_is_boolean::INST),73		("isObject", builtin_is_object::INST),74		("isArray", builtin_is_array::INST),75		("isFunction", builtin_is_function::INST),76		// Arrays77		("makeArray", builtin_make_array::INST),78		("repeat", builtin_repeat::INST),79		("slice", builtin_slice::INST),80		("map", builtin_map::INST),81		("mapWithIndex", builtin_map_with_index::INST),82		("flatMap", builtin_flatmap::INST),83		("filter", builtin_filter::INST),84		("foldl", builtin_foldl::INST),85		("foldr", builtin_foldr::INST),86		("range", builtin_range::INST),87		("join", builtin_join::INST),88		("lines", builtin_lines::INST),89		("resolvePath", builtin_resolve_path::INST),90		("deepJoin", builtin_deep_join::INST),91		("reverse", builtin_reverse::INST),92		("any", builtin_any::INST),93		("all", builtin_all::INST),94		("member", builtin_member::INST),95		("find", builtin_find::INST),96		("contains", builtin_contains::INST),97		("count", builtin_count::INST),98		("avg", builtin_avg::INST),99		("removeAt", builtin_remove_at::INST),100		("remove", builtin_remove::INST),101		("flattenArrays", builtin_flatten_arrays::INST),102		("flattenDeepArray", builtin_flatten_deep_array::INST),103		("prune", builtin_prune::INST),104		("filterMap", builtin_filter_map::INST),105		// Math106		("abs", builtin_abs::INST),107		("sign", builtin_sign::INST),108		("max", builtin_max::INST),109		("min", builtin_min::INST),110		("clamp", builtin_clamp::INST),111		("sum", builtin_sum::INST),112		("modulo", builtin_modulo::INST),113		("floor", builtin_floor::INST),114		("ceil", builtin_ceil::INST),115		("log", builtin_log::INST),116		("pow", builtin_pow::INST),117		("sqrt", builtin_sqrt::INST),118		("sin", builtin_sin::INST),119		("cos", builtin_cos::INST),120		("tan", builtin_tan::INST),121		("asin", builtin_asin::INST),122		("acos", builtin_acos::INST),123		("atan", builtin_atan::INST),124		("atan2", builtin_atan2::INST),125		("exp", builtin_exp::INST),126		("mantissa", builtin_mantissa::INST),127		("exponent", builtin_exponent::INST),128		("round", builtin_round::INST),129		("isEven", builtin_is_even::INST),130		("isOdd", builtin_is_odd::INST),131		("isInteger", builtin_is_integer::INST),132		("isDecimal", builtin_is_decimal::INST),133		// Operator134		("mod", builtin_mod::INST),135		("primitiveEquals", builtin_primitive_equals::INST),136		("equals", builtin_equals::INST),137		("xor", builtin_xor::INST),138		("xnor", builtin_xnor::INST),139		("format", builtin_format::INST),140		// Sort141		("sort", builtin_sort::INST),142		("uniq", builtin_uniq::INST),143		("set", builtin_set::INST),144		("minArray", builtin_min_array::INST),145		("maxArray", builtin_max_array::INST),146		// Hash147		("md5", builtin_md5::INST),148		("sha1", builtin_sha1::INST),149		("sha256", builtin_sha256::INST),150		("sha512", builtin_sha512::INST),151		("sha3", builtin_sha3::INST),152		// Encoding153		("encodeUTF8", builtin_encode_utf8::INST),154		("decodeUTF8", builtin_decode_utf8::INST),155		("base64", builtin_base64::INST),156		("base64Decode", builtin_base64_decode::INST),157		("base64DecodeBytes", builtin_base64_decode_bytes::INST),158		// Objects159		("objectFieldsEx", builtin_object_fields_ex::INST),160		("objectFields", builtin_object_fields::INST),161		("objectFieldsAll", builtin_object_fields_all::INST),162		("objectValues", builtin_object_values::INST),163		("objectValuesAll", builtin_object_values_all::INST),164		("objectKeysValues", builtin_object_keys_values::INST),165		("objectKeysValuesAll", builtin_object_keys_values_all::INST),166		("objectHasEx", builtin_object_has_ex::INST),167		("objectHas", builtin_object_has::INST),168		("objectHasAll", builtin_object_has_all::INST),169		("objectRemoveKey", builtin_object_remove_key::INST),170		// Manifest171		("escapeStringJson", builtin_escape_string_json::INST),172		("escapeStringPython", builtin_escape_string_python::INST),173		("escapeStringXML", builtin_escape_string_xml::INST),174		("manifestJsonEx", builtin_manifest_json_ex::INST),175		("manifestJson", builtin_manifest_json::INST),176		("manifestJsonMinified", builtin_manifest_json_minified::INST),177		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),178		("manifestYamlStream", builtin_manifest_yaml_stream::INST),179		("manifestTomlEx", builtin_manifest_toml_ex::INST),180		("manifestToml", builtin_manifest_toml::INST),181		("toString", builtin_to_string::INST),182		("manifestPython", builtin_manifest_python::INST),183		("manifestPythonVars", builtin_manifest_python_vars::INST),184		("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),185		("manifestIni", builtin_manifest_ini::INST),186		// Parse187		("parseJson", builtin_parse_json::INST),188		("parseYaml", builtin_parse_yaml::INST),189		// Strings190		("codepoint", builtin_codepoint::INST),191		("substr", builtin_substr::INST),192		("char", builtin_char::INST),193		("strReplace", builtin_str_replace::INST),194		("escapeStringBash", builtin_escape_string_bash::INST),195		("escapeStringDollars", builtin_escape_string_dollars::INST),196		("isEmpty", builtin_is_empty::INST),197		("equalsIgnoreCase", builtin_equals_ignore_case::INST),198		("splitLimit", builtin_splitlimit::INST),199		("splitLimitR", builtin_splitlimitr::INST),200		("split", builtin_split::INST),201		("asciiUpper", builtin_ascii_upper::INST),202		("asciiLower", builtin_ascii_lower::INST),203		("findSubstr", builtin_find_substr::INST),204		("parseInt", builtin_parse_int::INST),205		#[cfg(feature = "exp-bigint")]206		("bigint", builtin_bigint::INST),207		("parseOctal", builtin_parse_octal::INST),208		("parseHex", builtin_parse_hex::INST),209		("stringChars", builtin_string_chars::INST),210		("lstripChars", builtin_lstrip_chars::INST),211		("rstripChars", builtin_rstrip_chars::INST),212		("stripChars", builtin_strip_chars::INST),213		// Misc214		("length", builtin_length::INST),215		("get", builtin_get::INST),216		("startsWith", builtin_starts_with::INST),217		("endsWith", builtin_ends_with::INST),218		("assertEqual", builtin_assert_equal::INST),219		("mergePatch", builtin_merge_patch::INST),220		// Sets221		("setMember", builtin_set_member::INST),222		("setInter", builtin_set_inter::INST),223		("setDiff", builtin_set_diff::INST),224		("setUnion", builtin_set_union::INST),225		// Regex226		#[cfg(feature = "exp-regex")]227		("regexQuoteMeta", builtin_regex_quote_meta::INST),228		// Compat229		("__compare", builtin___compare::INST),230		("__compare_array", builtin___compare_array::INST),231		("__array_less", builtin___array_less::INST),232		("__array_greater", builtin___array_greater::INST),233		("__array_less_or_equal", builtin___array_less_or_equal::INST),234		(235			"__array_greater_or_equal",236			builtin___array_greater_or_equal::INST,237		),238	]239	.iter()240	.copied()241	{242		builder.method(name, builtin);243	}244245	builder.method(246		"extVar",247		builtin_ext_var {248			settings: settings.clone(),249		},250	);251	builder.method(252		"native",253		builtin_native {254			settings: settings.clone(),255		},256	);257	builder.method("trace", builtin_trace { settings });258	builder.method("id", FuncVal::Id);259260	#[cfg(feature = "exp-regex")]261	{262		// Regex263		let regex_cache = RegexCache::default();264		builder.method(265			"regexFullMatch",266			builtin_regex_full_match {267				cache: regex_cache.clone(),268			},269		);270		builder.method(271			"regexPartialMatch",272			builtin_regex_partial_match {273				cache: regex_cache.clone(),274			},275		);276		builder.method(277			"regexReplace",278			builtin_regex_replace {279				cache: regex_cache.clone(),280			},281		);282		builder.method(283			"regexGlobalReplace",284			builtin_regex_global_replace { cache: regex_cache },285		);286	};287288	builder.build()289}290291pub trait TracePrinter {292	fn print_trace(&self, loc: CallLocation, value: IStr);293}294295pub struct StdTracePrinter {296	resolver: PathResolver,297}298impl StdTracePrinter {299	pub fn new(resolver: PathResolver) -> Self {300		Self { resolver }301	}302}303impl TracePrinter for StdTracePrinter {304	fn print_trace(&self, loc: CallLocation, value: IStr) {305		eprint!("TRACE:");306		if let Some(loc) = loc.0 {307			let locs = loc.0.map_source_locations(&[loc.1]);308			eprint!(309				" {}:{}",310				loc.0.source_path().path().map_or_else(311					|| loc.0.source_path().to_string(),312					|p| self.resolver.resolve(p)313				),314				locs[0].line315			);316		}317		eprintln!(" {value}");318	}319}320321pub struct Settings {322	/// Used for `std.extVar`323	pub ext_vars: HashMap<IStr, TlaArg>,324	/// Used for `std.native`325	pub ext_natives: HashMap<IStr, FuncVal>,326	/// Used for `std.trace`327	pub trace_printer: Box<dyn TracePrinter>,328	/// Used for `std.thisFile`329	pub path_resolver: PathResolver,330}331332fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {333	let source_name = format!("<extvar:{name}>");334	Source::new_virtual(source_name.into(), code.into())335}336337#[derive(Trace, Clone)]338pub struct ContextInitializer {339	/// When we don't need to support legacy-this-file, we can reuse same context for all files340	#[cfg(not(feature = "legacy-this-file"))]341	context: jrsonnet_evaluator::Context,342	/// For `populate`343	#[cfg(not(feature = "legacy-this-file"))]344	stdlib_thunk: Thunk<Val>,345	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it346	#[cfg(feature = "legacy-this-file")]347	stdlib_obj: ObjValue,348	settings: Rc<RefCell<Settings>>,349}350impl ContextInitializer {351	pub fn new(s: State, resolver: PathResolver) -> Self {352		let settings = Settings {353			ext_vars: HashMap::new(),354			ext_natives: HashMap::new(),355			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),356			path_resolver: resolver,357		};358		let settings = Rc::new(RefCell::new(settings));359		let stdlib_obj = stdlib_uncached(settings.clone());360		#[cfg(not(feature = "legacy-this-file"))]361		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));362		#[cfg(feature = "legacy-this-file")]363		let _ = s;364		Self {365			#[cfg(not(feature = "legacy-this-file"))]366			context: {367				let mut context = ContextBuilder::with_capacity(s, 1);368				context.bind("std", stdlib_thunk.clone());369				context.build()370			},371			#[cfg(not(feature = "legacy-this-file"))]372			stdlib_thunk,373			#[cfg(feature = "legacy-this-file")]374			stdlib_obj,375			settings,376		}377	}378	pub fn settings(&self) -> Ref<Settings> {379		self.settings.borrow()380	}381	pub fn settings_mut(&self) -> RefMut<Settings> {382		self.settings.borrow_mut()383	}384	pub fn add_ext_var(&self, name: IStr, value: Val) {385		self.settings_mut()386			.ext_vars387			.insert(name, TlaArg::Val(value));388	}389	pub fn add_ext_str(&self, name: IStr, value: IStr) {390		self.settings_mut()391			.ext_vars392			.insert(name, TlaArg::String(value));393	}394	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {395		let code = code.into();396		let source = extvar_source(name, code.clone());397		let parsed = jrsonnet_parser::parse(398			&code,399			&jrsonnet_parser::ParserSettings {400				source: source.clone(),401			},402		)403		.map_err(|e| ImportSyntaxError {404			path: source,405			error: Box::new(e),406		})?;407		// self.data_mut().volatile_files.insert(source_name, code);408		self.settings_mut()409			.ext_vars410			.insert(name.into(), TlaArg::Code(parsed));411		Ok(())412	}413	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {414		self.settings_mut()415			.ext_natives416			.insert(name.into(), cb.into());417	}418}419impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {420	fn reserve_vars(&self) -> usize {421		1422	}423	#[cfg(not(feature = "legacy-this-file"))]424	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {425		self.context.clone()426	}427	#[cfg(not(feature = "legacy-this-file"))]428	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {429		builder.bind("std", self.stdlib_thunk.clone());430	}431	#[cfg(feature = "legacy-this-file")]432	fn populate(&self, source: Source, builder: &mut ContextBuilder) {433		let mut std = ObjValueBuilder::new();434		std.with_super(self.stdlib_obj.clone());435		std.field("thisFile").hide().value({436			let source_path = source.source_path();437			source_path.path().map_or_else(438				|| source_path.to_string(),439				|p| self.settings().path_resolver.resolve(p),440			)441		});442		let stdlib_with_this_file = std.build();443444		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));445	}446	fn as_any(&self) -> &dyn std::any::Any {447		self448	}449}450451pub trait StateExt {452	/// This method was previously implemented in jrsonnet-evaluator itself453	fn with_stdlib(&self);454}455456impl StateExt for State {457	fn with_stdlib(&self) {458		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());459		self.settings_mut().context_initializer = tb!(initializer);460	}461}
after · crates/jrsonnet-stdlib/src/lib.rs
1#![allow(clippy::similar_names)]23use std::{4	cell::{Ref, RefCell, RefMut},5	collections::HashMap,6	rc::Rc,7};89pub use arrays::*;10pub use compat::*;11pub use encoding::*;12pub use hash::*;13use jrsonnet_evaluator::{14	error::{ErrorKind::*, Result},15	function::{CallLocation, FuncVal, TlaArg},16	tb,17	trace::PathResolver,18	ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,19};20use jrsonnet_gcmodule::Trace;21use jrsonnet_parser::Source;22pub use manifest::*;23pub use math::*;24pub use misc::*;25pub use objects::*;26pub use operator::*;27pub use parse::*;28pub use sets::*;29pub use sort::*;30pub use strings::*;31pub use types::*;3233#[cfg(feature = "exp-regex")]34pub use crate::regex::*;3536mod arrays;37mod compat;38mod encoding;39mod expr;40mod hash;41mod manifest;42mod math;43mod misc;44mod objects;45mod operator;46mod parse;47#[cfg(feature = "exp-regex")]48mod regex;49mod sets;50mod sort;51mod strings;52mod types;5354#[allow(clippy::too_many_lines)]55pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {56	let mut builder = ObjValueBuilder::new();5758	let expr = expr::stdlib_expr();59	let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)60		.expect("stdlib.jsonnet should have no errors")61		.as_obj()62		.expect("stdlib.jsonnet should evaluate to object");6364	builder.with_super(eval);6566	// FIXME: Use PHF67	for (name, builtin) in [68		// Types69		("type", builtin_type::INST),70		("isString", builtin_is_string::INST),71		("isNumber", builtin_is_number::INST),72		("isBoolean", builtin_is_boolean::INST),73		("isObject", builtin_is_object::INST),74		("isArray", builtin_is_array::INST),75		("isFunction", builtin_is_function::INST),76		// Arrays77		("makeArray", builtin_make_array::INST),78		("repeat", builtin_repeat::INST),79		("slice", builtin_slice::INST),80		("map", builtin_map::INST),81		("mapWithIndex", builtin_map_with_index::INST),82		("mapWithKey", builtin_map_with_key::INST),83		("flatMap", builtin_flatmap::INST),84		("filter", builtin_filter::INST),85		("foldl", builtin_foldl::INST),86		("foldr", builtin_foldr::INST),87		("range", builtin_range::INST),88		("join", builtin_join::INST),89		("lines", builtin_lines::INST),90		("resolvePath", builtin_resolve_path::INST),91		("deepJoin", builtin_deep_join::INST),92		("reverse", builtin_reverse::INST),93		("any", builtin_any::INST),94		("all", builtin_all::INST),95		("member", builtin_member::INST),96		("find", builtin_find::INST),97		("contains", builtin_contains::INST),98		("count", builtin_count::INST),99		("avg", builtin_avg::INST),100		("removeAt", builtin_remove_at::INST),101		("remove", builtin_remove::INST),102		("flattenArrays", builtin_flatten_arrays::INST),103		("flattenDeepArray", builtin_flatten_deep_array::INST),104		("prune", builtin_prune::INST),105		("filterMap", builtin_filter_map::INST),106		// Math107		("abs", builtin_abs::INST),108		("sign", builtin_sign::INST),109		("max", builtin_max::INST),110		("min", builtin_min::INST),111		("clamp", builtin_clamp::INST),112		("sum", builtin_sum::INST),113		("modulo", builtin_modulo::INST),114		("floor", builtin_floor::INST),115		("ceil", builtin_ceil::INST),116		("log", builtin_log::INST),117		("pow", builtin_pow::INST),118		("sqrt", builtin_sqrt::INST),119		("sin", builtin_sin::INST),120		("cos", builtin_cos::INST),121		("tan", builtin_tan::INST),122		("asin", builtin_asin::INST),123		("acos", builtin_acos::INST),124		("atan", builtin_atan::INST),125		("atan2", builtin_atan2::INST),126		("exp", builtin_exp::INST),127		("mantissa", builtin_mantissa::INST),128		("exponent", builtin_exponent::INST),129		("round", builtin_round::INST),130		("isEven", builtin_is_even::INST),131		("isOdd", builtin_is_odd::INST),132		("isInteger", builtin_is_integer::INST),133		("isDecimal", builtin_is_decimal::INST),134		// Operator135		("mod", builtin_mod::INST),136		("primitiveEquals", builtin_primitive_equals::INST),137		("equals", builtin_equals::INST),138		("xor", builtin_xor::INST),139		("xnor", builtin_xnor::INST),140		("format", builtin_format::INST),141		// Sort142		("sort", builtin_sort::INST),143		("uniq", builtin_uniq::INST),144		("set", builtin_set::INST),145		("minArray", builtin_min_array::INST),146		("maxArray", builtin_max_array::INST),147		// Hash148		("md5", builtin_md5::INST),149		("sha1", builtin_sha1::INST),150		("sha256", builtin_sha256::INST),151		("sha512", builtin_sha512::INST),152		("sha3", builtin_sha3::INST),153		// Encoding154		("encodeUTF8", builtin_encode_utf8::INST),155		("decodeUTF8", builtin_decode_utf8::INST),156		("base64", builtin_base64::INST),157		("base64Decode", builtin_base64_decode::INST),158		("base64DecodeBytes", builtin_base64_decode_bytes::INST),159		// Objects160		("objectFieldsEx", builtin_object_fields_ex::INST),161		("objectFields", builtin_object_fields::INST),162		("objectFieldsAll", builtin_object_fields_all::INST),163		("objectValues", builtin_object_values::INST),164		("objectValuesAll", builtin_object_values_all::INST),165		("objectKeysValues", builtin_object_keys_values::INST),166		("objectKeysValuesAll", builtin_object_keys_values_all::INST),167		("objectHasEx", builtin_object_has_ex::INST),168		("objectHas", builtin_object_has::INST),169		("objectHasAll", builtin_object_has_all::INST),170		("objectRemoveKey", builtin_object_remove_key::INST),171		// Manifest172		("escapeStringJson", builtin_escape_string_json::INST),173		("escapeStringPython", builtin_escape_string_python::INST),174		("escapeStringXML", builtin_escape_string_xml::INST),175		("manifestJsonEx", builtin_manifest_json_ex::INST),176		("manifestJson", builtin_manifest_json::INST),177		("manifestJsonMinified", builtin_manifest_json_minified::INST),178		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),179		("manifestYamlStream", builtin_manifest_yaml_stream::INST),180		("manifestTomlEx", builtin_manifest_toml_ex::INST),181		("manifestToml", builtin_manifest_toml::INST),182		("toString", builtin_to_string::INST),183		("manifestPython", builtin_manifest_python::INST),184		("manifestPythonVars", builtin_manifest_python_vars::INST),185		("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),186		("manifestIni", builtin_manifest_ini::INST),187		// Parse188		("parseJson", builtin_parse_json::INST),189		("parseYaml", builtin_parse_yaml::INST),190		// Strings191		("codepoint", builtin_codepoint::INST),192		("substr", builtin_substr::INST),193		("char", builtin_char::INST),194		("strReplace", builtin_str_replace::INST),195		("escapeStringBash", builtin_escape_string_bash::INST),196		("escapeStringDollars", builtin_escape_string_dollars::INST),197		("isEmpty", builtin_is_empty::INST),198		("equalsIgnoreCase", builtin_equals_ignore_case::INST),199		("splitLimit", builtin_splitlimit::INST),200		("splitLimitR", builtin_splitlimitr::INST),201		("split", builtin_split::INST),202		("asciiUpper", builtin_ascii_upper::INST),203		("asciiLower", builtin_ascii_lower::INST),204		("findSubstr", builtin_find_substr::INST),205		("parseInt", builtin_parse_int::INST),206		#[cfg(feature = "exp-bigint")]207		("bigint", builtin_bigint::INST),208		("parseOctal", builtin_parse_octal::INST),209		("parseHex", builtin_parse_hex::INST),210		("stringChars", builtin_string_chars::INST),211		("lstripChars", builtin_lstrip_chars::INST),212		("rstripChars", builtin_rstrip_chars::INST),213		("stripChars", builtin_strip_chars::INST),214		// Misc215		("length", builtin_length::INST),216		("get", builtin_get::INST),217		("startsWith", builtin_starts_with::INST),218		("endsWith", builtin_ends_with::INST),219		("assertEqual", builtin_assert_equal::INST),220		("mergePatch", builtin_merge_patch::INST),221		// Sets222		("setMember", builtin_set_member::INST),223		("setInter", builtin_set_inter::INST),224		("setDiff", builtin_set_diff::INST),225		("setUnion", builtin_set_union::INST),226		// Regex227		#[cfg(feature = "exp-regex")]228		("regexQuoteMeta", builtin_regex_quote_meta::INST),229		// Compat230		("__compare", builtin___compare::INST),231		("__compare_array", builtin___compare_array::INST),232		("__array_less", builtin___array_less::INST),233		("__array_greater", builtin___array_greater::INST),234		("__array_less_or_equal", builtin___array_less_or_equal::INST),235		(236			"__array_greater_or_equal",237			builtin___array_greater_or_equal::INST,238		),239	]240	.iter()241	.copied()242	{243		builder.method(name, builtin);244	}245246	builder.method(247		"extVar",248		builtin_ext_var {249			settings: settings.clone(),250		},251	);252	builder.method(253		"native",254		builtin_native {255			settings: settings.clone(),256		},257	);258	builder.method("trace", builtin_trace { settings });259	builder.method("id", FuncVal::Id);260261	#[cfg(feature = "exp-regex")]262	{263		// Regex264		let regex_cache = RegexCache::default();265		builder.method(266			"regexFullMatch",267			builtin_regex_full_match {268				cache: regex_cache.clone(),269			},270		);271		builder.method(272			"regexPartialMatch",273			builtin_regex_partial_match {274				cache: regex_cache.clone(),275			},276		);277		builder.method(278			"regexReplace",279			builtin_regex_replace {280				cache: regex_cache.clone(),281			},282		);283		builder.method(284			"regexGlobalReplace",285			builtin_regex_global_replace { cache: regex_cache },286		);287	};288289	builder.build()290}291292pub trait TracePrinter {293	fn print_trace(&self, loc: CallLocation, value: IStr);294}295296pub struct StdTracePrinter {297	resolver: PathResolver,298}299impl StdTracePrinter {300	pub fn new(resolver: PathResolver) -> Self {301		Self { resolver }302	}303}304impl TracePrinter for StdTracePrinter {305	fn print_trace(&self, loc: CallLocation, value: IStr) {306		eprint!("TRACE:");307		if let Some(loc) = loc.0 {308			let locs = loc.0.map_source_locations(&[loc.1]);309			eprint!(310				" {}:{}",311				loc.0.source_path().path().map_or_else(312					|| loc.0.source_path().to_string(),313					|p| self.resolver.resolve(p)314				),315				locs[0].line316			);317		}318		eprintln!(" {value}");319	}320}321322pub struct Settings {323	/// Used for `std.extVar`324	pub ext_vars: HashMap<IStr, TlaArg>,325	/// Used for `std.native`326	pub ext_natives: HashMap<IStr, FuncVal>,327	/// Used for `std.trace`328	pub trace_printer: Box<dyn TracePrinter>,329	/// Used for `std.thisFile`330	pub path_resolver: PathResolver,331}332333fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {334	let source_name = format!("<extvar:{name}>");335	Source::new_virtual(source_name.into(), code.into())336}337338#[derive(Trace, Clone)]339pub struct ContextInitializer {340	/// When we don't need to support legacy-this-file, we can reuse same context for all files341	#[cfg(not(feature = "legacy-this-file"))]342	context: jrsonnet_evaluator::Context,343	/// For `populate`344	#[cfg(not(feature = "legacy-this-file"))]345	stdlib_thunk: Thunk<Val>,346	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it347	#[cfg(feature = "legacy-this-file")]348	stdlib_obj: ObjValue,349	settings: Rc<RefCell<Settings>>,350}351impl ContextInitializer {352	pub fn new(s: State, resolver: PathResolver) -> Self {353		let settings = Settings {354			ext_vars: HashMap::new(),355			ext_natives: HashMap::new(),356			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),357			path_resolver: resolver,358		};359		let settings = Rc::new(RefCell::new(settings));360		let stdlib_obj = stdlib_uncached(settings.clone());361		#[cfg(not(feature = "legacy-this-file"))]362		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));363		#[cfg(feature = "legacy-this-file")]364		let _ = s;365		Self {366			#[cfg(not(feature = "legacy-this-file"))]367			context: {368				let mut context = ContextBuilder::with_capacity(s, 1);369				context.bind("std", stdlib_thunk.clone());370				context.build()371			},372			#[cfg(not(feature = "legacy-this-file"))]373			stdlib_thunk,374			#[cfg(feature = "legacy-this-file")]375			stdlib_obj,376			settings,377		}378	}379	pub fn settings(&self) -> Ref<Settings> {380		self.settings.borrow()381	}382	pub fn settings_mut(&self) -> RefMut<Settings> {383		self.settings.borrow_mut()384	}385	pub fn add_ext_var(&self, name: IStr, value: Val) {386		self.settings_mut()387			.ext_vars388			.insert(name, TlaArg::Val(value));389	}390	pub fn add_ext_str(&self, name: IStr, value: IStr) {391		self.settings_mut()392			.ext_vars393			.insert(name, TlaArg::String(value));394	}395	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {396		let code = code.into();397		let source = extvar_source(name, code.clone());398		let parsed = jrsonnet_parser::parse(399			&code,400			&jrsonnet_parser::ParserSettings {401				source: source.clone(),402			},403		)404		.map_err(|e| ImportSyntaxError {405			path: source,406			error: Box::new(e),407		})?;408		// self.data_mut().volatile_files.insert(source_name, code);409		self.settings_mut()410			.ext_vars411			.insert(name.into(), TlaArg::Code(parsed));412		Ok(())413	}414	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {415		self.settings_mut()416			.ext_natives417			.insert(name.into(), cb.into());418	}419}420impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {421	fn reserve_vars(&self) -> usize {422		1423	}424	#[cfg(not(feature = "legacy-this-file"))]425	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {426		self.context.clone()427	}428	#[cfg(not(feature = "legacy-this-file"))]429	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {430		builder.bind("std", self.stdlib_thunk.clone());431	}432	#[cfg(feature = "legacy-this-file")]433	fn populate(&self, source: Source, builder: &mut ContextBuilder) {434		let mut std = ObjValueBuilder::new();435		std.with_super(self.stdlib_obj.clone());436		std.field("thisFile").hide().value({437			let source_path = source.source_path();438			source_path.path().map_or_else(439				|| source_path.to_string(),440				|p| self.settings().path_resolver.resolve(p),441			)442		});443		let stdlib_with_this_file = std.build();444445		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));446	}447	fn as_any(&self) -> &dyn std::any::Any {448		self449	}450}451452pub trait StateExt {453	/// This method was previously implemented in jrsonnet-evaluator itself454	fn with_stdlib(&self);455}456457impl StateExt for State {458	fn with_stdlib(&self) {459		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());460		self.settings_mut().context_initializer = tb!(initializer);461	}462}
modifiedcrates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/std.jsonnet
+++ b/crates/jrsonnet-stdlib/src/std.jsonnet
@@ -2,12 +2,4 @@
   local std = self,
 
   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',
-
-  mapWithKey(func, obj)::
-    if !std.isFunction(func) then
-      error ('std.mapWithKey first param must be function, got ' + std.type(func))
-    else if !std.isObject(obj) then
-      error ('std.mapWithKey second param must be object, got ' + std.type(obj))
-    else
-      { [k]: func(k, obj[k]) for k in std.objectFields(obj) },
 }