git.delta.rocks / jrsonnet / refs/commits / 89a650875ae4

difftreelog

perf move more stdlib functions to native

Yaroslav Bolyukin2023-08-13parent: #218d8cc.patch.diff
in: master

7 files changed

modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -103,6 +103,15 @@
 }
 
 #[builtin]
+pub fn builtin_filter_map(
+	filter_func: FuncVal,
+	map_func: FuncVal,
+	arr: ArrValue,
+) -> Result<ArrValue> {
+	Ok(builtin_filter(filter_func, arr)?.map(map_func))
+}
+
+#[builtin]
 pub fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Val) -> Result<Val> {
 	let mut acc = init;
 	for i in arr.iter() {
@@ -274,3 +283,22 @@
 	}
 	Ok(arr)
 }
+
+#[builtin]
+pub fn builtin_flatten_arrays(arrs: Vec<ArrValue>) -> ArrValue {
+	pub fn flatten_inner(values: &[ArrValue]) -> ArrValue {
+		if values.len() == 1 {
+			return values[0].clone();
+		} else if values.len() == 2 {
+			return ArrValue::extended(values[0].clone(), values[1].clone());
+		}
+		let (a, b) = values.split_at(values.len() / 2);
+		ArrValue::extended(flatten_inner(a), flatten_inner(b))
+	}
+	if arrs.is_empty() {
+		return ArrValue::empty();
+	} else if arrs.len() == 1 {
+		return arrs.into_iter().next().expect("single");
+	}
+	flatten_inner(&arrs)
+}
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
84 ("avg", builtin_avg::INST),84 ("avg", builtin_avg::INST),
85 ("removeAt", builtin_remove_at::INST),85 ("removeAt", builtin_remove_at::INST),
86 ("remove", builtin_remove::INST),86 ("remove", builtin_remove::INST),
87 ("flattenArrays", builtin_flatten_arrays::INST),
88 ("filterMap", builtin_filter_map::INST),
87 // Math89 // Math
88 ("abs", builtin_abs::INST),90 ("abs", builtin_abs::INST),
89 ("sign", builtin_sign::INST),91 ("sign", builtin_sign::INST),
137 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),139 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),
138 // Objects140 // Objects
139 ("objectFieldsEx", builtin_object_fields_ex::INST),141 ("objectFieldsEx", builtin_object_fields_ex::INST),
142 ("objectFields", builtin_object_fields::INST),
143 ("objectFieldsAll", builtin_object_fields_all::INST),
140 ("objectValues", builtin_object_values::INST),144 ("objectValues", builtin_object_values::INST),
141 ("objectValuesAll", builtin_object_values_all::INST),145 ("objectValuesAll", builtin_object_values_all::INST),
142 ("objectKeysValues", builtin_object_keys_values::INST),146 ("objectKeysValues", builtin_object_keys_values::INST),
143 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),147 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),
144 ("objectHasEx", builtin_object_has_ex::INST),148 ("objectHasEx", builtin_object_has_ex::INST),
149 ("objectHas", builtin_object_has::INST),
150 ("objectHasAll", builtin_object_has_all::INST),
145 ("objectRemoveKey", builtin_object_remove_key::INST),151 ("objectRemoveKey", builtin_object_remove_key::INST),
146 // Manifest152 // Manifest
147 ("escapeStringJson", builtin_escape_string_json::INST),153 ("escapeStringJson", builtin_escape_string_json::INST),
148 ("manifestJsonEx", builtin_manifest_json_ex::INST),154 ("manifestJsonEx", builtin_manifest_json_ex::INST),
149 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),155 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),
150 ("manifestTomlEx", builtin_manifest_toml_ex::INST),156 ("manifestTomlEx", builtin_manifest_toml_ex::INST),
157 ("toString", builtin_to_string::INST),
151 // Parsing158 // Parsing
152 ("parseJson", builtin_parse_json::INST),159 ("parseJson", builtin_parse_json::INST),
153 ("parseYaml", builtin_parse_yaml::INST),160 ("parseYaml", builtin_parse_yaml::INST),
167 ("bigint", builtin_bigint::INST),174 ("bigint", builtin_bigint::INST),
168 ("parseOctal", builtin_parse_octal::INST),175 ("parseOctal", builtin_parse_octal::INST),
169 ("parseHex", builtin_parse_hex::INST),176 ("parseHex", builtin_parse_hex::INST),
177 ("stringChars", builtin_string_chars::INST),
170 // Misc178 // Misc
171 ("length", builtin_length::INST),179 ("length", builtin_length::INST),
172 ("startsWith", builtin_starts_with::INST),180 ("startsWith", builtin_starts_with::INST),
175 ("setMember", builtin_set_member::INST),183 ("setMember", builtin_set_member::INST),
176 ("setInter", builtin_set_inter::INST),184 ("setInter", builtin_set_inter::INST),
177 ("setDiff", builtin_set_diff::INST),185 ("setDiff", builtin_set_diff::INST),
186 ("setUnion", builtin_set_union::INST),
178 // Compat187 // Compat
179 ("__compare", builtin___compare::INST),188 ("__compare", builtin___compare::INST),
180 ]189 ]
347356
348 let mut std = ObjValueBuilder::new();357 let mut std = ObjValueBuilder::new();
349 std.with_super(self.stdlib_obj.clone());358 std.with_super(self.stdlib_obj.clone());
350 std.field("thisFile".into())359 std.field("thisFile")
351 .hide()360 .hide()
352 .value(Val::string(match source.source_path().path() {361 .value(match source.source_path().path() {
353 Some(p) => self.settings().path_resolver.resolve(p).into(),362 Some(p) => self.settings().path_resolver.resolve(p),
354 None => source.source_path().to_string().into(),363 None => source.source_path().to_string(),
355 }))364 });
356 .expect("this object builder is empty");
357 let stdlib_with_this_file = std.build();365 let stdlib_with_this_file = std.build();
358366
359 builder.bind(367 builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));
360 "std".into(),
361 Thunk::evaluated(Val::Obj(stdlib_with_this_file)),
362 );
363 }368 }
364 fn as_any(&self) -> &dyn std::any::Any {369 fn as_any(&self) -> &dyn std::any::Any {
modifiedcrates/jrsonnet-stdlib/src/manifest/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/mod.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/mod.rs
@@ -60,3 +60,8 @@
 		preserve_order.unwrap_or(false),
 	))
 }
+
+#[builtin]
+pub fn builtin_to_string(a: Val) -> Result<IStr> {
+	a.to_string()
+}
modifiedcrates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -1,6 +1,6 @@
 use jrsonnet_evaluator::{
 	function::builtin,
-	val::{ArrValue, StrValue, Val},
+	val::{ArrValue, Val},
 	IStr, ObjValue, ObjValueBuilder,
 };
 
@@ -17,12 +17,35 @@
 		#[cfg(feature = "exp-preserve-order")]
 		preserve_order,
 	);
-	out.into_iter()
-		.map(StrValue::Flat)
-		.map(Val::Str)
-		.collect::<Vec<_>>()
+	out.into_iter().map(Val::string).collect::<Vec<_>>()
+}
+
+#[builtin]
+pub fn builtin_object_fields(
+	o: ObjValue,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> Vec<Val> {
+	builtin_object_fields_ex(
+		o,
+		false,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	)
 }
 
+#[builtin]
+pub fn builtin_object_fields_all(
+	o: ObjValue,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> Vec<Val> {
+	builtin_object_fields_ex(
+		o,
+		true,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	)
+}
+
 pub fn builtin_object_values_ex(
 	o: ObjValue,
 	include_hidden: bool,
@@ -105,6 +128,16 @@
 }
 
 #[builtin]
+pub fn builtin_object_has(o: ObjValue, f: IStr) -> bool {
+	o.has_field(f)
+}
+
+#[builtin]
+pub fn builtin_object_has_all(o: ObjValue, f: IStr) -> bool {
+	o.has_field_include_hidden(f)
+}
+
+#[builtin]
 pub fn builtin_object_remove_key(
 	obj: ObjValue,
 	key: IStr,
modifiedcrates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -70,6 +70,7 @@
 	}
 	Ok(ArrValue::lazy(out))
 }
+
 #[builtin]
 #[allow(non_snake_case, clippy::redundant_closure)]
 pub fn builtin_set_diff(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
@@ -115,3 +116,57 @@
 	}
 	Ok(ArrValue::lazy(out))
 }
+
+#[builtin]
+#[allow(non_snake_case, clippy::redundant_closure)]
+pub fn builtin_set_union(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
+	let mut a = a.iter_lazy();
+	let mut b = b.iter_lazy();
+
+	let keyF = keyF
+		.unwrap_or(FuncVal::identity())
+		.into_native::<((Thunk<Val>,), Val)>();
+	let keyF = |v| keyF(v);
+
+	let mut av = a.next();
+	let mut bv = b.next();
+	let mut ak = av.clone().map(keyF).transpose()?;
+	let mut bk = bv.clone().map(keyF).transpose()?;
+
+	let mut out = Vec::new();
+	while let (Some(ac), Some(bc)) = (&ak, &bk) {
+		match evaluate_compare_op(ac, bc, BinaryOpType::Lt)? {
+			Ordering::Less => {
+				out.push(av.clone().expect("ak != None"));
+				av = a.next();
+				ak = av.clone().map(keyF).transpose()?;
+			}
+			Ordering::Greater => {
+				out.push(bv.clone().expect("bk != None"));
+				bv = b.next();
+				bk = bv.clone().map(keyF).transpose()?;
+			}
+			Ordering::Equal => {
+				// NOTE: order matters, values in `a` win
+				out.push(av.clone().expect("ak != None"));
+				av = a.next();
+				ak = av.clone().map(keyF).transpose()?;
+				bv = b.next();
+				bk = bv.clone().map(keyF).transpose()?;
+			}
+		};
+	}
+	// a.len() > b.len()
+	while let Some(_ac) = &ak {
+		out.push(av.clone().expect("ak != None"));
+		av = a.next();
+		ak = av.clone().map(keyF).transpose()?;
+	}
+	// b.len() > a.len()
+	while let Some(_bc) = &bk {
+		out.push(bv.clone().expect("ak != None"));
+		bv = b.next();
+		bk = bv.clone().map(keyF).transpose()?;
+	}
+	Ok(ArrValue::lazy(out))
+}
modifiedcrates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/std.jsonnet
+++ b/crates/jrsonnet-stdlib/src/std.jsonnet
@@ -4,8 +4,6 @@
 
   thisFile:: error 'std.thisFile is deprecated, to enable its support in jrsonnet - recompile it with "legacy-this-file" support.\nThis will slow down stdlib caching a bit, though',
 
-  toString(a):: '' + a,
-
   lstripChars(str, chars)::
     if std.length(str) > 0 && std.member(chars, str[0]) then
       std.lstripChars(str[1:], chars)
@@ -21,9 +19,6 @@
 
   stripChars(str, chars)::
     std.lstripChars(std.rstripChars(str, chars), chars),
-
-  stringChars(str)::
-    std.makeArray(std.length(str), function(i) str[i]),
 
   splitLimitR(str, c, maxsplits)::
     if maxsplits == -1 then
@@ -60,16 +55,6 @@
       std.join('', [std.deepJoin(x) for x in arr])
     else
       error 'Expected string or array, got %s' % std.type(arr),
-
-  filterMap(filter_func, map_func, arr)::
-    if !std.isFunction(filter_func) then
-      error ('std.filterMap first param must be function, got ' + std.type(filter_func))
-    else if !std.isFunction(map_func) then
-      error ('std.filterMap second param must be function, got ' + std.type(map_func))
-    else if !std.isArray(arr) then
-      error ('std.filterMap third param must be array, got ' + std.type(arr))
-    else
-      std.map(map_func, std.filter(filter_func, arr)),
 
   assertEqual(a, b)::
     if a == b then
@@ -81,9 +66,6 @@
     if x < minVal then minVal
     else if x > maxVal then maxVal
     else x,
-
-  flattenArrays(arrs)::
-    std.foldl(function(a, b) a + b, arrs, []),
 
   manifestIni(ini)::
     local body_lines(body) =
@@ -195,24 +177,6 @@
           std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);
 
       aux(value),
-
-  setUnion(a, b, keyF=id)::
-    // NOTE: order matters, values in `a` win
-    local aux(a, b, i, j, acc) =
-      if i >= std.length(a) then
-        acc + b[j:]
-      else if j >= std.length(b) then
-        acc + a[i:]
-      else
-        local ak = keyF(a[i]);
-        local bk = keyF(b[j]);
-        if ak == bk then
-          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict
-        else if ak < bk then
-          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict
-        else
-          aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;
-    aux(a, b, 0, 0, []),
 
   mergePatch(target, patch)::
     if std.isObject(patch) then
@@ -240,18 +204,6 @@
 
   get(o, f, default=null, inc_hidden=true)::
     if std.objectHasEx(o, f, inc_hidden) then o[f] else default,
-
-  objectFields(o)::
-    std.objectFieldsEx(o, false),
-
-  objectFieldsAll(o)::
-    std.objectFieldsEx(o, true),
-
-  objectHas(o, f)::
-    std.objectHasEx(o, f, false),
-
-  objectHasAll(o, f)::
-    std.objectHasEx(o, f, true),
 
   resolvePath(f, r)::
     local arr = std.split(f, '/');
modifiedcrates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -198,3 +198,8 @@
 		assert_eq!(parse_nat::<16>("BbC").unwrap(), 0xBBC as f64);
 	}
 }
+
+#[builtin]
+pub fn builtin_string_chars(str: IStr) -> ArrValue {
+	ArrValue::chars(str.chars())
+}