git.delta.rocks / jrsonnet / refs/commits / 2e5acc0c12c5

difftreelog

refactor(stdlib) split more builtins into own files

Yaroslav Bolyukin2022-10-17parent: #446308e.patch.diff
in: master

3 files changed

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::{Error::*, Result},9	function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},10	gc::{GcHashMap, TraceBox},11	tb, throw,12	trace::PathResolver,13	typed::{Any, Either, Either2, Either4, VecVal, M1},14	val::{equals, ArrValue},15	Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,16};17use jrsonnet_gcmodule::Cc;18use jrsonnet_macros::builtin;19use jrsonnet_parser::Source;2021mod expr;22mod types;23pub use types::*;24mod arrays;25pub use arrays::*;26mod math;27pub use math::*;28mod operator;29pub use operator::*;30mod sort;31pub use sort::*;32mod hash;33pub use hash::*;34mod encoding;35pub use encoding::*;36mod objects;37pub use objects::*;38mod manifest;39pub use manifest::*;40mod parse;41pub use parse::*;4243pub fn stdlib_uncached(s: State, settings: Rc<RefCell<Settings>>) -> ObjValue {44	let mut builder = ObjValueBuilder::new();4546	let expr = expr::stdlib_expr();47	let eval = jrsonnet_evaluator::evaluate(s.clone(), Context::default(), &expr)48		.expect("stdlib.jsonnet should have no errors")49		.as_obj()50		.expect("stdlib.jsonnet should evaluate to object");5152	builder.with_super(eval);5354	for (name, builtin) in [55		("length", builtin_length::INST),56		// Types57		("type", builtin_type::INST),58		("isString", builtin_is_string::INST),59		("isNumber", builtin_is_number::INST),60		("isBoolean", builtin_is_boolean::INST),61		("isObject", builtin_is_object::INST),62		("isArray", builtin_is_array::INST),63		("isFunction", builtin_is_function::INST),64		// Arrays65		("makeArray", builtin_make_array::INST),66		("slice", builtin_slice::INST),67		("map", builtin_map::INST),68		("flatMap", builtin_flatmap::INST),69		("filter", builtin_filter::INST),70		("foldl", builtin_foldl::INST),71		("foldr", builtin_foldr::INST),72		("range", builtin_range::INST),73		("join", builtin_join::INST),74		("reverse", builtin_reverse::INST),75		("any", builtin_any::INST),76		("all", builtin_all::INST),77		("member", builtin_member::INST),78		("count", builtin_count::INST),79		// Math80		("modulo", builtin_modulo::INST),81		("floor", builtin_floor::INST),82		("ceil", builtin_ceil::INST),83		("log", builtin_log::INST),84		("pow", builtin_pow::INST),85		("sqrt", builtin_sqrt::INST),86		("sin", builtin_sin::INST),87		("cos", builtin_cos::INST),88		("tan", builtin_tan::INST),89		("asin", builtin_asin::INST),90		("acos", builtin_acos::INST),91		("atan", builtin_atan::INST),92		("exp", builtin_exp::INST),93		("mantissa", builtin_mantissa::INST),94		("exponent", builtin_exponent::INST),95		// Operator96		("mod", builtin_mod::INST),97		("primitiveEquals", builtin_primitive_equals::INST),98		("equals", builtin_equals::INST),99		("format", builtin_format::INST),100		// Sort101		("sort", builtin_sort::INST),102		// Hash103		("md5", builtin_md5::INST),104		// Encoding105		("encodeUTF8", builtin_encode_utf8::INST),106		("decodeUTF8", builtin_decode_utf8::INST),107		("base64", builtin_base64::INST),108		("base64Decode", builtin_base64_decode::INST),109		("base64DecodeBytes", builtin_base64_decode_bytes::INST),110		// Objects111		("objectFieldsEx", builtin_object_fields_ex::INST),112		("objectHasEx", builtin_object_has_ex::INST),113		// Manifest114		("escapeStringJson", builtin_escape_string_json::INST),115		("manifestJsonEx", builtin_manifest_json_ex::INST),116		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),117		// Parsing118		("parseJson", builtin_parse_json::INST),119		("parseYaml", builtin_parse_yaml::INST),120		// Misc121		("codepoint", builtin_codepoint::INST),122		("substr", builtin_substr::INST),123		("char", builtin_char::INST),124		("strReplace", builtin_str_replace::INST),125		("splitLimit", builtin_splitlimit::INST),126		("asciiUpper", builtin_ascii_upper::INST),127		("asciiLower", builtin_ascii_lower::INST),128		("findSubstr", builtin_find_substr::INST),129		("startsWith", builtin_starts_with::INST),130		("endsWith", builtin_ends_with::INST),131	]132	.iter()133	.cloned()134	{135		builder136			.member(name.into())137			.hide()138			.value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))139			.expect("no conflict");140	}141142	builder143		.member("extVar".into())144		.hide()145		.value(146			s.clone(),147			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {148				settings: settings.clone()149			})))),150		)151		.expect("no conflict");152	builder153		.member("native".into())154		.hide()155		.value(156			s.clone(),157			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {158				settings: settings.clone()159			})))),160		)161		.expect("no conflict");162	builder163		.member("trace".into())164		.hide()165		.value(166			s.clone(),167			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace { settings })))),168		)169		.expect("no conflict");170171	builder172		.member("id".into())173		.hide()174		.value(s, Val::Func(FuncVal::Id))175		.expect("no conflict");176177	builder.build()178}179180pub trait TracePrinter {181	fn print_trace(&self, s: State, loc: CallLocation, value: IStr);182}183184pub struct StdTracePrinter {185	resolver: PathResolver,186}187impl StdTracePrinter {188	pub fn new(resolver: PathResolver) -> Self {189		Self { resolver }190	}191}192impl TracePrinter for StdTracePrinter {193	fn print_trace(&self, _s: State, loc: CallLocation, value: IStr) {194		eprint!("TRACE:");195		if let Some(loc) = loc.0 {196			let locs = loc.0.map_source_locations(&[loc.1]);197			eprint!(198				" {}:{}",199				match loc.0.source_path().path() {200					Some(p) => self.resolver.resolve(p),201					None => loc.0.source_path().to_string(),202				},203				locs[0].line204			);205		}206		eprintln!(" {}", value);207	}208}209210pub struct Settings {211	/// Used for `std.extVar`212	pub ext_vars: HashMap<IStr, TlaArg>,213	/// Used for `std.native`214	pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,215	/// Helper to add globals without implementing custom ContextInitializer216	pub globals: GcHashMap<IStr, Thunk<Val>>,217	/// Used for `std.trace`218	pub trace_printer: Box<dyn TracePrinter>,219	/// Used for `std.thisFile`220	pub path_resolver: PathResolver,221}222223pub fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {224	let source_name = format!("<extvar:{}>", name);225	Source::new_virtual(source_name.into(), code.into())226}227228pub struct ContextInitializer {229	// When we don't need to support legacy-this-file, we can reuse same context for all files230	#[cfg(not(feature = "legacy-this-file"))]231	context: Context,232	// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it233	#[cfg(feature = "legacy-this-file")]234	stdlib_obj: ObjValue,235	settings: Rc<RefCell<Settings>>,236}237impl ContextInitializer {238	pub fn new(s: State, resolver: PathResolver) -> Self {239		let settings = Settings {240			ext_vars: Default::default(),241			ext_natives: Default::default(),242			globals: Default::default(),243			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),244			path_resolver: resolver,245		};246		let settings = Rc::new(RefCell::new(settings));247		Self {248			#[cfg(not(feature = "legacy-this-file"))]249			context: {250				let mut context = ContextBuilder::with_capacity(1);251				context.bind(252					"std".into(),253					Thunk::evaluated(Val::Obj(stdlib_uncached(s, settings.clone()))),254				);255				context.build()256			},257			#[cfg(feature = "legacy-this-file")]258			stdlib_obj: stdlib_uncached(s, settings.clone()),259			settings,260		}261	}262	pub fn settings(&self) -> Ref<Settings> {263		self.settings.borrow()264	}265	pub fn settings_mut(&self) -> RefMut<Settings> {266		self.settings.borrow_mut()267	}268	pub fn add_ext_var(&self, name: IStr, value: Val) {269		self.settings_mut()270			.ext_vars271			.insert(name, TlaArg::Val(value));272	}273	pub fn add_ext_str(&self, name: IStr, value: IStr) {274		self.settings_mut()275			.ext_vars276			.insert(name, TlaArg::String(value));277	}278	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {279		let code = code.into();280		let source = extvar_source(name, code.clone());281		let parsed = jrsonnet_parser::parse(282			&code,283			&jrsonnet_parser::ParserSettings {284				file_name: source.clone(),285			},286		)287		.map_err(|e| ImportSyntaxError {288			path: source,289			error: Box::new(e),290		})?;291		// self.data_mut().volatile_files.insert(source_name, code);292		self.settings_mut()293			.ext_vars294			.insert(name.into(), TlaArg::Code(parsed));295		Ok(())296	}297	pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {298		self.settings_mut().ext_natives.insert(name, cb);299	}300}301impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {302	#[cfg(not(feature = "legacy-this-file"))]303	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {304		let out = self.context.clone();305		let globals = &self.settings().globals;306		if globals.is_empty() {307			return out;308		}309310		let mut out = ContextBuilder::extend(out);311		for (k, v) in globals.iter() {312			out.bind(k.clone(), v.clone());313		}314		out.build()315	}316	#[cfg(feature = "legacy-this-file")]317	fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {318		let mut builder = ObjValueBuilder::new();319		builder.with_super(self.stdlib_obj.clone());320		builder321			.member("thisFile".into())322			.hide()323			.value(324				s,325				Val::Str(match source.source_path().path() {326					Some(p) => self.settings().path_resolver.resolve(p).into(),327					None => source.source_path().to_string().into(),328				}),329			)330			.expect("this object builder is empty");331		let stdlib_with_this_file = builder.build();332333		let mut context = ContextBuilder::with_capacity(1);334		context.bind(335			"std".into(),336			Thunk::evaluated(Val::Obj(stdlib_with_this_file)),337		);338		for (k, v) in self.settings().globals.iter() {339			context.bind(k.clone(), v.clone());340		}341		context.build()342	}343	fn as_any(&self) -> &dyn std::any::Any {344		self345	}346}347348#[builtin]349fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {350	use Either4::*;351	Ok(match x {352		A(x) => x.chars().count(),353		B(x) => x.len(),354		C(x) => x.len(),355		D(f) => f.params_len(),356	})357}358359#[builtin]360const fn builtin_codepoint(str: char) -> Result<u32> {361	Ok(str as u32)362}363364#[builtin]365fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {366	Ok(str.chars().skip(from).take(len).collect())367}368369#[builtin(fields(370	settings: Rc<RefCell<Settings>>,371))]372fn builtin_ext_var(this: &builtin_ext_var, s: State, x: IStr) -> Result<Any> {373	let ctx = s.create_default_context(extvar_source(&x, ""));374	Ok(Any(this375		.settings376		.borrow()377		.ext_vars378		.get(&x)379		.cloned()380		.ok_or_else(|| UndefinedExternalVariable(x))?381		.evaluate_arg(s.clone(), ctx, true)?382		.evaluate(s)?))383}384385#[builtin(fields(386	settings: Rc<RefCell<Settings>>,387))]388fn builtin_native(this: &builtin_native, name: IStr) -> Result<Any> {389	Ok(Any(this390		.settings391		.borrow()392		.ext_natives393		.get(&name)394		.cloned()395		.map_or(Val::Null, |v| {396			Val::Func(FuncVal::Builtin(v.clone()))397		})))398}399400#[builtin]401fn builtin_char(n: u32) -> Result<char> {402	Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)403}404405#[builtin(fields(406	settings: Rc<RefCell<Settings>>,407))]408fn builtin_trace(409	this: &builtin_trace,410	s: State,411	loc: CallLocation,412	str: IStr,413	rest: Thunk<Val>,414) -> Result<Any> {415	this.settings416		.borrow()417		.trace_printer418		.print_trace(s.clone(), loc, str);419	Ok(Any(rest.evaluate(s)?))420}421422#[builtin]423fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {424	Ok(str.replace(&from as &str, &to as &str))425}426427#[builtin]428fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {429	use Either2::*;430	Ok(VecVal(Cc::new(match maxsplits {431		A(n) => str432			.splitn(n + 1, &c as &str)433			.map(|s| Val::Str(s.into()))434			.collect(),435		B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),436	})))437}438439#[builtin]440fn builtin_ascii_upper(str: IStr) -> Result<String> {441	Ok(str.to_ascii_uppercase())442}443444#[builtin]445fn builtin_ascii_lower(str: IStr) -> Result<String> {446	Ok(str.to_ascii_lowercase())447}448449#[builtin]450fn builtin_find_substr(pat: IStr, str: IStr) -> Result<ArrValue> {451	if pat.is_empty() || str.is_empty() || pat.len() > str.len() {452		return Ok(ArrValue::empty());453	}454455	let str = str.as_str();456	let pat = pat.as_bytes();457	let strb = str.as_bytes();458459	let max_pos = str.len() - pat.len();460461	let mut out: Vec<Val> = Vec::new();462	for (ch_idx, (i, _)) in str463		.char_indices()464		.take_while(|(i, _)| i <= &max_pos)465		.enumerate()466	{467		if &strb[i..i + pat.len()] == pat {468			out.push(Val::Num(ch_idx as f64))469		}470	}471	Ok(out.into())472}473474#[allow(clippy::comparison_chain)]475#[builtin]476fn builtin_starts_with(477	s: State,478	a: Either![IStr, ArrValue],479	b: Either![IStr, ArrValue],480) -> Result<bool> {481	Ok(match (a, b) {482		(Either2::A(a), Either2::A(b)) => a.starts_with(b.as_str()),483		(Either2::B(a), Either2::B(b)) => {484			if b.len() > a.len() {485				return Ok(false);486			} else if b.len() == a.len() {487				return equals(s, &Val::Arr(a), &Val::Arr(b));488			} else {489				for (a, b) in a490					.slice(None, Some(b.len()), None)491					.iter(s.clone())492					.zip(b.iter(s.clone()))493				{494					let a = a?;495					let b = b?;496					if !equals(s.clone(), &a, &b)? {497						return Ok(false);498					}499				}500				true501			}502		}503		_ => throw!("both arguments should be of the same type"),504	})505}506507#[allow(clippy::comparison_chain)]508#[builtin]509fn builtin_ends_with(510	s: State,511	a: Either![IStr, ArrValue],512	b: Either![IStr, ArrValue],513) -> Result<bool> {514	Ok(match (a, b) {515		(Either2::A(a), Either2::A(b)) => a.ends_with(b.as_str()),516		(Either2::B(a), Either2::B(b)) => {517			if b.len() > a.len() {518				return Ok(false);519			} else if b.len() == a.len() {520				return equals(s, &Val::Arr(a), &Val::Arr(b));521			} else {522				let a_len = a.len();523				for (a, b) in a524					.slice(Some(a_len - b.len()), None, None)525					.iter(s.clone())526					.zip(b.iter(s.clone()))527				{528					let a = a?;529					let b = b?;530					if !equals(s.clone(), &a, &b)? {531						return Ok(false);532					}533				}534				true535			}536		}537		_ => throw!("both arguments should be of the same type"),538	})539}540541pub trait StateExt {542	/// This method was previously implemented in jrsonnet-evaluator itself543	fn with_stdlib(&self);544	fn add_global(&self, name: IStr, value: Thunk<Val>);545}546547impl StateExt for State {548	fn with_stdlib(&self) {549		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());550		self.settings_mut().context_initializer = Box::new(initializer)551	}552	fn add_global(&self, name: IStr, value: Thunk<Val>) {553		self.settings()554			.context_initializer555			.as_any()556			.downcast_ref::<ContextInitializer>()557			.expect("not standard context initializer")558			.settings_mut()559			.globals560			.insert(name, value);561	}562}
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::{Error::*, Result},9	function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},10	gc::{GcHashMap, TraceBox},11	tb, throw,12	trace::PathResolver,13	typed::{Any, Either, Either2, Either4, VecVal, M1},14	val::{equals, ArrValue},15	Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,16};17use jrsonnet_gcmodule::Cc;18use jrsonnet_macros::builtin;19use jrsonnet_parser::Source;2021mod expr;22mod types;23pub use types::*;24mod arrays;25pub use arrays::*;26mod math;27pub use math::*;28mod operator;29pub use operator::*;30mod sort;31pub use sort::*;32mod hash;33pub use hash::*;34mod encoding;35pub use encoding::*;36mod objects;37pub use objects::*;38mod manifest;39pub use manifest::*;40mod parse;41pub use parse::*;42mod strings;43pub use strings::*;44mod misc;45pub use misc::*;4647pub fn stdlib_uncached(s: State, settings: Rc<RefCell<Settings>>) -> ObjValue {48	let mut builder = ObjValueBuilder::new();4950	let expr = expr::stdlib_expr();51	let eval = jrsonnet_evaluator::evaluate(s.clone(), Context::default(), &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		("slice", builtin_slice::INST),70		("map", builtin_map::INST),71		("flatMap", builtin_flatmap::INST),72		("filter", builtin_filter::INST),73		("foldl", builtin_foldl::INST),74		("foldr", builtin_foldr::INST),75		("range", builtin_range::INST),76		("join", builtin_join::INST),77		("reverse", builtin_reverse::INST),78		("any", builtin_any::INST),79		("all", builtin_all::INST),80		("member", builtin_member::INST),81		("count", builtin_count::INST),82		// Math83		("modulo", builtin_modulo::INST),84		("floor", builtin_floor::INST),85		("ceil", builtin_ceil::INST),86		("log", builtin_log::INST),87		("pow", builtin_pow::INST),88		("sqrt", builtin_sqrt::INST),89		("sin", builtin_sin::INST),90		("cos", builtin_cos::INST),91		("tan", builtin_tan::INST),92		("asin", builtin_asin::INST),93		("acos", builtin_acos::INST),94		("atan", builtin_atan::INST),95		("exp", builtin_exp::INST),96		("mantissa", builtin_mantissa::INST),97		("exponent", builtin_exponent::INST),98		// Operator99		("mod", builtin_mod::INST),100		("primitiveEquals", builtin_primitive_equals::INST),101		("equals", builtin_equals::INST),102		("format", builtin_format::INST),103		// Sort104		("sort", builtin_sort::INST),105		// Hash106		("md5", builtin_md5::INST),107		// Encoding108		("encodeUTF8", builtin_encode_utf8::INST),109		("decodeUTF8", builtin_decode_utf8::INST),110		("base64", builtin_base64::INST),111		("base64Decode", builtin_base64_decode::INST),112		("base64DecodeBytes", builtin_base64_decode_bytes::INST),113		// Objects114		("objectFieldsEx", builtin_object_fields_ex::INST),115		("objectHasEx", builtin_object_has_ex::INST),116		// Manifest117		("escapeStringJson", builtin_escape_string_json::INST),118		("manifestJsonEx", builtin_manifest_json_ex::INST),119		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),120		// Parsing121		("parseJson", builtin_parse_json::INST),122		("parseYaml", builtin_parse_yaml::INST),123		// Strings124		("codepoint", builtin_codepoint::INST),125		("substr", builtin_substr::INST),126		("char", builtin_char::INST),127		("strReplace", builtin_str_replace::INST),128		("splitLimit", builtin_splitlimit::INST),129		("asciiUpper", builtin_ascii_upper::INST),130		("asciiLower", builtin_ascii_lower::INST),131		("findSubstr", builtin_find_substr::INST),132		// Misc133		("length", builtin_length::INST),134		("startsWith", builtin_starts_with::INST),135		("endsWith", builtin_ends_with::INST),136	]137	.iter()138	.cloned()139	{140		builder141			.member(name.into())142			.hide()143			.value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))144			.expect("no conflict");145	}146147	builder148		.member("extVar".into())149		.hide()150		.value(151			s.clone(),152			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {153				settings: settings.clone()154			})))),155		)156		.expect("no conflict");157	builder158		.member("native".into())159		.hide()160		.value(161			s.clone(),162			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {163				settings: settings.clone()164			})))),165		)166		.expect("no conflict");167	builder168		.member("trace".into())169		.hide()170		.value(171			s.clone(),172			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace { settings })))),173		)174		.expect("no conflict");175176	builder177		.member("id".into())178		.hide()179		.value(s, Val::Func(FuncVal::Id))180		.expect("no conflict");181182	builder.build()183}184185pub trait TracePrinter {186	fn print_trace(&self, s: State, loc: CallLocation, value: IStr);187}188189pub struct StdTracePrinter {190	resolver: PathResolver,191}192impl StdTracePrinter {193	pub fn new(resolver: PathResolver) -> Self {194		Self { resolver }195	}196}197impl TracePrinter for StdTracePrinter {198	fn print_trace(&self, _s: State, loc: CallLocation, value: IStr) {199		eprint!("TRACE:");200		if let Some(loc) = loc.0 {201			let locs = loc.0.map_source_locations(&[loc.1]);202			eprint!(203				" {}:{}",204				match loc.0.source_path().path() {205					Some(p) => self.resolver.resolve(p),206					None => loc.0.source_path().to_string(),207				},208				locs[0].line209			);210		}211		eprintln!(" {}", value);212	}213}214215pub struct Settings {216	/// Used for `std.extVar`217	pub ext_vars: HashMap<IStr, TlaArg>,218	/// Used for `std.native`219	pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,220	/// Helper to add globals without implementing custom ContextInitializer221	pub globals: GcHashMap<IStr, Thunk<Val>>,222	/// Used for `std.trace`223	pub trace_printer: Box<dyn TracePrinter>,224	/// Used for `std.thisFile`225	pub path_resolver: PathResolver,226}227228pub fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {229	let source_name = format!("<extvar:{}>", name);230	Source::new_virtual(source_name.into(), code.into())231}232233pub struct ContextInitializer {234	// When we don't need to support legacy-this-file, we can reuse same context for all files235	#[cfg(not(feature = "legacy-this-file"))]236	context: Context,237	// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it238	#[cfg(feature = "legacy-this-file")]239	stdlib_obj: ObjValue,240	settings: Rc<RefCell<Settings>>,241}242impl ContextInitializer {243	pub fn new(s: State, resolver: PathResolver) -> Self {244		let settings = Settings {245			ext_vars: Default::default(),246			ext_natives: Default::default(),247			globals: Default::default(),248			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),249			path_resolver: resolver,250		};251		let settings = Rc::new(RefCell::new(settings));252		Self {253			#[cfg(not(feature = "legacy-this-file"))]254			context: {255				let mut context = ContextBuilder::with_capacity(1);256				context.bind(257					"std".into(),258					Thunk::evaluated(Val::Obj(stdlib_uncached(s, settings.clone()))),259				);260				context.build()261			},262			#[cfg(feature = "legacy-this-file")]263			stdlib_obj: stdlib_uncached(s, settings.clone()),264			settings,265		}266	}267	pub fn settings(&self) -> Ref<Settings> {268		self.settings.borrow()269	}270	pub fn settings_mut(&self) -> RefMut<Settings> {271		self.settings.borrow_mut()272	}273	pub fn add_ext_var(&self, name: IStr, value: Val) {274		self.settings_mut()275			.ext_vars276			.insert(name, TlaArg::Val(value));277	}278	pub fn add_ext_str(&self, name: IStr, value: IStr) {279		self.settings_mut()280			.ext_vars281			.insert(name, TlaArg::String(value));282	}283	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {284		let code = code.into();285		let source = extvar_source(name, code.clone());286		let parsed = jrsonnet_parser::parse(287			&code,288			&jrsonnet_parser::ParserSettings {289				file_name: source.clone(),290			},291		)292		.map_err(|e| ImportSyntaxError {293			path: source,294			error: Box::new(e),295		})?;296		// self.data_mut().volatile_files.insert(source_name, code);297		self.settings_mut()298			.ext_vars299			.insert(name.into(), TlaArg::Code(parsed));300		Ok(())301	}302	pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {303		self.settings_mut().ext_natives.insert(name, cb);304	}305}306impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {307	#[cfg(not(feature = "legacy-this-file"))]308	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {309		let out = self.context.clone();310		let globals = &self.settings().globals;311		if globals.is_empty() {312			return out;313		}314315		let mut out = ContextBuilder::extend(out);316		for (k, v) in globals.iter() {317			out.bind(k.clone(), v.clone());318		}319		out.build()320	}321	#[cfg(feature = "legacy-this-file")]322	fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {323		let mut builder = ObjValueBuilder::new();324		builder.with_super(self.stdlib_obj.clone());325		builder326			.member("thisFile".into())327			.hide()328			.value(329				s,330				Val::Str(match source.source_path().path() {331					Some(p) => self.settings().path_resolver.resolve(p).into(),332					None => source.source_path().to_string().into(),333				}),334			)335			.expect("this object builder is empty");336		let stdlib_with_this_file = builder.build();337338		let mut context = ContextBuilder::with_capacity(1);339		context.bind(340			"std".into(),341			Thunk::evaluated(Val::Obj(stdlib_with_this_file)),342		);343		for (k, v) in self.settings().globals.iter() {344			context.bind(k.clone(), v.clone());345		}346		context.build()347	}348	fn as_any(&self) -> &dyn std::any::Any {349		self350	}351}352353pub trait StateExt {354	/// This method was previously implemented in jrsonnet-evaluator itself355	fn with_stdlib(&self);356	fn add_global(&self, name: IStr, value: Thunk<Val>);357}358359impl StateExt for State {360	fn with_stdlib(&self) {361		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());362		self.settings_mut().context_initializer = Box::new(initializer)363	}364	fn add_global(&self, name: IStr, value: Thunk<Val>) {365		self.settings()366			.context_initializer367			.as_any()368			.downcast_ref::<ContextInitializer>()369			.expect("not standard context initializer")370			.settings_mut()371			.globals372			.insert(name, value);373	}374}
addedcrates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -0,0 +1,138 @@
+use std::{cell::RefCell, rc::Rc};
+
+use jrsonnet_evaluator::{
+	error::{Error::*, Result},
+	function::{builtin, ArgLike, CallLocation, FuncVal},
+	throw,
+	typed::{Any, Either2, Either4},
+	val::{equals, ArrValue},
+	Either, IStr, ObjValue, State, Thunk, Val,
+};
+
+use crate::{extvar_source, Settings};
+
+#[builtin]
+pub fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {
+	use Either4::*;
+	Ok(match x {
+		A(x) => x.chars().count(),
+		B(x) => x.len(),
+		C(x) => x.len(),
+		D(f) => f.params_len(),
+	})
+}
+
+#[builtin(fields(
+	settings: Rc<RefCell<Settings>>,
+))]
+pub fn builtin_ext_var(this: &builtin_ext_var, s: State, x: IStr) -> Result<Any> {
+	let ctx = s.create_default_context(extvar_source(&x, ""));
+	Ok(Any(this
+		.settings
+		.borrow()
+		.ext_vars
+		.get(&x)
+		.cloned()
+		.ok_or_else(|| UndefinedExternalVariable(x))?
+		.evaluate_arg(s.clone(), ctx, true)?
+		.evaluate(s)?))
+}
+
+#[builtin(fields(
+	settings: Rc<RefCell<Settings>>,
+))]
+pub fn builtin_native(this: &builtin_native, name: IStr) -> Result<Any> {
+	Ok(Any(this
+		.settings
+		.borrow()
+		.ext_natives
+		.get(&name)
+		.cloned()
+		.map_or(Val::Null, |v| {
+			Val::Func(FuncVal::Builtin(v.clone()))
+		})))
+}
+
+#[builtin(fields(
+	settings: Rc<RefCell<Settings>>,
+))]
+pub fn builtin_trace(
+	this: &builtin_trace,
+	s: State,
+	loc: CallLocation,
+	str: IStr,
+	rest: Thunk<Val>,
+) -> Result<Any> {
+	this.settings
+		.borrow()
+		.trace_printer
+		.print_trace(s.clone(), loc, str);
+	Ok(Any(rest.evaluate(s)?))
+}
+
+#[allow(clippy::comparison_chain)]
+#[builtin]
+pub fn builtin_starts_with(
+	s: State,
+	a: Either![IStr, ArrValue],
+	b: Either![IStr, ArrValue],
+) -> Result<bool> {
+	Ok(match (a, b) {
+		(Either2::A(a), Either2::A(b)) => a.starts_with(b.as_str()),
+		(Either2::B(a), Either2::B(b)) => {
+			if b.len() > a.len() {
+				return Ok(false);
+			} else if b.len() == a.len() {
+				return equals(s, &Val::Arr(a), &Val::Arr(b));
+			} else {
+				for (a, b) in a
+					.slice(None, Some(b.len()), None)
+					.iter(s.clone())
+					.zip(b.iter(s.clone()))
+				{
+					let a = a?;
+					let b = b?;
+					if !equals(s.clone(), &a, &b)? {
+						return Ok(false);
+					}
+				}
+				true
+			}
+		}
+		_ => throw!("both arguments should be of the same type"),
+	})
+}
+
+#[allow(clippy::comparison_chain)]
+#[builtin]
+pub fn builtin_ends_with(
+	s: State,
+	a: Either![IStr, ArrValue],
+	b: Either![IStr, ArrValue],
+) -> Result<bool> {
+	Ok(match (a, b) {
+		(Either2::A(a), Either2::A(b)) => a.ends_with(b.as_str()),
+		(Either2::B(a), Either2::B(b)) => {
+			if b.len() > a.len() {
+				return Ok(false);
+			} else if b.len() == a.len() {
+				return equals(s, &Val::Arr(a), &Val::Arr(b));
+			} else {
+				let a_len = a.len();
+				for (a, b) in a
+					.slice(Some(a_len - b.len()), None, None)
+					.iter(s.clone())
+					.zip(b.iter(s.clone()))
+				{
+					let a = a?;
+					let b = b?;
+					if !equals(s.clone(), &a, &b)? {
+						return Ok(false);
+					}
+				}
+				true
+			}
+		}
+		_ => throw!("both arguments should be of the same type"),
+	})
+}
addedcrates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -0,0 +1,75 @@
+use jrsonnet_evaluator::{
+	error::{Error::*, Result},
+	function::builtin,
+	typed::{Either2, VecVal, M1},
+	val::ArrValue,
+	Either, IStr, Val,
+};
+use jrsonnet_gcmodule::Cc;
+
+#[builtin]
+pub const fn builtin_codepoint(str: char) -> Result<u32> {
+	Ok(str as u32)
+}
+
+#[builtin]
+pub fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {
+	Ok(str.chars().skip(from).take(len).collect())
+}
+
+#[builtin]
+pub fn builtin_char(n: u32) -> Result<char> {
+	Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)
+}
+
+#[builtin]
+pub fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {
+	Ok(str.replace(&from as &str, &to as &str))
+}
+
+#[builtin]
+pub fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {
+	use Either2::*;
+	Ok(VecVal(Cc::new(match maxsplits {
+		A(n) => str
+			.splitn(n + 1, &c as &str)
+			.map(|s| Val::Str(s.into()))
+			.collect(),
+		B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),
+	})))
+}
+
+#[builtin]
+pub fn builtin_ascii_upper(str: IStr) -> Result<String> {
+	Ok(str.to_ascii_uppercase())
+}
+
+#[builtin]
+pub fn builtin_ascii_lower(str: IStr) -> Result<String> {
+	Ok(str.to_ascii_lowercase())
+}
+
+#[builtin]
+pub fn builtin_find_substr(pat: IStr, str: IStr) -> Result<ArrValue> {
+	if pat.is_empty() || str.is_empty() || pat.len() > str.len() {
+		return Ok(ArrValue::empty());
+	}
+
+	let str = str.as_str();
+	let pat = pat.as_bytes();
+	let strb = str.as_bytes();
+
+	let max_pos = str.len() - pat.len();
+
+	let mut out: Vec<Val> = Vec::new();
+	for (ch_idx, (i, _)) in str
+		.char_indices()
+		.take_while(|(i, _)| i <= &max_pos)
+		.enumerate()
+	{
+		if &strb[i..i + pat.len()] == pat {
+			out.push(Val::Num(ch_idx as f64))
+		}
+	}
+	Ok(out.into())
+}