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
before · 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		("filterMap", builtin_filter_map::INST),96		// Math97		("abs", builtin_abs::INST),98		("sign", builtin_sign::INST),99		("max", builtin_max::INST),100		("min", builtin_min::INST),101		("sum", builtin_sum::INST),102		("modulo", builtin_modulo::INST),103		("floor", builtin_floor::INST),104		("ceil", builtin_ceil::INST),105		("log", builtin_log::INST),106		("pow", builtin_pow::INST),107		("sqrt", builtin_sqrt::INST),108		("sin", builtin_sin::INST),109		("cos", builtin_cos::INST),110		("tan", builtin_tan::INST),111		("asin", builtin_asin::INST),112		("acos", builtin_acos::INST),113		("atan", builtin_atan::INST),114		("atan2", builtin_atan2::INST),115		("exp", builtin_exp::INST),116		("mantissa", builtin_mantissa::INST),117		("exponent", builtin_exponent::INST),118		("round", builtin_round::INST),119		("isEven", builtin_is_even::INST),120		("isOdd", builtin_is_odd::INST),121		("isInteger", builtin_is_integer::INST),122		("isDecimal", builtin_is_decimal::INST),123		// Operator124		("mod", builtin_mod::INST),125		("primitiveEquals", builtin_primitive_equals::INST),126		("equals", builtin_equals::INST),127		("xor", builtin_xor::INST),128		("xnor", builtin_xnor::INST),129		("format", builtin_format::INST),130		// Sort131		("sort", builtin_sort::INST),132		("uniq", builtin_uniq::INST),133		("set", builtin_set::INST),134		("minArray", builtin_min_array::INST),135		("maxArray", builtin_max_array::INST),136		// Hash137		("md5", builtin_md5::INST),138		("sha1", builtin_sha1::INST),139		("sha256", builtin_sha256::INST),140		("sha512", builtin_sha512::INST),141		("sha3", builtin_sha3::INST),142		// Encoding143		("encodeUTF8", builtin_encode_utf8::INST),144		("decodeUTF8", builtin_decode_utf8::INST),145		("base64", builtin_base64::INST),146		("base64Decode", builtin_base64_decode::INST),147		("base64DecodeBytes", builtin_base64_decode_bytes::INST),148		// Objects149		("objectFieldsEx", builtin_object_fields_ex::INST),150		("objectFields", builtin_object_fields::INST),151		("objectFieldsAll", builtin_object_fields_all::INST),152		("objectValues", builtin_object_values::INST),153		("objectValuesAll", builtin_object_values_all::INST),154		("objectKeysValues", builtin_object_keys_values::INST),155		("objectKeysValuesAll", builtin_object_keys_values_all::INST),156		("objectHasEx", builtin_object_has_ex::INST),157		("objectHas", builtin_object_has::INST),158		("objectHasAll", builtin_object_has_all::INST),159		("objectRemoveKey", builtin_object_remove_key::INST),160		// Manifest161		("escapeStringJson", builtin_escape_string_json::INST),162		("manifestJsonEx", builtin_manifest_json_ex::INST),163		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),164		("manifestTomlEx", builtin_manifest_toml_ex::INST),165		("toString", builtin_to_string::INST),166		// Parsing167		("parseJson", builtin_parse_json::INST),168		("parseYaml", builtin_parse_yaml::INST),169		// Strings170		("codepoint", builtin_codepoint::INST),171		("substr", builtin_substr::INST),172		("char", builtin_char::INST),173		("strReplace", builtin_str_replace::INST),174		("isEmpty", builtin_is_empty::INST),175		("equalsIgnoreCase", builtin_equals_ignore_case::INST),176		("splitLimit", builtin_splitlimit::INST),177		("asciiUpper", builtin_ascii_upper::INST),178		("asciiLower", builtin_ascii_lower::INST),179		("findSubstr", builtin_find_substr::INST),180		("parseInt", builtin_parse_int::INST),181		#[cfg(feature = "exp-bigint")]182		("bigint", builtin_bigint::INST),183		("parseOctal", builtin_parse_octal::INST),184		("parseHex", builtin_parse_hex::INST),185		("stringChars", builtin_string_chars::INST),186		// Misc187		("length", builtin_length::INST),188		("startsWith", builtin_starts_with::INST),189		("endsWith", builtin_ends_with::INST),190		// Sets191		("setMember", builtin_set_member::INST),192		("setInter", builtin_set_inter::INST),193		("setDiff", builtin_set_diff::INST),194		("setUnion", builtin_set_union::INST),195		// Regex196		#[cfg(feature = "exp-regex")]197		("regexQuoteMeta", builtin_regex_quote_meta::INST),198		// Compat199		("__compare", builtin___compare::INST),200	]201	.iter()202	.copied()203	{204		builder.method(name, builtin);205	}206207	builder.method(208		"extVar",209		builtin_ext_var {210			settings: settings.clone(),211		},212	);213	builder.method(214		"native",215		builtin_native {216			settings: settings.clone(),217		},218	);219	builder.method("trace", builtin_trace { settings });220	builder.method("id", FuncVal::Id);221222	#[cfg(feature = "exp-regex")]223	{224		// Regex225		let regex_cache = RegexCache::default();226		builder.method(227			"regexFullMatch",228			builtin_regex_full_match {229				cache: regex_cache.clone(),230			},231		);232		builder.method(233			"regexPartialMatch",234			builtin_regex_partial_match {235				cache: regex_cache.clone(),236			},237		);238		builder.method(239			"regexReplace",240			builtin_regex_replace {241				cache: regex_cache.clone(),242			},243		);244		builder.method(245			"regexGlobalReplace",246			builtin_regex_global_replace {247				cache: regex_cache.clone(),248			},249		);250	};251252	builder.build()253}254255pub trait TracePrinter {256	fn print_trace(&self, loc: CallLocation, value: IStr);257}258259pub struct StdTracePrinter {260	resolver: PathResolver,261}262impl StdTracePrinter {263	pub fn new(resolver: PathResolver) -> Self {264		Self { resolver }265	}266}267impl TracePrinter for StdTracePrinter {268	fn print_trace(&self, loc: CallLocation, value: IStr) {269		eprint!("TRACE:");270		if let Some(loc) = loc.0 {271			let locs = loc.0.map_source_locations(&[loc.1]);272			eprint!(273				" {}:{}",274				loc.0.source_path().path().map_or_else(275					|| loc.0.source_path().to_string(),276					|p| self.resolver.resolve(p)277				),278				locs[0].line279			);280		}281		eprintln!(" {value}");282	}283}284285pub struct Settings {286	/// Used for `std.extVar`287	pub ext_vars: HashMap<IStr, TlaArg>,288	/// Used for `std.native`289	pub ext_natives: HashMap<IStr, FuncVal>,290	/// Used for `std.trace`291	pub trace_printer: Box<dyn TracePrinter>,292	/// Used for `std.thisFile`293	pub path_resolver: PathResolver,294}295296fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {297	let source_name = format!("<extvar:{name}>");298	Source::new_virtual(source_name.into(), code.into())299}300301#[derive(Trace, Clone)]302pub struct ContextInitializer {303	/// When we don't need to support legacy-this-file, we can reuse same context for all files304	#[cfg(not(feature = "legacy-this-file"))]305	context: jrsonnet_evaluator::Context,306	/// For `populate`307	#[cfg(not(feature = "legacy-this-file"))]308	stdlib_thunk: Thunk<Val>,309	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it310	#[cfg(feature = "legacy-this-file")]311	stdlib_obj: ObjValue,312	settings: Rc<RefCell<Settings>>,313}314impl ContextInitializer {315	pub fn new(_s: State, resolver: PathResolver) -> Self {316		let settings = Settings {317			ext_vars: Default::default(),318			ext_natives: Default::default(),319			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),320			path_resolver: resolver,321		};322		let settings = Rc::new(RefCell::new(settings));323		let stdlib_obj = stdlib_uncached(settings.clone());324		#[cfg(not(feature = "legacy-this-file"))]325		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));326		Self {327			#[cfg(not(feature = "legacy-this-file"))]328			context: {329				let mut context = ContextBuilder::with_capacity(_s, 1);330				context.bind("std", stdlib_thunk.clone());331				context.build()332			},333			#[cfg(not(feature = "legacy-this-file"))]334			stdlib_thunk,335			#[cfg(feature = "legacy-this-file")]336			stdlib_obj,337			settings,338		}339	}340	pub fn settings(&self) -> Ref<Settings> {341		self.settings.borrow()342	}343	pub fn settings_mut(&self) -> RefMut<Settings> {344		self.settings.borrow_mut()345	}346	pub fn add_ext_var(&self, name: IStr, value: Val) {347		self.settings_mut()348			.ext_vars349			.insert(name, TlaArg::Val(value));350	}351	pub fn add_ext_str(&self, name: IStr, value: IStr) {352		self.settings_mut()353			.ext_vars354			.insert(name, TlaArg::String(value));355	}356	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {357		let code = code.into();358		let source = extvar_source(name, code.clone());359		let parsed = jrsonnet_parser::parse(360			&code,361			&jrsonnet_parser::ParserSettings {362				source: source.clone(),363			},364		)365		.map_err(|e| ImportSyntaxError {366			path: source,367			error: Box::new(e),368		})?;369		// self.data_mut().volatile_files.insert(source_name, code);370		self.settings_mut()371			.ext_vars372			.insert(name.into(), TlaArg::Code(parsed));373		Ok(())374	}375	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {376		self.settings_mut()377			.ext_natives378			.insert(name.into(), cb.into());379	}380}381impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {382	fn reserve_vars(&self) -> usize {383		1384	}385	#[cfg(not(feature = "legacy-this-file"))]386	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {387		self.context.clone()388	}389	#[cfg(not(feature = "legacy-this-file"))]390	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {391		builder.bind("std", self.stdlib_thunk.clone());392	}393	#[cfg(feature = "legacy-this-file")]394	fn populate(&self, source: Source, builder: &mut ContextBuilder) {395		use jrsonnet_evaluator::val::StrValue;396397		let mut std = ObjValueBuilder::new();398		std.with_super(self.stdlib_obj.clone());399		std.field("thisFile")400			.hide()401			.value(match source.source_path().path() {402				Some(p) => self.settings().path_resolver.resolve(p),403				None => source.source_path().to_string(),404			});405		let stdlib_with_this_file = std.build();406407		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));408	}409	fn as_any(&self) -> &dyn std::any::Any {410		self411	}412}413414pub trait StateExt {415	/// This method was previously implemented in jrsonnet-evaluator itself416	fn with_stdlib(&self);417}418419impl StateExt for State {420	fn with_stdlib(&self) {421		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());422		self.settings_mut().context_initializer = tb!(initializer);423	}424}
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)