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

difftreelog

perf implement std.prune in native

Yaroslav Bolyukin2024-04-07parent: #66d8cad.patch.diff
in: master

6 files changed

modifiedcmds/jrsonnet-fmt/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet-fmt/src/main.rs
+++ b/cmds/jrsonnet-fmt/src/main.rs
@@ -356,16 +356,16 @@
 impl Printable for Member {
 	fn print(&self, out: &mut PrintItems) {
 		match self {
-			Member::MemberBindStmt(b) => {
+			Self::MemberBindStmt(b) => {
 				p!(out, { b.obj_local() })
 			}
-			Member::MemberAssertStmt(ass) => {
+			Self::MemberAssertStmt(ass) => {
 				p!(out, { ass.assertion() })
 			}
-			Member::MemberFieldNormal(n) => {
+			Self::MemberFieldNormal(n) => {
 				p!(out, {n.field_name()} if(n.plus_token().is_some())({n.plus_token()}) {n.visibility()} str(" ") {n.expr()})
 			}
-			Member::MemberFieldMethod(m) => {
+			Self::MemberFieldMethod(m) => {
 				p!(out, {m.field_name()} {m.params_desc()} {m.visibility()} str(" ") {m.expr()})
 			}
 		}
modifiedcrates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -1,6 +1,6 @@
 use std::{borrow::Cow, fmt::Write};
 
-use crate::{bail, Result, State, Val};
+use crate::{bail, Result, ResultExt, State, Val};
 
 pub trait ManifestFormat {
 	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
@@ -235,7 +235,8 @@
 						}
 					}
 					buf.push_str(cur_padding);
-					manifest_json_ex_buf(&item?, buf, cur_padding, options)?;
+					manifest_json_ex_buf(&item?, buf, cur_padding, options)
+						.with_description(|| format!("elem <{i}> manifestification"))?;
 				}
 				cur_padding.truncate(old_len);
 
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -278,7 +278,7 @@
 }
 impl ObjectLike for ThisOverride {
 	fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {
-		ObjValue::new(ThisOverride {
+		ObjValue::new(Self {
 			inner: self.inner.clone(),
 			this,
 		})
@@ -398,7 +398,7 @@
 		self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))
 	}
 
-	pub fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
+	pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {
 		self.0.get_for(key, this)
 	}
 
@@ -410,7 +410,7 @@
 		Ok(value)
 	}
 
-	fn get_raw(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
+	fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {
 		self.0.get_for_uncached(key, this)
 	}
 
@@ -422,7 +422,7 @@
 		// FIXME: Should it use `self.0.this()` in case of standalone super?
 		self.run_assertions_raw(self.clone())
 	}
-	fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {
+	fn run_assertions_raw(&self, this: Self) -> Result<()> {
 		self.0.run_assertions_raw(this)
 	}
 
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -6,7 +6,7 @@
 	runtime_error,
 	typed::{BoundedI32, BoundedUsize, Either2, NativeFn, Typed},
 	val::{equals, ArrValue, IndexableVal},
-	Either, IStr, Result, Thunk, Val,
+	Either, IStr, ObjValueBuilder, Result, ResultExt, Thunk, Val,
 };
 
 pub(crate) fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
@@ -21,16 +21,17 @@
 pub fn builtin_make_array(sz: BoundedI32<0, { i32::MAX }>, func: FuncVal) -> Result<ArrValue> {
 	if *sz == 0 {
 		return Ok(ArrValue::empty());
-	}
-	if let Some(trivial) = func.evaluate_trivial() {
-		let mut out = Vec::with_capacity(*sz as usize);
-		for _ in 0..*sz {
-			out.push(trivial.clone())
-		}
-		Ok(ArrValue::eager(out))
-	} else {
-		Ok(ArrValue::range_exclusive(0, *sz).map(func))
 	}
+	func.evaluate_trivial().map_or_else(
+		|| Ok(ArrValue::range_exclusive(0, *sz).map(func)),
+		|trivial| {
+			let mut out = Vec::with_capacity(*sz as usize);
+			for _ in 0..*sz {
+				out.push(trivial.clone());
+			}
+			Ok(ArrValue::eager(out))
+		},
+	)
 }
 
 #[builtin]
@@ -180,7 +181,7 @@
 						out += &sep;
 					}
 					first = false;
-					write!(out, "{item}").unwrap()
+					write!(out, "{item}").unwrap();
 				} else if matches!(item, Val::Null) {
 					continue;
 				} else {
@@ -320,3 +321,61 @@
 	process(value, &mut out)?;
 	Ok(out)
 }
+
+#[builtin]
+pub fn builtin_prune(
+	a: Val,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+) -> Result<Val> {
+	fn is_content(val: &Val) -> bool {
+		match val {
+			Val::Null => false,
+			Val::Arr(a) => !a.is_empty(),
+			Val::Obj(o) => !o.is_empty(),
+			_ => true,
+		}
+	}
+	Ok(match a {
+		Val::Arr(a) => {
+			let mut out = Vec::new();
+			for (i, ele) in a.iter().enumerate() {
+				let ele = ele
+					.and_then(|v| {
+						builtin_prune(
+							v,
+							#[cfg(feature = "exp-preserve-order")]
+							preserve_order,
+						)
+					})
+					.with_description(|| format!("elem <{i}> pruning"))?;
+				if is_content(&ele) {
+					out.push(ele);
+				}
+			}
+			Val::Arr(ArrValue::eager(out))
+		}
+		Val::Obj(o) => {
+			let mut out = ObjValueBuilder::new();
+			for (name, value) in o.iter(
+				#[cfg(feature = "exp-preserve-order")]
+				preserve_order,
+			) {
+				let value = value
+					.and_then(|v| {
+						builtin_prune(
+							v,
+							#[cfg(feature = "exp-preserve-order")]
+							preserve_order,
+						)
+					})
+					.with_description(|| format!("field <{name}> pruning"))?;
+				if !is_content(&value) {
+					continue;
+				}
+				out.field(name).value(value);
+			}
+			Val::Obj(out.build())
+		}
+		_ => a,
+	})
+}
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
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::{ErrorKind::*, Result},9	function::{CallLocation, FuncVal, TlaArg},10	tb,11	trace::PathResolver,12	ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,13};14use jrsonnet_gcmodule::Trace;15use jrsonnet_parser::Source;1617mod expr;18mod types;19pub use types::*;20mod arrays;21pub use arrays::*;22mod math;23pub use math::*;24mod operator;25pub use operator::*;26mod sort;27pub use sort::*;28mod hash;29pub use hash::*;30mod encoding;31pub use encoding::*;32mod objects;33pub use objects::*;34mod manifest;35pub use manifest::*;36mod parse;37pub use parse::*;38mod strings;39pub use strings::*;40mod misc;41pub use misc::*;42mod sets;43pub use sets::*;44mod compat;45pub use compat::*;46#[cfg(feature = "exp-regex")]47mod regex;48#[cfg(feature = "exp-regex")]49pub use crate::regex::*;5051#[allow(clippy::too_many_lines)]52pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {53	let mut builder = ObjValueBuilder::new();5455	let expr = expr::stdlib_expr();56	let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)57		.expect("stdlib.jsonnet should have no errors")58		.as_obj()59		.expect("stdlib.jsonnet should evaluate to object");6061	builder.with_super(eval);6263	// FIXME: Use PHF64	for (name, builtin) in [65		// Types66		("type", builtin_type::INST),67		("isString", builtin_is_string::INST),68		("isNumber", builtin_is_number::INST),69		("isBoolean", builtin_is_boolean::INST),70		("isObject", builtin_is_object::INST),71		("isArray", builtin_is_array::INST),72		("isFunction", builtin_is_function::INST),73		// Arrays74		("makeArray", builtin_make_array::INST),75		("repeat", builtin_repeat::INST),76		("slice", builtin_slice::INST),77		("map", builtin_map::INST),78		("flatMap", builtin_flatmap::INST),79		("filter", builtin_filter::INST),80		("foldl", builtin_foldl::INST),81		("foldr", builtin_foldr::INST),82		("range", builtin_range::INST),83		("join", builtin_join::INST),84		("reverse", builtin_reverse::INST),85		("any", builtin_any::INST),86		("all", builtin_all::INST),87		("member", builtin_member::INST),88		("contains", builtin_contains::INST),89		("count", builtin_count::INST),90		("avg", builtin_avg::INST),91		("removeAt", builtin_remove_at::INST),92		("remove", builtin_remove::INST),93		("flattenArrays", builtin_flatten_arrays::INST),94		("flattenDeepArray", builtin_flatten_deep_array::INST),95		("prune", builtin_prune::INST),96		("filterMap", builtin_filter_map::INST),97		// Math98		("abs", builtin_abs::INST),99		("sign", builtin_sign::INST),100		("max", builtin_max::INST),101		("min", builtin_min::INST),102		("sum", builtin_sum::INST),103		("modulo", builtin_modulo::INST),104		("floor", builtin_floor::INST),105		("ceil", builtin_ceil::INST),106		("log", builtin_log::INST),107		("pow", builtin_pow::INST),108		("sqrt", builtin_sqrt::INST),109		("sin", builtin_sin::INST),110		("cos", builtin_cos::INST),111		("tan", builtin_tan::INST),112		("asin", builtin_asin::INST),113		("acos", builtin_acos::INST),114		("atan", builtin_atan::INST),115		("atan2", builtin_atan2::INST),116		("exp", builtin_exp::INST),117		("mantissa", builtin_mantissa::INST),118		("exponent", builtin_exponent::INST),119		("round", builtin_round::INST),120		("isEven", builtin_is_even::INST),121		("isOdd", builtin_is_odd::INST),122		("isInteger", builtin_is_integer::INST),123		("isDecimal", builtin_is_decimal::INST),124		// Operator125		("mod", builtin_mod::INST),126		("primitiveEquals", builtin_primitive_equals::INST),127		("equals", builtin_equals::INST),128		("xor", builtin_xor::INST),129		("xnor", builtin_xnor::INST),130		("format", builtin_format::INST),131		// Sort132		("sort", builtin_sort::INST),133		("uniq", builtin_uniq::INST),134		("set", builtin_set::INST),135		("minArray", builtin_min_array::INST),136		("maxArray", builtin_max_array::INST),137		// Hash138		("md5", builtin_md5::INST),139		("sha1", builtin_sha1::INST),140		("sha256", builtin_sha256::INST),141		("sha512", builtin_sha512::INST),142		("sha3", builtin_sha3::INST),143		// Encoding144		("encodeUTF8", builtin_encode_utf8::INST),145		("decodeUTF8", builtin_decode_utf8::INST),146		("base64", builtin_base64::INST),147		("base64Decode", builtin_base64_decode::INST),148		("base64DecodeBytes", builtin_base64_decode_bytes::INST),149		// Objects150		("objectFieldsEx", builtin_object_fields_ex::INST),151		("objectFields", builtin_object_fields::INST),152		("objectFieldsAll", builtin_object_fields_all::INST),153		("objectValues", builtin_object_values::INST),154		("objectValuesAll", builtin_object_values_all::INST),155		("objectKeysValues", builtin_object_keys_values::INST),156		("objectKeysValuesAll", builtin_object_keys_values_all::INST),157		("objectHasEx", builtin_object_has_ex::INST),158		("objectHas", builtin_object_has::INST),159		("objectHasAll", builtin_object_has_all::INST),160		("objectRemoveKey", builtin_object_remove_key::INST),161		// Manifest162		("escapeStringJson", builtin_escape_string_json::INST),163		("manifestJsonEx", builtin_manifest_json_ex::INST),164		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),165		("manifestTomlEx", builtin_manifest_toml_ex::INST),166		("toString", builtin_to_string::INST),167		// Parsing168		("parseJson", builtin_parse_json::INST),169		("parseYaml", builtin_parse_yaml::INST),170		// Strings171		("codepoint", builtin_codepoint::INST),172		("substr", builtin_substr::INST),173		("char", builtin_char::INST),174		("strReplace", builtin_str_replace::INST),175		("isEmpty", builtin_is_empty::INST),176		("equalsIgnoreCase", builtin_equals_ignore_case::INST),177		("splitLimit", builtin_splitlimit::INST),178		("asciiUpper", builtin_ascii_upper::INST),179		("asciiLower", builtin_ascii_lower::INST),180		("findSubstr", builtin_find_substr::INST),181		("parseInt", builtin_parse_int::INST),182		#[cfg(feature = "exp-bigint")]183		("bigint", builtin_bigint::INST),184		("parseOctal", builtin_parse_octal::INST),185		("parseHex", builtin_parse_hex::INST),186		("stringChars", builtin_string_chars::INST),187		// Misc188		("length", builtin_length::INST),189		("startsWith", builtin_starts_with::INST),190		("endsWith", builtin_ends_with::INST),191		// Sets192		("setMember", builtin_set_member::INST),193		("setInter", builtin_set_inter::INST),194		("setDiff", builtin_set_diff::INST),195		("setUnion", builtin_set_union::INST),196		// Regex197		#[cfg(feature = "exp-regex")]198		("regexQuoteMeta", builtin_regex_quote_meta::INST),199		// Compat200		("__compare", builtin___compare::INST),201	]202	.iter()203	.copied()204	{205		builder.method(name, builtin);206	}207208	builder.method(209		"extVar",210		builtin_ext_var {211			settings: settings.clone(),212		},213	);214	builder.method(215		"native",216		builtin_native {217			settings: settings.clone(),218		},219	);220	builder.method("trace", builtin_trace { settings });221	builder.method("id", FuncVal::Id);222223	#[cfg(feature = "exp-regex")]224	{225		// Regex226		let regex_cache = RegexCache::default();227		builder.method(228			"regexFullMatch",229			builtin_regex_full_match {230				cache: regex_cache.clone(),231			},232		);233		builder.method(234			"regexPartialMatch",235			builtin_regex_partial_match {236				cache: regex_cache.clone(),237			},238		);239		builder.method(240			"regexReplace",241			builtin_regex_replace {242				cache: regex_cache.clone(),243			},244		);245		builder.method(246			"regexGlobalReplace",247			builtin_regex_global_replace {248				cache: regex_cache.clone(),249			},250		);251	};252253	builder.build()254}255256pub trait TracePrinter {257	fn print_trace(&self, loc: CallLocation, value: IStr);258}259260pub struct StdTracePrinter {261	resolver: PathResolver,262}263impl StdTracePrinter {264	pub fn new(resolver: PathResolver) -> Self {265		Self { resolver }266	}267}268impl TracePrinter for StdTracePrinter {269	fn print_trace(&self, loc: CallLocation, value: IStr) {270		eprint!("TRACE:");271		if let Some(loc) = loc.0 {272			let locs = loc.0.map_source_locations(&[loc.1]);273			eprint!(274				" {}:{}",275				loc.0.source_path().path().map_or_else(276					|| loc.0.source_path().to_string(),277					|p| self.resolver.resolve(p)278				),279				locs[0].line280			);281		}282		eprintln!(" {value}");283	}284}285286pub struct Settings {287	/// Used for `std.extVar`288	pub ext_vars: HashMap<IStr, TlaArg>,289	/// Used for `std.native`290	pub ext_natives: HashMap<IStr, FuncVal>,291	/// Used for `std.trace`292	pub trace_printer: Box<dyn TracePrinter>,293	/// Used for `std.thisFile`294	pub path_resolver: PathResolver,295}296297fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {298	let source_name = format!("<extvar:{name}>");299	Source::new_virtual(source_name.into(), code.into())300}301302#[derive(Trace, Clone)]303pub struct ContextInitializer {304	/// When we don't need to support legacy-this-file, we can reuse same context for all files305	#[cfg(not(feature = "legacy-this-file"))]306	context: jrsonnet_evaluator::Context,307	/// For `populate`308	#[cfg(not(feature = "legacy-this-file"))]309	stdlib_thunk: Thunk<Val>,310	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it311	#[cfg(feature = "legacy-this-file")]312	stdlib_obj: ObjValue,313	settings: Rc<RefCell<Settings>>,314}315impl ContextInitializer {316	pub fn new(_s: State, resolver: PathResolver) -> Self {317		let settings = Settings {318			ext_vars: Default::default(),319			ext_natives: Default::default(),320			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),321			path_resolver: resolver,322		};323		let settings = Rc::new(RefCell::new(settings));324		let stdlib_obj = stdlib_uncached(settings.clone());325		#[cfg(not(feature = "legacy-this-file"))]326		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));327		Self {328			#[cfg(not(feature = "legacy-this-file"))]329			context: {330				let mut context = ContextBuilder::with_capacity(_s, 1);331				context.bind("std", stdlib_thunk.clone());332				context.build()333			},334			#[cfg(not(feature = "legacy-this-file"))]335			stdlib_thunk,336			#[cfg(feature = "legacy-this-file")]337			stdlib_obj,338			settings,339		}340	}341	pub fn settings(&self) -> Ref<Settings> {342		self.settings.borrow()343	}344	pub fn settings_mut(&self) -> RefMut<Settings> {345		self.settings.borrow_mut()346	}347	pub fn add_ext_var(&self, name: IStr, value: Val) {348		self.settings_mut()349			.ext_vars350			.insert(name, TlaArg::Val(value));351	}352	pub fn add_ext_str(&self, name: IStr, value: IStr) {353		self.settings_mut()354			.ext_vars355			.insert(name, TlaArg::String(value));356	}357	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {358		let code = code.into();359		let source = extvar_source(name, code.clone());360		let parsed = jrsonnet_parser::parse(361			&code,362			&jrsonnet_parser::ParserSettings {363				source: source.clone(),364			},365		)366		.map_err(|e| ImportSyntaxError {367			path: source,368			error: Box::new(e),369		})?;370		// self.data_mut().volatile_files.insert(source_name, code);371		self.settings_mut()372			.ext_vars373			.insert(name.into(), TlaArg::Code(parsed));374		Ok(())375	}376	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {377		self.settings_mut()378			.ext_natives379			.insert(name.into(), cb.into());380	}381}382impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {383	fn reserve_vars(&self) -> usize {384		1385	}386	#[cfg(not(feature = "legacy-this-file"))]387	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {388		self.context.clone()389	}390	#[cfg(not(feature = "legacy-this-file"))]391	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {392		builder.bind("std", self.stdlib_thunk.clone());393	}394	#[cfg(feature = "legacy-this-file")]395	fn populate(&self, source: Source, builder: &mut ContextBuilder) {396		use jrsonnet_evaluator::val::StrValue;397398		let mut std = ObjValueBuilder::new();399		std.with_super(self.stdlib_obj.clone());400		std.field("thisFile")401			.hide()402			.value(match source.source_path().path() {403				Some(p) => self.settings().path_resolver.resolve(p),404				None => source.source_path().to_string(),405			});406		let stdlib_with_this_file = std.build();407408		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));409	}410	fn as_any(&self) -> &dyn std::any::Any {411		self412	}413}414415pub trait StateExt {416	/// This method was previously implemented in jrsonnet-evaluator itself417	fn with_stdlib(&self);418}419420impl StateExt for State {421	fn with_stdlib(&self) {422		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());423		self.settings_mut().context_initializer = tb!(initializer);424	}425}
modifiedcrates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/std.jsonnet
+++ b/crates/jrsonnet-stdlib/src/std.jsonnet
@@ -209,25 +209,6 @@
     local arr = std.split(f, '/');
     std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),
 
-  prune(a)::
-    local isContent(b) =
-      if b == null then
-        false
-      else if std.isArray(b) then
-        std.length(b) > 0
-      else if std.isObject(b) then
-        std.length(b) > 0
-      else
-        true;
-    if std.isArray(a) then
-      [std.prune(x) for x in a if isContent($.prune(x))]
-    else if std.isObject(a) then {
-      [x]: $.prune(a[x])
-      for x in std.objectFields(a)
-      if isContent(std.prune(a[x]))
-    } else
-      a,
-
   find(value, arr)::
     if !std.isArray(arr) then
       error 'find second parameter should be an array, got ' + std.type(arr)