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
6 runtime_error,6 runtime_error,
7 typed::{BoundedI32, BoundedUsize, Either2, NativeFn, Typed},7 typed::{BoundedI32, BoundedUsize, Either2, NativeFn, Typed},
8 val::{equals, ArrValue, IndexableVal},8 val::{equals, ArrValue, IndexableVal},
9 Either, IStr, Result, Thunk, Val,9 Either, IStr, ObjValueBuilder, Result, ResultExt, Thunk, Val,
10};10};
1111
12pub(crate) fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {12pub(crate) fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
22 if *sz == 0 {22 if *sz == 0 {
23 return Ok(ArrValue::empty());23 return Ok(ArrValue::empty());
24 }24 }
25 if let Some(trivial) = func.evaluate_trivial() {25 func.evaluate_trivial().map_or_else(
26 || Ok(ArrValue::range_exclusive(0, *sz).map(func)),
27 |trivial| {
26 let mut out = Vec::with_capacity(*sz as usize);28 let mut out = Vec::with_capacity(*sz as usize);
27 for _ in 0..*sz {29 for _ in 0..*sz {
28 out.push(trivial.clone())30 out.push(trivial.clone());
29 }31 }
30 Ok(ArrValue::eager(out))32 Ok(ArrValue::eager(out))
31 } else {33 },
32 Ok(ArrValue::range_exclusive(0, *sz).map(func))34 )
33 }
34}35}
3536
36#[builtin]37#[builtin]
180 out += &sep;181 out += &sep;
181 }182 }
182 first = false;183 first = false;
183 write!(out, "{item}").unwrap()184 write!(out, "{item}").unwrap();
184 } else if matches!(item, Val::Null) {185 } else if matches!(item, Val::Null) {
185 continue;186 continue;
186 } else {187 } else {
321 Ok(out)322 Ok(out)
322}323}
324
325#[builtin]
326pub fn builtin_prune(
327 a: Val,
328 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
329) -> Result<Val> {
330 fn is_content(val: &Val) -> bool {
331 match val {
332 Val::Null => false,
333 Val::Arr(a) => !a.is_empty(),
334 Val::Obj(o) => !o.is_empty(),
335 _ => true,
336 }
337 }
338 Ok(match a {
339 Val::Arr(a) => {
340 let mut out = Vec::new();
341 for (i, ele) in a.iter().enumerate() {
342 let ele = ele
343 .and_then(|v| {
344 builtin_prune(
345 v,
346 #[cfg(feature = "exp-preserve-order")]
347 preserve_order,
348 )
349 })
350 .with_description(|| format!("elem <{i}> pruning"))?;
351 if is_content(&ele) {
352 out.push(ele);
353 }
354 }
355 Val::Arr(ArrValue::eager(out))
356 }
357 Val::Obj(o) => {
358 let mut out = ObjValueBuilder::new();
359 for (name, value) in o.iter(
360 #[cfg(feature = "exp-preserve-order")]
361 preserve_order,
362 ) {
363 let value = value
364 .and_then(|v| {
365 builtin_prune(
366 v,
367 #[cfg(feature = "exp-preserve-order")]
368 preserve_order,
369 )
370 })
371 .with_description(|| format!("field <{name}> pruning"))?;
372 if !is_content(&value) {
373 continue;
374 }
375 out.field(name).value(value);
376 }
377 Val::Obj(out.build())
378 }
379 _ => a,
380 })
381}
323382
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -92,6 +92,7 @@
 		("remove", builtin_remove::INST),
 		("flattenArrays", builtin_flatten_arrays::INST),
 		("flattenDeepArray", builtin_flatten_deep_array::INST),
+		("prune", builtin_prune::INST),
 		("filterMap", builtin_filter_map::INST),
 		// Math
 		("abs", builtin_abs::INST),
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)