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

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		("manifestIni", builtin_manifest_ini::INST),183		// Parse184		("parseJson", builtin_parse_json::INST),185		("parseYaml", builtin_parse_yaml::INST),186		// Strings187		("codepoint", builtin_codepoint::INST),188		("substr", builtin_substr::INST),189		("char", builtin_char::INST),190		("strReplace", builtin_str_replace::INST),191		("escapeStringBash", builtin_escape_string_bash::INST),192		("escapeStringDollars", builtin_escape_string_dollars::INST),193		("isEmpty", builtin_is_empty::INST),194		("equalsIgnoreCase", builtin_equals_ignore_case::INST),195		("splitLimit", builtin_splitlimit::INST),196		("splitLimitR", builtin_splitlimitr::INST),197		("split", builtin_split::INST),198		("asciiUpper", builtin_ascii_upper::INST),199		("asciiLower", builtin_ascii_lower::INST),200		("findSubstr", builtin_find_substr::INST),201		("parseInt", builtin_parse_int::INST),202		#[cfg(feature = "exp-bigint")]203		("bigint", builtin_bigint::INST),204		("parseOctal", builtin_parse_octal::INST),205		("parseHex", builtin_parse_hex::INST),206		("stringChars", builtin_string_chars::INST),207		("lstripChars", builtin_lstrip_chars::INST),208		("rstripChars", builtin_rstrip_chars::INST),209		("stripChars", builtin_strip_chars::INST),210		// Misc211		("length", builtin_length::INST),212		("get", builtin_get::INST),213		("startsWith", builtin_starts_with::INST),214		("endsWith", builtin_ends_with::INST),215		// Sets216		("setMember", builtin_set_member::INST),217		("setInter", builtin_set_inter::INST),218		("setDiff", builtin_set_diff::INST),219		("setUnion", builtin_set_union::INST),220		// Regex221		#[cfg(feature = "exp-regex")]222		("regexQuoteMeta", builtin_regex_quote_meta::INST),223		// Compat224		("__compare", builtin___compare::INST),225		("__compare_array", builtin___compare_array::INST),226		("__array_less", builtin___array_less::INST),227		("__array_greater", builtin___array_greater::INST),228		("__array_less_or_equal", builtin___array_less_or_equal::INST),229		(230			"__array_greater_or_equal",231			builtin___array_greater_or_equal::INST,232		),233	]234	.iter()235	.copied()236	{237		builder.method(name, builtin);238	}239240	builder.method(241		"extVar",242		builtin_ext_var {243			settings: settings.clone(),244		},245	);246	builder.method(247		"native",248		builtin_native {249			settings: settings.clone(),250		},251	);252	builder.method("trace", builtin_trace { settings });253	builder.method("id", FuncVal::Id);254255	#[cfg(feature = "exp-regex")]256	{257		// Regex258		let regex_cache = RegexCache::default();259		builder.method(260			"regexFullMatch",261			builtin_regex_full_match {262				cache: regex_cache.clone(),263			},264		);265		builder.method(266			"regexPartialMatch",267			builtin_regex_partial_match {268				cache: regex_cache.clone(),269			},270		);271		builder.method(272			"regexReplace",273			builtin_regex_replace {274				cache: regex_cache.clone(),275			},276		);277		builder.method(278			"regexGlobalReplace",279			builtin_regex_global_replace { cache: regex_cache },280		);281	};282283	builder.build()284}285286pub trait TracePrinter {287	fn print_trace(&self, loc: CallLocation, value: IStr);288}289290pub struct StdTracePrinter {291	resolver: PathResolver,292}293impl StdTracePrinter {294	pub fn new(resolver: PathResolver) -> Self {295		Self { resolver }296	}297}298impl TracePrinter for StdTracePrinter {299	fn print_trace(&self, loc: CallLocation, value: IStr) {300		eprint!("TRACE:");301		if let Some(loc) = loc.0 {302			let locs = loc.0.map_source_locations(&[loc.1]);303			eprint!(304				" {}:{}",305				loc.0.source_path().path().map_or_else(306					|| loc.0.source_path().to_string(),307					|p| self.resolver.resolve(p)308				),309				locs[0].line310			);311		}312		eprintln!(" {value}");313	}314}315316pub struct Settings {317	/// Used for `std.extVar`318	pub ext_vars: HashMap<IStr, TlaArg>,319	/// Used for `std.native`320	pub ext_natives: HashMap<IStr, FuncVal>,321	/// Used for `std.trace`322	pub trace_printer: Box<dyn TracePrinter>,323	/// Used for `std.thisFile`324	pub path_resolver: PathResolver,325}326327fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {328	let source_name = format!("<extvar:{name}>");329	Source::new_virtual(source_name.into(), code.into())330}331332#[derive(Trace, Clone)]333pub struct ContextInitializer {334	/// When we don't need to support legacy-this-file, we can reuse same context for all files335	#[cfg(not(feature = "legacy-this-file"))]336	context: jrsonnet_evaluator::Context,337	/// For `populate`338	#[cfg(not(feature = "legacy-this-file"))]339	stdlib_thunk: Thunk<Val>,340	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it341	#[cfg(feature = "legacy-this-file")]342	stdlib_obj: ObjValue,343	settings: Rc<RefCell<Settings>>,344}345impl ContextInitializer {346	pub fn new(s: State, resolver: PathResolver) -> Self {347		let settings = Settings {348			ext_vars: HashMap::new(),349			ext_natives: HashMap::new(),350			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),351			path_resolver: resolver,352		};353		let settings = Rc::new(RefCell::new(settings));354		let stdlib_obj = stdlib_uncached(settings.clone());355		#[cfg(not(feature = "legacy-this-file"))]356		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));357		#[cfg(feature = "legacy-this-file")]358		let _ = s;359		Self {360			#[cfg(not(feature = "legacy-this-file"))]361			context: {362				let mut context = ContextBuilder::with_capacity(s, 1);363				context.bind("std", stdlib_thunk.clone());364				context.build()365			},366			#[cfg(not(feature = "legacy-this-file"))]367			stdlib_thunk,368			#[cfg(feature = "legacy-this-file")]369			stdlib_obj,370			settings,371		}372	}373	pub fn settings(&self) -> Ref<Settings> {374		self.settings.borrow()375	}376	pub fn settings_mut(&self) -> RefMut<Settings> {377		self.settings.borrow_mut()378	}379	pub fn add_ext_var(&self, name: IStr, value: Val) {380		self.settings_mut()381			.ext_vars382			.insert(name, TlaArg::Val(value));383	}384	pub fn add_ext_str(&self, name: IStr, value: IStr) {385		self.settings_mut()386			.ext_vars387			.insert(name, TlaArg::String(value));388	}389	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {390		let code = code.into();391		let source = extvar_source(name, code.clone());392		let parsed = jrsonnet_parser::parse(393			&code,394			&jrsonnet_parser::ParserSettings {395				source: source.clone(),396			},397		)398		.map_err(|e| ImportSyntaxError {399			path: source,400			error: Box::new(e),401		})?;402		// self.data_mut().volatile_files.insert(source_name, code);403		self.settings_mut()404			.ext_vars405			.insert(name.into(), TlaArg::Code(parsed));406		Ok(())407	}408	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {409		self.settings_mut()410			.ext_natives411			.insert(name.into(), cb.into());412	}413}414impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {415	fn reserve_vars(&self) -> usize {416		1417	}418	#[cfg(not(feature = "legacy-this-file"))]419	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {420		self.context.clone()421	}422	#[cfg(not(feature = "legacy-this-file"))]423	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {424		builder.bind("std", self.stdlib_thunk.clone());425	}426	#[cfg(feature = "legacy-this-file")]427	fn populate(&self, source: Source, builder: &mut ContextBuilder) {428		let mut std = ObjValueBuilder::new();429		std.with_super(self.stdlib_obj.clone());430		std.field("thisFile").hide().value({431			let source_path = source.source_path();432			source_path.path().map_or_else(433				|| source_path.to_string(),434				|p| self.settings().path_resolver.resolve(p),435			)436		});437		let stdlib_with_this_file = std.build();438439		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));440	}441	fn as_any(&self) -> &dyn std::any::Any {442		self443	}444}445446pub trait StateExt {447	/// This method was previously implemented in jrsonnet-evaluator itself448	fn with_stdlib(&self);449}450451impl StateExt for State {452	fn with_stdlib(&self) {453		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());454		self.settings_mut().context_initializer = tb!(initializer);455	}456}