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

difftreelog

source

crates/jrsonnet-stdlib/src/lib.rs12.8 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		("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	]223	.iter()224	.copied()225	{226		builder.method(name, builtin);227	}228229	builder.method(230		"extVar",231		builtin_ext_var {232			settings: settings.clone(),233		},234	);235	builder.method(236		"native",237		builtin_native {238			settings: settings.clone(),239		},240	);241	builder.method("trace", builtin_trace { settings });242	builder.method("id", FuncVal::Id);243244	#[cfg(feature = "exp-regex")]245	{246		// Regex247		let regex_cache = RegexCache::default();248		builder.method(249			"regexFullMatch",250			builtin_regex_full_match {251				cache: regex_cache.clone(),252			},253		);254		builder.method(255			"regexPartialMatch",256			builtin_regex_partial_match {257				cache: regex_cache.clone(),258			},259		);260		builder.method(261			"regexReplace",262			builtin_regex_replace {263				cache: regex_cache.clone(),264			},265		);266		builder.method(267			"regexGlobalReplace",268			builtin_regex_global_replace { cache: regex_cache },269		);270	};271272	builder.build()273}274275pub trait TracePrinter {276	fn print_trace(&self, loc: CallLocation, value: IStr);277}278279pub struct StdTracePrinter {280	resolver: PathResolver,281}282impl StdTracePrinter {283	pub fn new(resolver: PathResolver) -> Self {284		Self { resolver }285	}286}287impl TracePrinter for StdTracePrinter {288	fn print_trace(&self, loc: CallLocation, value: IStr) {289		eprint!("TRACE:");290		if let Some(loc) = loc.0 {291			let locs = loc.0.map_source_locations(&[loc.1]);292			eprint!(293				" {}:{}",294				loc.0.source_path().path().map_or_else(295					|| loc.0.source_path().to_string(),296					|p| self.resolver.resolve(p)297				),298				locs[0].line299			);300		}301		eprintln!(" {value}");302	}303}304305pub struct Settings {306	/// Used for `std.extVar`307	pub ext_vars: HashMap<IStr, TlaArg>,308	/// Used for `std.native`309	pub ext_natives: HashMap<IStr, FuncVal>,310	/// Used for `std.trace`311	pub trace_printer: Box<dyn TracePrinter>,312	/// Used for `std.thisFile`313	pub path_resolver: PathResolver,314}315316fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {317	let source_name = format!("<extvar:{name}>");318	Source::new_virtual(source_name.into(), code.into())319}320321#[derive(Trace, Clone)]322pub struct ContextInitializer {323	/// When we don't need to support legacy-this-file, we can reuse same context for all files324	#[cfg(not(feature = "legacy-this-file"))]325	context: jrsonnet_evaluator::Context,326	/// For `populate`327	#[cfg(not(feature = "legacy-this-file"))]328	stdlib_thunk: Thunk<Val>,329	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it330	#[cfg(feature = "legacy-this-file")]331	stdlib_obj: ObjValue,332	settings: Rc<RefCell<Settings>>,333}334impl ContextInitializer {335	pub fn new(s: State, resolver: PathResolver) -> Self {336		let settings = Settings {337			ext_vars: HashMap::new(),338			ext_natives: HashMap::new(),339			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),340			path_resolver: resolver,341		};342		let settings = Rc::new(RefCell::new(settings));343		let stdlib_obj = stdlib_uncached(settings.clone());344		#[cfg(not(feature = "legacy-this-file"))]345		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));346		#[cfg(feature = "legacy-this-file")]347		let _ = s;348		Self {349			#[cfg(not(feature = "legacy-this-file"))]350			context: {351				let mut context = ContextBuilder::with_capacity(s, 1);352				context.bind("std", stdlib_thunk.clone());353				context.build()354			},355			#[cfg(not(feature = "legacy-this-file"))]356			stdlib_thunk,357			#[cfg(feature = "legacy-this-file")]358			stdlib_obj,359			settings,360		}361	}362	pub fn settings(&self) -> Ref<Settings> {363		self.settings.borrow()364	}365	pub fn settings_mut(&self) -> RefMut<Settings> {366		self.settings.borrow_mut()367	}368	pub fn add_ext_var(&self, name: IStr, value: Val) {369		self.settings_mut()370			.ext_vars371			.insert(name, TlaArg::Val(value));372	}373	pub fn add_ext_str(&self, name: IStr, value: IStr) {374		self.settings_mut()375			.ext_vars376			.insert(name, TlaArg::String(value));377	}378	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {379		let code = code.into();380		let source = extvar_source(name, code.clone());381		let parsed = jrsonnet_parser::parse(382			&code,383			&jrsonnet_parser::ParserSettings {384				source: source.clone(),385			},386		)387		.map_err(|e| ImportSyntaxError {388			path: source,389			error: Box::new(e),390		})?;391		// self.data_mut().volatile_files.insert(source_name, code);392		self.settings_mut()393			.ext_vars394			.insert(name.into(), TlaArg::Code(parsed));395		Ok(())396	}397	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {398		self.settings_mut()399			.ext_natives400			.insert(name.into(), cb.into());401	}402}403impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {404	fn reserve_vars(&self) -> usize {405		1406	}407	#[cfg(not(feature = "legacy-this-file"))]408	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {409		self.context.clone()410	}411	#[cfg(not(feature = "legacy-this-file"))]412	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {413		builder.bind("std", self.stdlib_thunk.clone());414	}415	#[cfg(feature = "legacy-this-file")]416	fn populate(&self, source: Source, builder: &mut ContextBuilder) {417		let mut std = ObjValueBuilder::new();418		std.with_super(self.stdlib_obj.clone());419		std.field("thisFile").hide().value({420			let source_path = source.source_path();421			source_path.path().map_or_else(422				|| source_path.to_string(),423				|p| self.settings().path_resolver.resolve(p),424			)425		});426		let stdlib_with_this_file = std.build();427428		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));429	}430	fn as_any(&self) -> &dyn std::any::Any {431		self432	}433}434435pub trait StateExt {436	/// This method was previously implemented in jrsonnet-evaluator itself437	fn with_stdlib(&self);438}439440impl StateExt for State {441	fn with_stdlib(&self) {442		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());443		self.settings_mut().context_initializer = tb!(initializer);444	}445}