git.delta.rocks / jrsonnet / refs/commits / 8f8545cd220d

difftreelog

feat implement std.flattenDeepArray builtin

Yaroslav Bolyukin2024-04-07parent: #69c135a.patch.diff
in: master

2 files changed

modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -302,3 +302,21 @@
 	}
 	flatten_inner(&arrs)
 }
+
+#[builtin]
+pub fn builtin_flatten_deep_array(value: Val) -> Result<Vec<Val>> {
+	fn process(value: Val, out: &mut Vec<Val>) -> Result<()> {
+		match value {
+			Val::Arr(arr) => {
+				for ele in arr.iter() {
+					process(ele?, out)?;
+				}
+			}
+			_ => out.push(value),
+		}
+		Ok(())
+	}
+	let mut out = Vec::new();
+	process(value, &mut out)?;
+	Ok(out)
+}
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::*;46#[cfg(feature = "exp-regex")]47mod regex;48#[cfg(feature = "exp-regex")]49pub use crate::regex::*;5051pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {52	let mut builder = ObjValueBuilder::new();5354	let expr = expr::stdlib_expr();55	let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)56		.expect("stdlib.jsonnet should have no errors")57		.as_obj()58		.expect("stdlib.jsonnet should evaluate to object");5960	builder.with_super(eval);6162	for (name, builtin) in [63		// Types64		("type", builtin_type::INST),65		("isString", builtin_is_string::INST),66		("isNumber", builtin_is_number::INST),67		("isBoolean", builtin_is_boolean::INST),68		("isObject", builtin_is_object::INST),69		("isArray", builtin_is_array::INST),70		("isFunction", builtin_is_function::INST),71		// Arrays72		("makeArray", builtin_make_array::INST),73		("repeat", builtin_repeat::INST),74		("slice", builtin_slice::INST),75		("map", builtin_map::INST),76		("flatMap", builtin_flatmap::INST),77		("filter", builtin_filter::INST),78		("foldl", builtin_foldl::INST),79		("foldr", builtin_foldr::INST),80		("range", builtin_range::INST),81		("join", builtin_join::INST),82		("reverse", builtin_reverse::INST),83		("any", builtin_any::INST),84		("all", builtin_all::INST),85		("member", builtin_member::INST),86		("contains", builtin_contains::INST),87		("count", builtin_count::INST),88		("avg", builtin_avg::INST),89		("removeAt", builtin_remove_at::INST),90		("remove", builtin_remove::INST),91		("flattenArrays", builtin_flatten_arrays::INST),92		("filterMap", builtin_filter_map::INST),93		// Math94		("abs", builtin_abs::INST),95		("sign", builtin_sign::INST),96		("max", builtin_max::INST),97		("min", builtin_min::INST),98		("sum", builtin_sum::INST),99		("modulo", builtin_modulo::INST),100		("floor", builtin_floor::INST),101		("ceil", builtin_ceil::INST),102		("log", builtin_log::INST),103		("pow", builtin_pow::INST),104		("sqrt", builtin_sqrt::INST),105		("sin", builtin_sin::INST),106		("cos", builtin_cos::INST),107		("tan", builtin_tan::INST),108		("asin", builtin_asin::INST),109		("acos", builtin_acos::INST),110		("atan", builtin_atan::INST),111		("atan2", builtin_atan2::INST),112		("exp", builtin_exp::INST),113		("mantissa", builtin_mantissa::INST),114		("exponent", builtin_exponent::INST),115		("round", builtin_round::INST),116		("isEven", builtin_is_even::INST),117		("isOdd", builtin_is_odd::INST),118		("isInteger", builtin_is_integer::INST),119		("isDecimal", builtin_is_decimal::INST),120		// Operator121		("mod", builtin_mod::INST),122		("primitiveEquals", builtin_primitive_equals::INST),123		("equals", builtin_equals::INST),124		("xor", builtin_xor::INST),125		("xnor", builtin_xnor::INST),126		("format", builtin_format::INST),127		// Sort128		("sort", builtin_sort::INST),129		("uniq", builtin_uniq::INST),130		("set", builtin_set::INST),131		("minArray", builtin_min_array::INST),132		("maxArray", builtin_max_array::INST),133		// Hash134		("md5", builtin_md5::INST),135		("sha1", builtin_sha1::INST),136		("sha256", builtin_sha256::INST),137		("sha512", builtin_sha512::INST),138		("sha3", builtin_sha3::INST),139		// Encoding140		("encodeUTF8", builtin_encode_utf8::INST),141		("decodeUTF8", builtin_decode_utf8::INST),142		("base64", builtin_base64::INST),143		("base64Decode", builtin_base64_decode::INST),144		("base64DecodeBytes", builtin_base64_decode_bytes::INST),145		// Objects146		("objectFieldsEx", builtin_object_fields_ex::INST),147		("objectFields", builtin_object_fields::INST),148		("objectFieldsAll", builtin_object_fields_all::INST),149		("objectValues", builtin_object_values::INST),150		("objectValuesAll", builtin_object_values_all::INST),151		("objectKeysValues", builtin_object_keys_values::INST),152		("objectKeysValuesAll", builtin_object_keys_values_all::INST),153		("objectHasEx", builtin_object_has_ex::INST),154		("objectHas", builtin_object_has::INST),155		("objectHasAll", builtin_object_has_all::INST),156		("objectRemoveKey", builtin_object_remove_key::INST),157		// Manifest158		("escapeStringJson", builtin_escape_string_json::INST),159		("manifestJsonEx", builtin_manifest_json_ex::INST),160		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),161		("manifestTomlEx", builtin_manifest_toml_ex::INST),162		("toString", builtin_to_string::INST),163		// Parsing164		("parseJson", builtin_parse_json::INST),165		("parseYaml", builtin_parse_yaml::INST),166		// Strings167		("codepoint", builtin_codepoint::INST),168		("substr", builtin_substr::INST),169		("char", builtin_char::INST),170		("strReplace", builtin_str_replace::INST),171		("isEmpty", builtin_is_empty::INST),172		("equalsIgnoreCase", builtin_equals_ignore_case::INST),173		("splitLimit", builtin_splitlimit::INST),174		("asciiUpper", builtin_ascii_upper::INST),175		("asciiLower", builtin_ascii_lower::INST),176		("findSubstr", builtin_find_substr::INST),177		("parseInt", builtin_parse_int::INST),178		#[cfg(feature = "exp-bigint")]179		("bigint", builtin_bigint::INST),180		("parseOctal", builtin_parse_octal::INST),181		("parseHex", builtin_parse_hex::INST),182		("stringChars", builtin_string_chars::INST),183		// Misc184		("length", builtin_length::INST),185		("startsWith", builtin_starts_with::INST),186		("endsWith", builtin_ends_with::INST),187		// Sets188		("setMember", builtin_set_member::INST),189		("setInter", builtin_set_inter::INST),190		("setDiff", builtin_set_diff::INST),191		("setUnion", builtin_set_union::INST),192		// Regex193		#[cfg(feature = "exp-regex")]194		("regexQuoteMeta", builtin_regex_quote_meta::INST),195		// Compat196		("__compare", builtin___compare::INST),197	]198	.iter()199	.cloned()200	{201		builder.method(name, builtin);202	}203204	builder.method(205		"extVar",206		builtin_ext_var {207			settings: settings.clone(),208		},209	);210	builder.method(211		"native",212		builtin_native {213			settings: settings.clone(),214		},215	);216	builder.method("trace", builtin_trace { settings });217	builder.method("id", FuncVal::Id);218219	#[cfg(feature = "exp-regex")]220	{221		// Regex222		let regex_cache = RegexCache::default();223		builder.method(224			"regexFullMatch",225			builtin_regex_full_match {226				cache: regex_cache.clone(),227			},228		);229		builder.method(230			"regexPartialMatch",231			builtin_regex_partial_match {232				cache: regex_cache.clone(),233			},234		);235		builder.method(236			"regexReplace",237			builtin_regex_replace {238				cache: regex_cache.clone(),239			},240		);241		builder.method(242			"regexGlobalReplace",243			builtin_regex_global_replace {244				cache: regex_cache.clone(),245			},246		);247	};248249	builder.build()250}251252pub trait TracePrinter {253	fn print_trace(&self, loc: CallLocation, value: IStr);254}255256pub struct StdTracePrinter {257	resolver: PathResolver,258}259impl StdTracePrinter {260	pub fn new(resolver: PathResolver) -> Self {261		Self { resolver }262	}263}264impl TracePrinter for StdTracePrinter {265	fn print_trace(&self, loc: CallLocation, value: IStr) {266		eprint!("TRACE:");267		if let Some(loc) = loc.0 {268			let locs = loc.0.map_source_locations(&[loc.1]);269			eprint!(270				" {}:{}",271				match loc.0.source_path().path() {272					Some(p) => self.resolver.resolve(p),273					None => loc.0.source_path().to_string(),274				},275				locs[0].line276			);277		}278		eprintln!(" {value}");279	}280}281282pub struct Settings {283	/// Used for `std.extVar`284	pub ext_vars: HashMap<IStr, TlaArg>,285	/// Used for `std.native`286	pub ext_natives: HashMap<IStr, FuncVal>,287	/// Used for `std.trace`288	pub trace_printer: Box<dyn TracePrinter>,289	/// Used for `std.thisFile`290	pub path_resolver: PathResolver,291}292293fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {294	let source_name = format!("<extvar:{name}>");295	Source::new_virtual(source_name.into(), code.into())296}297298#[derive(Trace, Clone)]299pub struct ContextInitializer {300	/// When we don't need to support legacy-this-file, we can reuse same context for all files301	#[cfg(not(feature = "legacy-this-file"))]302	context: jrsonnet_evaluator::Context,303	/// For `populate`304	#[cfg(not(feature = "legacy-this-file"))]305	stdlib_thunk: Thunk<Val>,306	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it307	#[cfg(feature = "legacy-this-file")]308	stdlib_obj: ObjValue,309	settings: Rc<RefCell<Settings>>,310}311impl ContextInitializer {312	pub fn new(_s: State, resolver: PathResolver) -> Self {313		let settings = Settings {314			ext_vars: Default::default(),315			ext_natives: Default::default(),316			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),317			path_resolver: resolver,318		};319		let settings = Rc::new(RefCell::new(settings));320		let stdlib_obj = stdlib_uncached(settings.clone());321		#[cfg(not(feature = "legacy-this-file"))]322		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));323		Self {324			#[cfg(not(feature = "legacy-this-file"))]325			context: {326				let mut context = ContextBuilder::with_capacity(_s, 1);327				context.bind("std", stdlib_thunk.clone());328				context.build()329			},330			#[cfg(not(feature = "legacy-this-file"))]331			stdlib_thunk,332			#[cfg(feature = "legacy-this-file")]333			stdlib_obj,334			settings,335		}336	}337	pub fn settings(&self) -> Ref<Settings> {338		self.settings.borrow()339	}340	pub fn settings_mut(&self) -> RefMut<Settings> {341		self.settings.borrow_mut()342	}343	pub fn add_ext_var(&self, name: IStr, value: Val) {344		self.settings_mut()345			.ext_vars346			.insert(name, TlaArg::Val(value));347	}348	pub fn add_ext_str(&self, name: IStr, value: IStr) {349		self.settings_mut()350			.ext_vars351			.insert(name, TlaArg::String(value));352	}353	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {354		let code = code.into();355		let source = extvar_source(name, code.clone());356		let parsed = jrsonnet_parser::parse(357			&code,358			&jrsonnet_parser::ParserSettings {359				source: source.clone(),360			},361		)362		.map_err(|e| ImportSyntaxError {363			path: source,364			error: Box::new(e),365		})?;366		// self.data_mut().volatile_files.insert(source_name, code);367		self.settings_mut()368			.ext_vars369			.insert(name.into(), TlaArg::Code(parsed));370		Ok(())371	}372	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {373		self.settings_mut()374			.ext_natives375			.insert(name.into(), cb.into());376	}377}378impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {379	fn reserve_vars(&self) -> usize {380		1381	}382	#[cfg(not(feature = "legacy-this-file"))]383	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {384		self.context.clone()385	}386	#[cfg(not(feature = "legacy-this-file"))]387	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {388		builder.bind("std", self.stdlib_thunk.clone());389	}390	#[cfg(feature = "legacy-this-file")]391	fn populate(&self, source: Source, builder: &mut ContextBuilder) {392		use jrsonnet_evaluator::val::StrValue;393394		let mut std = ObjValueBuilder::new();395		std.with_super(self.stdlib_obj.clone());396		std.field("thisFile")397			.hide()398			.value(match source.source_path().path() {399				Some(p) => self.settings().path_resolver.resolve(p),400				None => source.source_path().to_string(),401			});402		let stdlib_with_this_file = std.build();403404		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));405	}406	fn as_any(&self) -> &dyn std::any::Any {407		self408	}409}410411pub trait StateExt {412	/// This method was previously implemented in jrsonnet-evaluator itself413	fn with_stdlib(&self);414}415416impl StateExt for State {417	fn with_stdlib(&self) {418		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());419		self.settings_mut().context_initializer = tb!(initializer)420	}421}
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::*;46#[cfg(feature = "exp-regex")]47mod regex;48#[cfg(feature = "exp-regex")]49pub use crate::regex::*;5051#[allow(clippy::too_many_lines)]52pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {53	let mut builder = ObjValueBuilder::new();5455	let expr = expr::stdlib_expr();56	let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)57		.expect("stdlib.jsonnet should have no errors")58		.as_obj()59		.expect("stdlib.jsonnet should evaluate to object");6061	builder.with_super(eval);6263	// FIXME: Use PHF64	for (name, builtin) in [65		// Types66		("type", builtin_type::INST),67		("isString", builtin_is_string::INST),68		("isNumber", builtin_is_number::INST),69		("isBoolean", builtin_is_boolean::INST),70		("isObject", builtin_is_object::INST),71		("isArray", builtin_is_array::INST),72		("isFunction", builtin_is_function::INST),73		// Arrays74		("makeArray", builtin_make_array::INST),75		("repeat", builtin_repeat::INST),76		("slice", builtin_slice::INST),77		("map", builtin_map::INST),78		("flatMap", builtin_flatmap::INST),79		("filter", builtin_filter::INST),80		("foldl", builtin_foldl::INST),81		("foldr", builtin_foldr::INST),82		("range", builtin_range::INST),83		("join", builtin_join::INST),84		("reverse", builtin_reverse::INST),85		("any", builtin_any::INST),86		("all", builtin_all::INST),87		("member", builtin_member::INST),88		("contains", builtin_contains::INST),89		("count", builtin_count::INST),90		("avg", builtin_avg::INST),91		("removeAt", builtin_remove_at::INST),92		("remove", builtin_remove::INST),93		("flattenArrays", builtin_flatten_arrays::INST),94		("flattenDeepArray", builtin_flatten_deep_array::INST),95		("filterMap", builtin_filter_map::INST),96		// Math97		("abs", builtin_abs::INST),98		("sign", builtin_sign::INST),99		("max", builtin_max::INST),100		("min", builtin_min::INST),101		("sum", builtin_sum::INST),102		("modulo", builtin_modulo::INST),103		("floor", builtin_floor::INST),104		("ceil", builtin_ceil::INST),105		("log", builtin_log::INST),106		("pow", builtin_pow::INST),107		("sqrt", builtin_sqrt::INST),108		("sin", builtin_sin::INST),109		("cos", builtin_cos::INST),110		("tan", builtin_tan::INST),111		("asin", builtin_asin::INST),112		("acos", builtin_acos::INST),113		("atan", builtin_atan::INST),114		("atan2", builtin_atan2::INST),115		("exp", builtin_exp::INST),116		("mantissa", builtin_mantissa::INST),117		("exponent", builtin_exponent::INST),118		("round", builtin_round::INST),119		("isEven", builtin_is_even::INST),120		("isOdd", builtin_is_odd::INST),121		("isInteger", builtin_is_integer::INST),122		("isDecimal", builtin_is_decimal::INST),123		// Operator124		("mod", builtin_mod::INST),125		("primitiveEquals", builtin_primitive_equals::INST),126		("equals", builtin_equals::INST),127		("xor", builtin_xor::INST),128		("xnor", builtin_xnor::INST),129		("format", builtin_format::INST),130		// Sort131		("sort", builtin_sort::INST),132		("uniq", builtin_uniq::INST),133		("set", builtin_set::INST),134		("minArray", builtin_min_array::INST),135		("maxArray", builtin_max_array::INST),136		// Hash137		("md5", builtin_md5::INST),138		("sha1", builtin_sha1::INST),139		("sha256", builtin_sha256::INST),140		("sha512", builtin_sha512::INST),141		("sha3", builtin_sha3::INST),142		// Encoding143		("encodeUTF8", builtin_encode_utf8::INST),144		("decodeUTF8", builtin_decode_utf8::INST),145		("base64", builtin_base64::INST),146		("base64Decode", builtin_base64_decode::INST),147		("base64DecodeBytes", builtin_base64_decode_bytes::INST),148		// Objects149		("objectFieldsEx", builtin_object_fields_ex::INST),150		("objectFields", builtin_object_fields::INST),151		("objectFieldsAll", builtin_object_fields_all::INST),152		("objectValues", builtin_object_values::INST),153		("objectValuesAll", builtin_object_values_all::INST),154		("objectKeysValues", builtin_object_keys_values::INST),155		("objectKeysValuesAll", builtin_object_keys_values_all::INST),156		("objectHasEx", builtin_object_has_ex::INST),157		("objectHas", builtin_object_has::INST),158		("objectHasAll", builtin_object_has_all::INST),159		("objectRemoveKey", builtin_object_remove_key::INST),160		// Manifest161		("escapeStringJson", builtin_escape_string_json::INST),162		("manifestJsonEx", builtin_manifest_json_ex::INST),163		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),164		("manifestTomlEx", builtin_manifest_toml_ex::INST),165		("toString", builtin_to_string::INST),166		// Parsing167		("parseJson", builtin_parse_json::INST),168		("parseYaml", builtin_parse_yaml::INST),169		// Strings170		("codepoint", builtin_codepoint::INST),171		("substr", builtin_substr::INST),172		("char", builtin_char::INST),173		("strReplace", builtin_str_replace::INST),174		("isEmpty", builtin_is_empty::INST),175		("equalsIgnoreCase", builtin_equals_ignore_case::INST),176		("splitLimit", builtin_splitlimit::INST),177		("asciiUpper", builtin_ascii_upper::INST),178		("asciiLower", builtin_ascii_lower::INST),179		("findSubstr", builtin_find_substr::INST),180		("parseInt", builtin_parse_int::INST),181		#[cfg(feature = "exp-bigint")]182		("bigint", builtin_bigint::INST),183		("parseOctal", builtin_parse_octal::INST),184		("parseHex", builtin_parse_hex::INST),185		("stringChars", builtin_string_chars::INST),186		// Misc187		("length", builtin_length::INST),188		("startsWith", builtin_starts_with::INST),189		("endsWith", builtin_ends_with::INST),190		// Sets191		("setMember", builtin_set_member::INST),192		("setInter", builtin_set_inter::INST),193		("setDiff", builtin_set_diff::INST),194		("setUnion", builtin_set_union::INST),195		// Regex196		#[cfg(feature = "exp-regex")]197		("regexQuoteMeta", builtin_regex_quote_meta::INST),198		// Compat199		("__compare", builtin___compare::INST),200	]201	.iter()202	.copied()203	{204		builder.method(name, builtin);205	}206207	builder.method(208		"extVar",209		builtin_ext_var {210			settings: settings.clone(),211		},212	);213	builder.method(214		"native",215		builtin_native {216			settings: settings.clone(),217		},218	);219	builder.method("trace", builtin_trace { settings });220	builder.method("id", FuncVal::Id);221222	#[cfg(feature = "exp-regex")]223	{224		// Regex225		let regex_cache = RegexCache::default();226		builder.method(227			"regexFullMatch",228			builtin_regex_full_match {229				cache: regex_cache.clone(),230			},231		);232		builder.method(233			"regexPartialMatch",234			builtin_regex_partial_match {235				cache: regex_cache.clone(),236			},237		);238		builder.method(239			"regexReplace",240			builtin_regex_replace {241				cache: regex_cache.clone(),242			},243		);244		builder.method(245			"regexGlobalReplace",246			builtin_regex_global_replace {247				cache: regex_cache.clone(),248			},249		);250	};251252	builder.build()253}254255pub trait TracePrinter {256	fn print_trace(&self, loc: CallLocation, value: IStr);257}258259pub struct StdTracePrinter {260	resolver: PathResolver,261}262impl StdTracePrinter {263	pub fn new(resolver: PathResolver) -> Self {264		Self { resolver }265	}266}267impl TracePrinter for StdTracePrinter {268	fn print_trace(&self, loc: CallLocation, value: IStr) {269		eprint!("TRACE:");270		if let Some(loc) = loc.0 {271			let locs = loc.0.map_source_locations(&[loc.1]);272			eprint!(273				" {}:{}",274				loc.0.source_path().path().map_or_else(275					|| loc.0.source_path().to_string(),276					|p| self.resolver.resolve(p)277				),278				locs[0].line279			);280		}281		eprintln!(" {value}");282	}283}284285pub struct Settings {286	/// Used for `std.extVar`287	pub ext_vars: HashMap<IStr, TlaArg>,288	/// Used for `std.native`289	pub ext_natives: HashMap<IStr, FuncVal>,290	/// Used for `std.trace`291	pub trace_printer: Box<dyn TracePrinter>,292	/// Used for `std.thisFile`293	pub path_resolver: PathResolver,294}295296fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {297	let source_name = format!("<extvar:{name}>");298	Source::new_virtual(source_name.into(), code.into())299}300301#[derive(Trace, Clone)]302pub struct ContextInitializer {303	/// When we don't need to support legacy-this-file, we can reuse same context for all files304	#[cfg(not(feature = "legacy-this-file"))]305	context: jrsonnet_evaluator::Context,306	/// For `populate`307	#[cfg(not(feature = "legacy-this-file"))]308	stdlib_thunk: Thunk<Val>,309	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it310	#[cfg(feature = "legacy-this-file")]311	stdlib_obj: ObjValue,312	settings: Rc<RefCell<Settings>>,313}314impl ContextInitializer {315	pub fn new(_s: State, resolver: PathResolver) -> Self {316		let settings = Settings {317			ext_vars: Default::default(),318			ext_natives: Default::default(),319			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),320			path_resolver: resolver,321		};322		let settings = Rc::new(RefCell::new(settings));323		let stdlib_obj = stdlib_uncached(settings.clone());324		#[cfg(not(feature = "legacy-this-file"))]325		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));326		Self {327			#[cfg(not(feature = "legacy-this-file"))]328			context: {329				let mut context = ContextBuilder::with_capacity(_s, 1);330				context.bind("std", stdlib_thunk.clone());331				context.build()332			},333			#[cfg(not(feature = "legacy-this-file"))]334			stdlib_thunk,335			#[cfg(feature = "legacy-this-file")]336			stdlib_obj,337			settings,338		}339	}340	pub fn settings(&self) -> Ref<Settings> {341		self.settings.borrow()342	}343	pub fn settings_mut(&self) -> RefMut<Settings> {344		self.settings.borrow_mut()345	}346	pub fn add_ext_var(&self, name: IStr, value: Val) {347		self.settings_mut()348			.ext_vars349			.insert(name, TlaArg::Val(value));350	}351	pub fn add_ext_str(&self, name: IStr, value: IStr) {352		self.settings_mut()353			.ext_vars354			.insert(name, TlaArg::String(value));355	}356	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {357		let code = code.into();358		let source = extvar_source(name, code.clone());359		let parsed = jrsonnet_parser::parse(360			&code,361			&jrsonnet_parser::ParserSettings {362				source: source.clone(),363			},364		)365		.map_err(|e| ImportSyntaxError {366			path: source,367			error: Box::new(e),368		})?;369		// self.data_mut().volatile_files.insert(source_name, code);370		self.settings_mut()371			.ext_vars372			.insert(name.into(), TlaArg::Code(parsed));373		Ok(())374	}375	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {376		self.settings_mut()377			.ext_natives378			.insert(name.into(), cb.into());379	}380}381impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {382	fn reserve_vars(&self) -> usize {383		1384	}385	#[cfg(not(feature = "legacy-this-file"))]386	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {387		self.context.clone()388	}389	#[cfg(not(feature = "legacy-this-file"))]390	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {391		builder.bind("std", self.stdlib_thunk.clone());392	}393	#[cfg(feature = "legacy-this-file")]394	fn populate(&self, source: Source, builder: &mut ContextBuilder) {395		use jrsonnet_evaluator::val::StrValue;396397		let mut std = ObjValueBuilder::new();398		std.with_super(self.stdlib_obj.clone());399		std.field("thisFile")400			.hide()401			.value(match source.source_path().path() {402				Some(p) => self.settings().path_resolver.resolve(p),403				None => source.source_path().to_string(),404			});405		let stdlib_with_this_file = std.build();406407		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));408	}409	fn as_any(&self) -> &dyn std::any::Any {410		self411	}412}413414pub trait StateExt {415	/// This method was previously implemented in jrsonnet-evaluator itself416	fn with_stdlib(&self);417}418419impl StateExt for State {420	fn with_stdlib(&self) {421		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());422		self.settings_mut().context_initializer = tb!(initializer);423	}424}