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

difftreelog

perf move mapWithIndex to native

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

5 files changed

modifiedcrates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -54,7 +54,12 @@
 
 	#[must_use]
 	pub fn map(self, mapper: FuncVal) -> Self {
-		Self::new(MappedArray::new(self, mapper))
+		Self::new(<MappedArray<false>>::new(self, mapper))
+	}
+
+	#[must_use]
+	pub fn map_with_index(self, mapper: FuncVal) -> Self {
+		Self::new(<MappedArray<true>>::new(self, mapper))
 	}
 
 	pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -430,12 +430,12 @@
 }
 
 #[derive(Trace, Debug, Clone)]
-pub struct MappedArray {
+pub struct MappedArray<const WithIndex: bool> {
 	inner: ArrValue,
 	cached: Cc<RefCell<Vec<ArrayThunk<()>>>>,
 	mapper: FuncVal,
 }
-impl MappedArray {
+impl<const WithIndex: bool> MappedArray<WithIndex> {
 	pub fn new(inner: ArrValue, mapper: FuncVal) -> Self {
 		let len = inner.len();
 		Self {
@@ -444,8 +444,15 @@
 			mapper,
 		}
 	}
+	fn evaluate(&self, index: usize, value: Val) -> Result<Val> {
+		if WithIndex {
+			self.mapper.evaluate_simple(&(index, value), false)
+		} else {
+			self.mapper.evaluate_simple(&(value,), false)
+		}
+	}
 }
-impl ArrayLike for MappedArray {
+impl<const WithIndex: bool> ArrayLike for MappedArray<WithIndex> {
 	fn len(&self) -> usize {
 		self.cached.borrow().len()
 	}
@@ -472,7 +479,7 @@
 			.get(index)
 			.transpose()
 			.expect("index checked")
-			.and_then(|r| self.mapper.evaluate_simple(&(r,), false));
+			.and_then(|r| self.evaluate(index, r));
 
 		let new_value = match val {
 			Ok(v) => v,
@@ -486,12 +493,12 @@
 	}
 	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
 		#[derive(Trace)]
-		struct ArrayElement {
-			arr_thunk: MappedArray,
+		struct ArrayElement<const WithIndex: bool> {
+			arr_thunk: MappedArray<WithIndex>,
 			index: usize,
 		}
 
-		impl ThunkValue for ArrayElement {
+		impl<const WithIndex: bool> ThunkValue for ArrayElement<WithIndex> {
 			type Output = Val;
 
 			fn get(self: Box<Self>) -> Result<Self::Output> {
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -62,6 +62,12 @@
 }
 
 #[builtin]
+pub fn builtin_map_with_index(func: FuncVal, arr: IndexableVal) -> ArrValue {
+	let arr = arr.to_array();
+	arr.map_with_index(func)
+}
+
+#[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		("flatMap", builtin_flatmap::INST),82		("filter", builtin_filter::INST),83		("foldl", builtin_foldl::INST),84		("foldr", builtin_foldr::INST),85		("range", builtin_range::INST),86		("join", builtin_join::INST),87		("reverse", builtin_reverse::INST),88		("any", builtin_any::INST),89		("all", builtin_all::INST),90		("member", builtin_member::INST),91		("contains", builtin_contains::INST),92		("count", builtin_count::INST),93		("avg", builtin_avg::INST),94		("removeAt", builtin_remove_at::INST),95		("remove", builtin_remove::INST),96		("flattenArrays", builtin_flatten_arrays::INST),97		("flattenDeepArray", builtin_flatten_deep_array::INST),98		("prune", builtin_prune::INST),99		("filterMap", builtin_filter_map::INST),100		// Math101		("abs", builtin_abs::INST),102		("sign", builtin_sign::INST),103		("max", builtin_max::INST),104		("min", builtin_min::INST),105		("clamp", builtin_clamp::INST),106		("sum", builtin_sum::INST),107		("modulo", builtin_modulo::INST),108		("floor", builtin_floor::INST),109		("ceil", builtin_ceil::INST),110		("log", builtin_log::INST),111		("pow", builtin_pow::INST),112		("sqrt", builtin_sqrt::INST),113		("sin", builtin_sin::INST),114		("cos", builtin_cos::INST),115		("tan", builtin_tan::INST),116		("asin", builtin_asin::INST),117		("acos", builtin_acos::INST),118		("atan", builtin_atan::INST),119		("atan2", builtin_atan2::INST),120		("exp", builtin_exp::INST),121		("mantissa", builtin_mantissa::INST),122		("exponent", builtin_exponent::INST),123		("round", builtin_round::INST),124		("isEven", builtin_is_even::INST),125		("isOdd", builtin_is_odd::INST),126		("isInteger", builtin_is_integer::INST),127		("isDecimal", builtin_is_decimal::INST),128		// Operator129		("mod", builtin_mod::INST),130		("primitiveEquals", builtin_primitive_equals::INST),131		("equals", builtin_equals::INST),132		("xor", builtin_xor::INST),133		("xnor", builtin_xnor::INST),134		("format", builtin_format::INST),135		// Sort136		("sort", builtin_sort::INST),137		("uniq", builtin_uniq::INST),138		("set", builtin_set::INST),139		("minArray", builtin_min_array::INST),140		("maxArray", builtin_max_array::INST),141		// Hash142		("md5", builtin_md5::INST),143		("sha1", builtin_sha1::INST),144		("sha256", builtin_sha256::INST),145		("sha512", builtin_sha512::INST),146		("sha3", builtin_sha3::INST),147		// Encoding148		("encodeUTF8", builtin_encode_utf8::INST),149		("decodeUTF8", builtin_decode_utf8::INST),150		("base64", builtin_base64::INST),151		("base64Decode", builtin_base64_decode::INST),152		("base64DecodeBytes", builtin_base64_decode_bytes::INST),153		// Objects154		("objectFieldsEx", builtin_object_fields_ex::INST),155		("objectFields", builtin_object_fields::INST),156		("objectFieldsAll", builtin_object_fields_all::INST),157		("objectValues", builtin_object_values::INST),158		("objectValuesAll", builtin_object_values_all::INST),159		("objectKeysValues", builtin_object_keys_values::INST),160		("objectKeysValuesAll", builtin_object_keys_values_all::INST),161		("objectHasEx", builtin_object_has_ex::INST),162		("objectHas", builtin_object_has::INST),163		("objectHasAll", builtin_object_has_all::INST),164		("objectRemoveKey", builtin_object_remove_key::INST),165		// Manifest166		("escapeStringJson", builtin_escape_string_json::INST),167		("escapeStringPython", builtin_escape_string_python::INST),168		("escapeStringXML", builtin_escape_string_xml::INST),169		("manifestJsonEx", builtin_manifest_json_ex::INST),170		("manifestJson", builtin_manifest_json::INST),171		("manifestJsonMinified", builtin_manifest_json_minified::INST),172		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),173		("manifestYamlStream", builtin_manifest_yaml_stream::INST),174		("manifestTomlEx", builtin_manifest_toml_ex::INST),175		("manifestToml", builtin_manifest_toml::INST),176		("toString", builtin_to_string::INST),177		("manifestPython", builtin_manifest_python::INST),178		("manifestPythonVars", builtin_manifest_python_vars::INST),179		("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),180		// Parse181		("parseJson", builtin_parse_json::INST),182		("parseYaml", builtin_parse_yaml::INST),183		// Strings184		("codepoint", builtin_codepoint::INST),185		("substr", builtin_substr::INST),186		("char", builtin_char::INST),187		("strReplace", builtin_str_replace::INST),188		("escapeStringBash", builtin_escape_string_bash::INST),189		("escapeStringDollars", builtin_escape_string_dollars::INST),190		("isEmpty", builtin_is_empty::INST),191		("equalsIgnoreCase", builtin_equals_ignore_case::INST),192		("splitLimit", builtin_splitlimit::INST),193		("splitLimitR", builtin_splitlimitr::INST),194		("split", builtin_split::INST),195		("asciiUpper", builtin_ascii_upper::INST),196		("asciiLower", builtin_ascii_lower::INST),197		("findSubstr", builtin_find_substr::INST),198		("parseInt", builtin_parse_int::INST),199		#[cfg(feature = "exp-bigint")]200		("bigint", builtin_bigint::INST),201		("parseOctal", builtin_parse_octal::INST),202		("parseHex", builtin_parse_hex::INST),203		("stringChars", builtin_string_chars::INST),204		("lstripChars", builtin_lstrip_chars::INST),205		("rstripChars", builtin_rstrip_chars::INST),206		("stripChars", builtin_strip_chars::INST),207		// Misc208		("length", builtin_length::INST),209		("get", builtin_get::INST),210		("startsWith", builtin_starts_with::INST),211		("endsWith", builtin_ends_with::INST),212		// Sets213		("setMember", builtin_set_member::INST),214		("setInter", builtin_set_inter::INST),215		("setDiff", builtin_set_diff::INST),216		("setUnion", builtin_set_union::INST),217		// Regex218		#[cfg(feature = "exp-regex")]219		("regexQuoteMeta", builtin_regex_quote_meta::INST),220		// Compat221		("__compare", builtin___compare::INST),222		("__compare_array", builtin___compare_array::INST),223		("__array_less", builtin___array_less::INST),224		("__array_greater", builtin___array_greater::INST),225		("__array_less_or_equal", builtin___array_less_or_equal::INST),226		(227			"__array_greater_or_equal",228			builtin___array_greater_or_equal::INST,229		),230	]231	.iter()232	.copied()233	{234		builder.method(name, builtin);235	}236237	builder.method(238		"extVar",239		builtin_ext_var {240			settings: settings.clone(),241		},242	);243	builder.method(244		"native",245		builtin_native {246			settings: settings.clone(),247		},248	);249	builder.method("trace", builtin_trace { settings });250	builder.method("id", FuncVal::Id);251252	#[cfg(feature = "exp-regex")]253	{254		// Regex255		let regex_cache = RegexCache::default();256		builder.method(257			"regexFullMatch",258			builtin_regex_full_match {259				cache: regex_cache.clone(),260			},261		);262		builder.method(263			"regexPartialMatch",264			builtin_regex_partial_match {265				cache: regex_cache.clone(),266			},267		);268		builder.method(269			"regexReplace",270			builtin_regex_replace {271				cache: regex_cache.clone(),272			},273		);274		builder.method(275			"regexGlobalReplace",276			builtin_regex_global_replace { cache: regex_cache },277		);278	};279280	builder.build()281}282283pub trait TracePrinter {284	fn print_trace(&self, loc: CallLocation, value: IStr);285}286287pub struct StdTracePrinter {288	resolver: PathResolver,289}290impl StdTracePrinter {291	pub fn new(resolver: PathResolver) -> Self {292		Self { resolver }293	}294}295impl TracePrinter for StdTracePrinter {296	fn print_trace(&self, loc: CallLocation, value: IStr) {297		eprint!("TRACE:");298		if let Some(loc) = loc.0 {299			let locs = loc.0.map_source_locations(&[loc.1]);300			eprint!(301				" {}:{}",302				loc.0.source_path().path().map_or_else(303					|| loc.0.source_path().to_string(),304					|p| self.resolver.resolve(p)305				),306				locs[0].line307			);308		}309		eprintln!(" {value}");310	}311}312313pub struct Settings {314	/// Used for `std.extVar`315	pub ext_vars: HashMap<IStr, TlaArg>,316	/// Used for `std.native`317	pub ext_natives: HashMap<IStr, FuncVal>,318	/// Used for `std.trace`319	pub trace_printer: Box<dyn TracePrinter>,320	/// Used for `std.thisFile`321	pub path_resolver: PathResolver,322}323324fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {325	let source_name = format!("<extvar:{name}>");326	Source::new_virtual(source_name.into(), code.into())327}328329#[derive(Trace, Clone)]330pub struct ContextInitializer {331	/// When we don't need to support legacy-this-file, we can reuse same context for all files332	#[cfg(not(feature = "legacy-this-file"))]333	context: jrsonnet_evaluator::Context,334	/// For `populate`335	#[cfg(not(feature = "legacy-this-file"))]336	stdlib_thunk: Thunk<Val>,337	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it338	#[cfg(feature = "legacy-this-file")]339	stdlib_obj: ObjValue,340	settings: Rc<RefCell<Settings>>,341}342impl ContextInitializer {343	pub fn new(s: State, resolver: PathResolver) -> Self {344		let settings = Settings {345			ext_vars: HashMap::new(),346			ext_natives: HashMap::new(),347			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),348			path_resolver: resolver,349		};350		let settings = Rc::new(RefCell::new(settings));351		let stdlib_obj = stdlib_uncached(settings.clone());352		#[cfg(not(feature = "legacy-this-file"))]353		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));354		#[cfg(feature = "legacy-this-file")]355		let _ = s;356		Self {357			#[cfg(not(feature = "legacy-this-file"))]358			context: {359				let mut context = ContextBuilder::with_capacity(s, 1);360				context.bind("std", stdlib_thunk.clone());361				context.build()362			},363			#[cfg(not(feature = "legacy-this-file"))]364			stdlib_thunk,365			#[cfg(feature = "legacy-this-file")]366			stdlib_obj,367			settings,368		}369	}370	pub fn settings(&self) -> Ref<Settings> {371		self.settings.borrow()372	}373	pub fn settings_mut(&self) -> RefMut<Settings> {374		self.settings.borrow_mut()375	}376	pub fn add_ext_var(&self, name: IStr, value: Val) {377		self.settings_mut()378			.ext_vars379			.insert(name, TlaArg::Val(value));380	}381	pub fn add_ext_str(&self, name: IStr, value: IStr) {382		self.settings_mut()383			.ext_vars384			.insert(name, TlaArg::String(value));385	}386	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {387		let code = code.into();388		let source = extvar_source(name, code.clone());389		let parsed = jrsonnet_parser::parse(390			&code,391			&jrsonnet_parser::ParserSettings {392				source: source.clone(),393			},394		)395		.map_err(|e| ImportSyntaxError {396			path: source,397			error: Box::new(e),398		})?;399		// self.data_mut().volatile_files.insert(source_name, code);400		self.settings_mut()401			.ext_vars402			.insert(name.into(), TlaArg::Code(parsed));403		Ok(())404	}405	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {406		self.settings_mut()407			.ext_natives408			.insert(name.into(), cb.into());409	}410}411impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {412	fn reserve_vars(&self) -> usize {413		1414	}415	#[cfg(not(feature = "legacy-this-file"))]416	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {417		self.context.clone()418	}419	#[cfg(not(feature = "legacy-this-file"))]420	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {421		builder.bind("std", self.stdlib_thunk.clone());422	}423	#[cfg(feature = "legacy-this-file")]424	fn populate(&self, source: Source, builder: &mut ContextBuilder) {425		let mut std = ObjValueBuilder::new();426		std.with_super(self.stdlib_obj.clone());427		std.field("thisFile").hide().value({428			let source_path = source.source_path();429			source_path.path().map_or_else(430				|| source_path.to_string(),431				|p| self.settings().path_resolver.resolve(p),432			)433		});434		let stdlib_with_this_file = std.build();435436		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));437	}438	fn as_any(&self) -> &dyn std::any::Any {439		self440	}441}442443pub trait StateExt {444	/// This method was previously implemented in jrsonnet-evaluator itself445	fn with_stdlib(&self);446}447448impl StateExt for State {449	fn with_stdlib(&self) {450		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());451		self.settings_mut().context_initializer = tb!(initializer);452	}453}
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		("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		("reverse", builtin_reverse::INST),89		("any", builtin_any::INST),90		("all", builtin_all::INST),91		("member", builtin_member::INST),92		("contains", builtin_contains::INST),93		("count", builtin_count::INST),94		("avg", builtin_avg::INST),95		("removeAt", builtin_remove_at::INST),96		("remove", builtin_remove::INST),97		("flattenArrays", builtin_flatten_arrays::INST),98		("flattenDeepArray", builtin_flatten_deep_array::INST),99		("prune", builtin_prune::INST),100		("filterMap", builtin_filter_map::INST),101		// Math102		("abs", builtin_abs::INST),103		("sign", builtin_sign::INST),104		("max", builtin_max::INST),105		("min", builtin_min::INST),106		("clamp", builtin_clamp::INST),107		("sum", builtin_sum::INST),108		("modulo", builtin_modulo::INST),109		("floor", builtin_floor::INST),110		("ceil", builtin_ceil::INST),111		("log", builtin_log::INST),112		("pow", builtin_pow::INST),113		("sqrt", builtin_sqrt::INST),114		("sin", builtin_sin::INST),115		("cos", builtin_cos::INST),116		("tan", builtin_tan::INST),117		("asin", builtin_asin::INST),118		("acos", builtin_acos::INST),119		("atan", builtin_atan::INST),120		("atan2", builtin_atan2::INST),121		("exp", builtin_exp::INST),122		("mantissa", builtin_mantissa::INST),123		("exponent", builtin_exponent::INST),124		("round", builtin_round::INST),125		("isEven", builtin_is_even::INST),126		("isOdd", builtin_is_odd::INST),127		("isInteger", builtin_is_integer::INST),128		("isDecimal", builtin_is_decimal::INST),129		// Operator130		("mod", builtin_mod::INST),131		("primitiveEquals", builtin_primitive_equals::INST),132		("equals", builtin_equals::INST),133		("xor", builtin_xor::INST),134		("xnor", builtin_xnor::INST),135		("format", builtin_format::INST),136		// Sort137		("sort", builtin_sort::INST),138		("uniq", builtin_uniq::INST),139		("set", builtin_set::INST),140		("minArray", builtin_min_array::INST),141		("maxArray", builtin_max_array::INST),142		// Hash143		("md5", builtin_md5::INST),144		("sha1", builtin_sha1::INST),145		("sha256", builtin_sha256::INST),146		("sha512", builtin_sha512::INST),147		("sha3", builtin_sha3::INST),148		// Encoding149		("encodeUTF8", builtin_encode_utf8::INST),150		("decodeUTF8", builtin_decode_utf8::INST),151		("base64", builtin_base64::INST),152		("base64Decode", builtin_base64_decode::INST),153		("base64DecodeBytes", builtin_base64_decode_bytes::INST),154		// Objects155		("objectFieldsEx", builtin_object_fields_ex::INST),156		("objectFields", builtin_object_fields::INST),157		("objectFieldsAll", builtin_object_fields_all::INST),158		("objectValues", builtin_object_values::INST),159		("objectValuesAll", builtin_object_values_all::INST),160		("objectKeysValues", builtin_object_keys_values::INST),161		("objectKeysValuesAll", builtin_object_keys_values_all::INST),162		("objectHasEx", builtin_object_has_ex::INST),163		("objectHas", builtin_object_has::INST),164		("objectHasAll", builtin_object_has_all::INST),165		("objectRemoveKey", builtin_object_remove_key::INST),166		// Manifest167		("escapeStringJson", builtin_escape_string_json::INST),168		("escapeStringPython", builtin_escape_string_python::INST),169		("escapeStringXML", builtin_escape_string_xml::INST),170		("manifestJsonEx", builtin_manifest_json_ex::INST),171		("manifestJson", builtin_manifest_json::INST),172		("manifestJsonMinified", builtin_manifest_json_minified::INST),173		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),174		("manifestYamlStream", builtin_manifest_yaml_stream::INST),175		("manifestTomlEx", builtin_manifest_toml_ex::INST),176		("manifestToml", builtin_manifest_toml::INST),177		("toString", builtin_to_string::INST),178		("manifestPython", builtin_manifest_python::INST),179		("manifestPythonVars", builtin_manifest_python_vars::INST),180		("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),181		// Parse182		("parseJson", builtin_parse_json::INST),183		("parseYaml", builtin_parse_yaml::INST),184		// Strings185		("codepoint", builtin_codepoint::INST),186		("substr", builtin_substr::INST),187		("char", builtin_char::INST),188		("strReplace", builtin_str_replace::INST),189		("escapeStringBash", builtin_escape_string_bash::INST),190		("escapeStringDollars", builtin_escape_string_dollars::INST),191		("isEmpty", builtin_is_empty::INST),192		("equalsIgnoreCase", builtin_equals_ignore_case::INST),193		("splitLimit", builtin_splitlimit::INST),194		("splitLimitR", builtin_splitlimitr::INST),195		("split", builtin_split::INST),196		("asciiUpper", builtin_ascii_upper::INST),197		("asciiLower", builtin_ascii_lower::INST),198		("findSubstr", builtin_find_substr::INST),199		("parseInt", builtin_parse_int::INST),200		#[cfg(feature = "exp-bigint")]201		("bigint", builtin_bigint::INST),202		("parseOctal", builtin_parse_octal::INST),203		("parseHex", builtin_parse_hex::INST),204		("stringChars", builtin_string_chars::INST),205		("lstripChars", builtin_lstrip_chars::INST),206		("rstripChars", builtin_rstrip_chars::INST),207		("stripChars", builtin_strip_chars::INST),208		// Misc209		("length", builtin_length::INST),210		("get", builtin_get::INST),211		("startsWith", builtin_starts_with::INST),212		("endsWith", builtin_ends_with::INST),213		// Sets214		("setMember", builtin_set_member::INST),215		("setInter", builtin_set_inter::INST),216		("setDiff", builtin_set_diff::INST),217		("setUnion", builtin_set_union::INST),218		// Regex219		#[cfg(feature = "exp-regex")]220		("regexQuoteMeta", builtin_regex_quote_meta::INST),221		// Compat222		("__compare", builtin___compare::INST),223		("__compare_array", builtin___compare_array::INST),224		("__array_less", builtin___array_less::INST),225		("__array_greater", builtin___array_greater::INST),226		("__array_less_or_equal", builtin___array_less_or_equal::INST),227		(228			"__array_greater_or_equal",229			builtin___array_greater_or_equal::INST,230		),231	]232	.iter()233	.copied()234	{235		builder.method(name, builtin);236	}237238	builder.method(239		"extVar",240		builtin_ext_var {241			settings: settings.clone(),242		},243	);244	builder.method(245		"native",246		builtin_native {247			settings: settings.clone(),248		},249	);250	builder.method("trace", builtin_trace { settings });251	builder.method("id", FuncVal::Id);252253	#[cfg(feature = "exp-regex")]254	{255		// Regex256		let regex_cache = RegexCache::default();257		builder.method(258			"regexFullMatch",259			builtin_regex_full_match {260				cache: regex_cache.clone(),261			},262		);263		builder.method(264			"regexPartialMatch",265			builtin_regex_partial_match {266				cache: regex_cache.clone(),267			},268		);269		builder.method(270			"regexReplace",271			builtin_regex_replace {272				cache: regex_cache.clone(),273			},274		);275		builder.method(276			"regexGlobalReplace",277			builtin_regex_global_replace { cache: regex_cache },278		);279	};280281	builder.build()282}283284pub trait TracePrinter {285	fn print_trace(&self, loc: CallLocation, value: IStr);286}287288pub struct StdTracePrinter {289	resolver: PathResolver,290}291impl StdTracePrinter {292	pub fn new(resolver: PathResolver) -> Self {293		Self { resolver }294	}295}296impl TracePrinter for StdTracePrinter {297	fn print_trace(&self, loc: CallLocation, value: IStr) {298		eprint!("TRACE:");299		if let Some(loc) = loc.0 {300			let locs = loc.0.map_source_locations(&[loc.1]);301			eprint!(302				" {}:{}",303				loc.0.source_path().path().map_or_else(304					|| loc.0.source_path().to_string(),305					|p| self.resolver.resolve(p)306				),307				locs[0].line308			);309		}310		eprintln!(" {value}");311	}312}313314pub struct Settings {315	/// Used for `std.extVar`316	pub ext_vars: HashMap<IStr, TlaArg>,317	/// Used for `std.native`318	pub ext_natives: HashMap<IStr, FuncVal>,319	/// Used for `std.trace`320	pub trace_printer: Box<dyn TracePrinter>,321	/// Used for `std.thisFile`322	pub path_resolver: PathResolver,323}324325fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {326	let source_name = format!("<extvar:{name}>");327	Source::new_virtual(source_name.into(), code.into())328}329330#[derive(Trace, Clone)]331pub struct ContextInitializer {332	/// When we don't need to support legacy-this-file, we can reuse same context for all files333	#[cfg(not(feature = "legacy-this-file"))]334	context: jrsonnet_evaluator::Context,335	/// For `populate`336	#[cfg(not(feature = "legacy-this-file"))]337	stdlib_thunk: Thunk<Val>,338	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it339	#[cfg(feature = "legacy-this-file")]340	stdlib_obj: ObjValue,341	settings: Rc<RefCell<Settings>>,342}343impl ContextInitializer {344	pub fn new(s: State, resolver: PathResolver) -> Self {345		let settings = Settings {346			ext_vars: HashMap::new(),347			ext_natives: HashMap::new(),348			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),349			path_resolver: resolver,350		};351		let settings = Rc::new(RefCell::new(settings));352		let stdlib_obj = stdlib_uncached(settings.clone());353		#[cfg(not(feature = "legacy-this-file"))]354		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));355		#[cfg(feature = "legacy-this-file")]356		let _ = s;357		Self {358			#[cfg(not(feature = "legacy-this-file"))]359			context: {360				let mut context = ContextBuilder::with_capacity(s, 1);361				context.bind("std", stdlib_thunk.clone());362				context.build()363			},364			#[cfg(not(feature = "legacy-this-file"))]365			stdlib_thunk,366			#[cfg(feature = "legacy-this-file")]367			stdlib_obj,368			settings,369		}370	}371	pub fn settings(&self) -> Ref<Settings> {372		self.settings.borrow()373	}374	pub fn settings_mut(&self) -> RefMut<Settings> {375		self.settings.borrow_mut()376	}377	pub fn add_ext_var(&self, name: IStr, value: Val) {378		self.settings_mut()379			.ext_vars380			.insert(name, TlaArg::Val(value));381	}382	pub fn add_ext_str(&self, name: IStr, value: IStr) {383		self.settings_mut()384			.ext_vars385			.insert(name, TlaArg::String(value));386	}387	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {388		let code = code.into();389		let source = extvar_source(name, code.clone());390		let parsed = jrsonnet_parser::parse(391			&code,392			&jrsonnet_parser::ParserSettings {393				source: source.clone(),394			},395		)396		.map_err(|e| ImportSyntaxError {397			path: source,398			error: Box::new(e),399		})?;400		// self.data_mut().volatile_files.insert(source_name, code);401		self.settings_mut()402			.ext_vars403			.insert(name.into(), TlaArg::Code(parsed));404		Ok(())405	}406	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {407		self.settings_mut()408			.ext_natives409			.insert(name.into(), cb.into());410	}411}412impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {413	fn reserve_vars(&self) -> usize {414		1415	}416	#[cfg(not(feature = "legacy-this-file"))]417	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {418		self.context.clone()419	}420	#[cfg(not(feature = "legacy-this-file"))]421	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {422		builder.bind("std", self.stdlib_thunk.clone());423	}424	#[cfg(feature = "legacy-this-file")]425	fn populate(&self, source: Source, builder: &mut ContextBuilder) {426		let mut std = ObjValueBuilder::new();427		std.with_super(self.stdlib_obj.clone());428		std.field("thisFile").hide().value({429			let source_path = source.source_path();430			source_path.path().map_or_else(431				|| source_path.to_string(),432				|p| self.settings().path_resolver.resolve(p),433			)434		});435		let stdlib_with_this_file = std.build();436437		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));438	}439	fn as_any(&self) -> &dyn std::any::Any {440		self441	}442}443444pub trait StateExt {445	/// This method was previously implemented in jrsonnet-evaluator itself446	fn with_stdlib(&self);447}448449impl StateExt for State {450	fn with_stdlib(&self) {451		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());452		self.settings_mut().context_initializer = tb!(initializer);453	}454}
modifiedcrates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/std.jsonnet
+++ b/crates/jrsonnet-stdlib/src/std.jsonnet
@@ -3,14 +3,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',
 
-  mapWithIndex(func, arr)::
-    if !std.isFunction(func) then
-      error ('std.mapWithIndex first param must be function, got ' + std.type(func))
-    else if !std.isArray(arr) && !std.isString(arr) then
-      error ('std.mapWithIndex second param must be array, got ' + std.type(arr))
-    else
-      std.makeArray(std.length(arr), function(i) func(i, arr[i])),
-
   mapWithKey(func, obj)::
     if !std.isFunction(func) then
       error ('std.mapWithKey first param must be function, got ' + std.type(func))