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

difftreelog

source

crates/jrsonnet-stdlib/src/lib.rs13.2 KiBsourcehistory
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		("reverse", builtin_reverse::INST),90		("any", builtin_any::INST),91		("all", builtin_all::INST),92		("member", builtin_member::INST),93		("contains", builtin_contains::INST),94		("count", builtin_count::INST),95		("avg", builtin_avg::INST),96		("removeAt", builtin_remove_at::INST),97		("remove", builtin_remove::INST),98		("flattenArrays", builtin_flatten_arrays::INST),99		("flattenDeepArray", builtin_flatten_deep_array::INST),100		("prune", builtin_prune::INST),101		("filterMap", builtin_filter_map::INST),102		// Math103		("abs", builtin_abs::INST),104		("sign", builtin_sign::INST),105		("max", builtin_max::INST),106		("min", builtin_min::INST),107		("clamp", builtin_clamp::INST),108		("sum", builtin_sum::INST),109		("modulo", builtin_modulo::INST),110		("floor", builtin_floor::INST),111		("ceil", builtin_ceil::INST),112		("log", builtin_log::INST),113		("pow", builtin_pow::INST),114		("sqrt", builtin_sqrt::INST),115		("sin", builtin_sin::INST),116		("cos", builtin_cos::INST),117		("tan", builtin_tan::INST),118		("asin", builtin_asin::INST),119		("acos", builtin_acos::INST),120		("atan", builtin_atan::INST),121		("atan2", builtin_atan2::INST),122		("exp", builtin_exp::INST),123		("mantissa", builtin_mantissa::INST),124		("exponent", builtin_exponent::INST),125		("round", builtin_round::INST),126		("isEven", builtin_is_even::INST),127		("isOdd", builtin_is_odd::INST),128		("isInteger", builtin_is_integer::INST),129		("isDecimal", builtin_is_decimal::INST),130		// Operator131		("mod", builtin_mod::INST),132		("primitiveEquals", builtin_primitive_equals::INST),133		("equals", builtin_equals::INST),134		("xor", builtin_xor::INST),135		("xnor", builtin_xnor::INST),136		("format", builtin_format::INST),137		// Sort138		("sort", builtin_sort::INST),139		("uniq", builtin_uniq::INST),140		("set", builtin_set::INST),141		("minArray", builtin_min_array::INST),142		("maxArray", builtin_max_array::INST),143		// Hash144		("md5", builtin_md5::INST),145		("sha1", builtin_sha1::INST),146		("sha256", builtin_sha256::INST),147		("sha512", builtin_sha512::INST),148		("sha3", builtin_sha3::INST),149		// Encoding150		("encodeUTF8", builtin_encode_utf8::INST),151		("decodeUTF8", builtin_decode_utf8::INST),152		("base64", builtin_base64::INST),153		("base64Decode", builtin_base64_decode::INST),154		("base64DecodeBytes", builtin_base64_decode_bytes::INST),155		// Objects156		("objectFieldsEx", builtin_object_fields_ex::INST),157		("objectFields", builtin_object_fields::INST),158		("objectFieldsAll", builtin_object_fields_all::INST),159		("objectValues", builtin_object_values::INST),160		("objectValuesAll", builtin_object_values_all::INST),161		("objectKeysValues", builtin_object_keys_values::INST),162		("objectKeysValuesAll", builtin_object_keys_values_all::INST),163		("objectHasEx", builtin_object_has_ex::INST),164		("objectHas", builtin_object_has::INST),165		("objectHasAll", builtin_object_has_all::INST),166		("objectRemoveKey", builtin_object_remove_key::INST),167		// Manifest168		("escapeStringJson", builtin_escape_string_json::INST),169		("escapeStringPython", builtin_escape_string_python::INST),170		("escapeStringXML", builtin_escape_string_xml::INST),171		("manifestJsonEx", builtin_manifest_json_ex::INST),172		("manifestJson", builtin_manifest_json::INST),173		("manifestJsonMinified", builtin_manifest_json_minified::INST),174		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),175		("manifestYamlStream", builtin_manifest_yaml_stream::INST),176		("manifestTomlEx", builtin_manifest_toml_ex::INST),177		("manifestToml", builtin_manifest_toml::INST),178		("toString", builtin_to_string::INST),179		("manifestPython", builtin_manifest_python::INST),180		("manifestPythonVars", builtin_manifest_python_vars::INST),181		("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),182		// Parse183		("parseJson", builtin_parse_json::INST),184		("parseYaml", builtin_parse_yaml::INST),185		// Strings186		("codepoint", builtin_codepoint::INST),187		("substr", builtin_substr::INST),188		("char", builtin_char::INST),189		("strReplace", builtin_str_replace::INST),190		("escapeStringBash", builtin_escape_string_bash::INST),191		("escapeStringDollars", builtin_escape_string_dollars::INST),192		("isEmpty", builtin_is_empty::INST),193		("equalsIgnoreCase", builtin_equals_ignore_case::INST),194		("splitLimit", builtin_splitlimit::INST),195		("splitLimitR", builtin_splitlimitr::INST),196		("split", builtin_split::INST),197		("asciiUpper", builtin_ascii_upper::INST),198		("asciiLower", builtin_ascii_lower::INST),199		("findSubstr", builtin_find_substr::INST),200		("parseInt", builtin_parse_int::INST),201		#[cfg(feature = "exp-bigint")]202		("bigint", builtin_bigint::INST),203		("parseOctal", builtin_parse_octal::INST),204		("parseHex", builtin_parse_hex::INST),205		("stringChars", builtin_string_chars::INST),206		("lstripChars", builtin_lstrip_chars::INST),207		("rstripChars", builtin_rstrip_chars::INST),208		("stripChars", builtin_strip_chars::INST),209		// Misc210		("length", builtin_length::INST),211		("get", builtin_get::INST),212		("startsWith", builtin_starts_with::INST),213		("endsWith", builtin_ends_with::INST),214		// Sets215		("setMember", builtin_set_member::INST),216		("setInter", builtin_set_inter::INST),217		("setDiff", builtin_set_diff::INST),218		("setUnion", builtin_set_union::INST),219		// Regex220		#[cfg(feature = "exp-regex")]221		("regexQuoteMeta", builtin_regex_quote_meta::INST),222		// Compat223		("__compare", builtin___compare::INST),224		("__compare_array", builtin___compare_array::INST),225		("__array_less", builtin___array_less::INST),226		("__array_greater", builtin___array_greater::INST),227		("__array_less_or_equal", builtin___array_less_or_equal::INST),228		(229			"__array_greater_or_equal",230			builtin___array_greater_or_equal::INST,231		),232	]233	.iter()234	.copied()235	{236		builder.method(name, builtin);237	}238239	builder.method(240		"extVar",241		builtin_ext_var {242			settings: settings.clone(),243		},244	);245	builder.method(246		"native",247		builtin_native {248			settings: settings.clone(),249		},250	);251	builder.method("trace", builtin_trace { settings });252	builder.method("id", FuncVal::Id);253254	#[cfg(feature = "exp-regex")]255	{256		// Regex257		let regex_cache = RegexCache::default();258		builder.method(259			"regexFullMatch",260			builtin_regex_full_match {261				cache: regex_cache.clone(),262			},263		);264		builder.method(265			"regexPartialMatch",266			builtin_regex_partial_match {267				cache: regex_cache.clone(),268			},269		);270		builder.method(271			"regexReplace",272			builtin_regex_replace {273				cache: regex_cache.clone(),274			},275		);276		builder.method(277			"regexGlobalReplace",278			builtin_regex_global_replace { cache: regex_cache },279		);280	};281282	builder.build()283}284285pub trait TracePrinter {286	fn print_trace(&self, loc: CallLocation, value: IStr);287}288289pub struct StdTracePrinter {290	resolver: PathResolver,291}292impl StdTracePrinter {293	pub fn new(resolver: PathResolver) -> Self {294		Self { resolver }295	}296}297impl TracePrinter for StdTracePrinter {298	fn print_trace(&self, loc: CallLocation, value: IStr) {299		eprint!("TRACE:");300		if let Some(loc) = loc.0 {301			let locs = loc.0.map_source_locations(&[loc.1]);302			eprint!(303				" {}:{}",304				loc.0.source_path().path().map_or_else(305					|| loc.0.source_path().to_string(),306					|p| self.resolver.resolve(p)307				),308				locs[0].line309			);310		}311		eprintln!(" {value}");312	}313}314315pub struct Settings {316	/// Used for `std.extVar`317	pub ext_vars: HashMap<IStr, TlaArg>,318	/// Used for `std.native`319	pub ext_natives: HashMap<IStr, FuncVal>,320	/// Used for `std.trace`321	pub trace_printer: Box<dyn TracePrinter>,322	/// Used for `std.thisFile`323	pub path_resolver: PathResolver,324}325326fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {327	let source_name = format!("<extvar:{name}>");328	Source::new_virtual(source_name.into(), code.into())329}330331#[derive(Trace, Clone)]332pub struct ContextInitializer {333	/// When we don't need to support legacy-this-file, we can reuse same context for all files334	#[cfg(not(feature = "legacy-this-file"))]335	context: jrsonnet_evaluator::Context,336	/// For `populate`337	#[cfg(not(feature = "legacy-this-file"))]338	stdlib_thunk: Thunk<Val>,339	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it340	#[cfg(feature = "legacy-this-file")]341	stdlib_obj: ObjValue,342	settings: Rc<RefCell<Settings>>,343}344impl ContextInitializer {345	pub fn new(s: State, resolver: PathResolver) -> Self {346		let settings = Settings {347			ext_vars: HashMap::new(),348			ext_natives: HashMap::new(),349			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),350			path_resolver: resolver,351		};352		let settings = Rc::new(RefCell::new(settings));353		let stdlib_obj = stdlib_uncached(settings.clone());354		#[cfg(not(feature = "legacy-this-file"))]355		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));356		#[cfg(feature = "legacy-this-file")]357		let _ = s;358		Self {359			#[cfg(not(feature = "legacy-this-file"))]360			context: {361				let mut context = ContextBuilder::with_capacity(s, 1);362				context.bind("std", stdlib_thunk.clone());363				context.build()364			},365			#[cfg(not(feature = "legacy-this-file"))]366			stdlib_thunk,367			#[cfg(feature = "legacy-this-file")]368			stdlib_obj,369			settings,370		}371	}372	pub fn settings(&self) -> Ref<Settings> {373		self.settings.borrow()374	}375	pub fn settings_mut(&self) -> RefMut<Settings> {376		self.settings.borrow_mut()377	}378	pub fn add_ext_var(&self, name: IStr, value: Val) {379		self.settings_mut()380			.ext_vars381			.insert(name, TlaArg::Val(value));382	}383	pub fn add_ext_str(&self, name: IStr, value: IStr) {384		self.settings_mut()385			.ext_vars386			.insert(name, TlaArg::String(value));387	}388	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {389		let code = code.into();390		let source = extvar_source(name, code.clone());391		let parsed = jrsonnet_parser::parse(392			&code,393			&jrsonnet_parser::ParserSettings {394				source: source.clone(),395			},396		)397		.map_err(|e| ImportSyntaxError {398			path: source,399			error: Box::new(e),400		})?;401		// self.data_mut().volatile_files.insert(source_name, code);402		self.settings_mut()403			.ext_vars404			.insert(name.into(), TlaArg::Code(parsed));405		Ok(())406	}407	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {408		self.settings_mut()409			.ext_natives410			.insert(name.into(), cb.into());411	}412}413impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {414	fn reserve_vars(&self) -> usize {415		1416	}417	#[cfg(not(feature = "legacy-this-file"))]418	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {419		self.context.clone()420	}421	#[cfg(not(feature = "legacy-this-file"))]422	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {423		builder.bind("std", self.stdlib_thunk.clone());424	}425	#[cfg(feature = "legacy-this-file")]426	fn populate(&self, source: Source, builder: &mut ContextBuilder) {427		let mut std = ObjValueBuilder::new();428		std.with_super(self.stdlib_obj.clone());429		std.field("thisFile").hide().value({430			let source_path = source.source_path();431			source_path.path().map_or_else(432				|| source_path.to_string(),433				|p| self.settings().path_resolver.resolve(p),434			)435		});436		let stdlib_with_this_file = std.build();437438		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));439	}440	fn as_any(&self) -> &dyn std::any::Any {441		self442	}443}444445pub trait StateExt {446	/// This method was previously implemented in jrsonnet-evaluator itself447	fn with_stdlib(&self);448}449450impl StateExt for State {451	fn with_stdlib(&self) {452		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());453		self.settings_mut().context_initializer = tb!(initializer);454	}455}