git.delta.rocks / jrsonnet / refs/commits / 57f709a58e12

difftreelog

source

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