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
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -84,6 +84,8 @@
 		("avg", builtin_avg::INST),
 		("removeAt", builtin_remove_at::INST),
 		("remove", builtin_remove::INST),
+		("flattenArrays", builtin_flatten_arrays::INST),
+		("filterMap", builtin_filter_map::INST),
 		// Math
 		("abs", builtin_abs::INST),
 		("sign", builtin_sign::INST),
@@ -137,17 +139,22 @@
 		("base64DecodeBytes", builtin_base64_decode_bytes::INST),
 		// Objects
 		("objectFieldsEx", builtin_object_fields_ex::INST),
+		("objectFields", builtin_object_fields::INST),
+		("objectFieldsAll", builtin_object_fields_all::INST),
 		("objectValues", builtin_object_values::INST),
 		("objectValuesAll", builtin_object_values_all::INST),
 		("objectKeysValues", builtin_object_keys_values::INST),
 		("objectKeysValuesAll", builtin_object_keys_values_all::INST),
 		("objectHasEx", builtin_object_has_ex::INST),
+		("objectHas", builtin_object_has::INST),
+		("objectHasAll", builtin_object_has_all::INST),
 		("objectRemoveKey", builtin_object_remove_key::INST),
 		// Manifest
 		("escapeStringJson", builtin_escape_string_json::INST),
 		("manifestJsonEx", builtin_manifest_json_ex::INST),
 		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),
 		("manifestTomlEx", builtin_manifest_toml_ex::INST),
+		("toString", builtin_to_string::INST),
 		// Parsing
 		("parseJson", builtin_parse_json::INST),
 		("parseYaml", builtin_parse_yaml::INST),
@@ -167,6 +174,7 @@
 		("bigint", builtin_bigint::INST),
 		("parseOctal", builtin_parse_octal::INST),
 		("parseHex", builtin_parse_hex::INST),
+		("stringChars", builtin_string_chars::INST),
 		// Misc
 		("length", builtin_length::INST),
 		("startsWith", builtin_starts_with::INST),
@@ -175,6 +183,7 @@
 		("setMember", builtin_set_member::INST),
 		("setInter", builtin_set_inter::INST),
 		("setDiff", builtin_set_diff::INST),
+		("setUnion", builtin_set_union::INST),
 		// Compat
 		("__compare", builtin___compare::INST),
 	]
@@ -347,19 +356,15 @@
 
 		let mut std = ObjValueBuilder::new();
 		std.with_super(self.stdlib_obj.clone());
-		std.field("thisFile".into())
+		std.field("thisFile")
 			.hide()
-			.value(Val::string(match source.source_path().path() {
-				Some(p) => self.settings().path_resolver.resolve(p).into(),
-				None => source.source_path().to_string().into(),
-			}))
-			.expect("this object builder is empty");
+			.value(match source.source_path().path() {
+				Some(p) => self.settings().path_resolver.resolve(p),
+				None => source.source_path().to_string(),
+			});
 		let stdlib_with_this_file = std.build();
 
-		builder.bind(
-			"std".into(),
-			Thunk::evaluated(Val::Obj(stdlib_with_this_file)),
-		);
+		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));
 	}
 	fn as_any(&self) -> &dyn std::any::Any {
 		self
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
before · crates/jrsonnet-stdlib/src/objects.rs
1use jrsonnet_evaluator::{2	function::builtin,3	val::{ArrValue, StrValue, Val},4	IStr, ObjValue, ObjValueBuilder,5};67#[builtin]8pub fn builtin_object_fields_ex(9	obj: ObjValue,10	hidden: bool,11	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,12) -> Vec<Val> {13	#[cfg(feature = "exp-preserve-order")]14	let preserve_order = preserve_order.unwrap_or(false);15	let out = obj.fields_ex(16		hidden,17		#[cfg(feature = "exp-preserve-order")]18		preserve_order,19	);20	out.into_iter()21		.map(StrValue::Flat)22		.map(Val::Str)23		.collect::<Vec<_>>()24}2526pub fn builtin_object_values_ex(27	o: ObjValue,28	include_hidden: bool,29	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,30) -> ArrValue {31	#[cfg(feature = "exp-preserve-order")]32	let preserve_order = preserve_order.unwrap_or(false);33	o.values_ex(34		include_hidden,35		#[cfg(feature = "exp-preserve-order")]36		preserve_order,37	)38}39#[builtin]40pub fn builtin_object_values(41	o: ObjValue,42	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,43) -> ArrValue {44	builtin_object_values_ex(45		o,46		false,47		#[cfg(feature = "exp-preserve-order")]48		preserve_order,49	)50}51#[builtin]52pub fn builtin_object_values_all(53	o: ObjValue,54	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,55) -> ArrValue {56	builtin_object_values_ex(57		o,58		true,59		#[cfg(feature = "exp-preserve-order")]60		preserve_order,61	)62}6364pub fn builtin_object_keys_values_ex(65	o: ObjValue,66	include_hidden: bool,67	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,68) -> ArrValue {69	#[cfg(feature = "exp-preserve-order")]70	let preserve_order = preserve_order.unwrap_or(false);71	o.key_values_ex(72		include_hidden,73		#[cfg(feature = "exp-preserve-order")]74		preserve_order,75	)76}77#[builtin]78pub fn builtin_object_keys_values(79	o: ObjValue,80	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,81) -> ArrValue {82	builtin_object_keys_values_ex(83		o,84		false,85		#[cfg(feature = "exp-preserve-order")]86		preserve_order,87	)88}89#[builtin]90pub fn builtin_object_keys_values_all(91	o: ObjValue,92	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,93) -> ArrValue {94	builtin_object_keys_values_ex(95		o,96		true,97		#[cfg(feature = "exp-preserve-order")]98		preserve_order,99	)100}101102#[builtin]103pub fn builtin_object_has_ex(obj: ObjValue, fname: IStr, hidden: bool) -> bool {104	obj.has_field_ex(fname, hidden)105}106107#[builtin]108pub fn builtin_object_remove_key(109	obj: ObjValue,110	key: IStr,111	// Standard implementation uses std.objectFields without such argument, we can't112	// assume order preservation should always be enabled/disabled113	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,114) -> ObjValue {115	#[cfg(feature = "exp-preserve-order")]116	let preserve_order = preserve_order.unwrap_or(false);117	let mut new_obj = ObjValueBuilder::with_capacity(obj.len() - 1);118	for (k, v) in obj.iter(119		#[cfg(feature = "exp-preserve-order")]120		preserve_order,121	) {122		if k == key {123			continue;124		}125		new_obj.field(k).value(v.unwrap())126	}127128	new_obj.build()129}
after · crates/jrsonnet-stdlib/src/objects.rs
1use jrsonnet_evaluator::{2	function::builtin,3	val::{ArrValue, Val},4	IStr, ObjValue, ObjValueBuilder,5};67#[builtin]8pub fn builtin_object_fields_ex(9	obj: ObjValue,10	hidden: bool,11	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,12) -> Vec<Val> {13	#[cfg(feature = "exp-preserve-order")]14	let preserve_order = preserve_order.unwrap_or(false);15	let out = obj.fields_ex(16		hidden,17		#[cfg(feature = "exp-preserve-order")]18		preserve_order,19	);20	out.into_iter().map(Val::string).collect::<Vec<_>>()21}2223#[builtin]24pub fn builtin_object_fields(25	o: ObjValue,26	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,27) -> Vec<Val> {28	builtin_object_fields_ex(29		o,30		false,31		#[cfg(feature = "exp-preserve-order")]32		preserve_order,33	)34}3536#[builtin]37pub fn builtin_object_fields_all(38	o: ObjValue,39	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,40) -> Vec<Val> {41	builtin_object_fields_ex(42		o,43		true,44		#[cfg(feature = "exp-preserve-order")]45		preserve_order,46	)47}4849pub fn builtin_object_values_ex(50	o: ObjValue,51	include_hidden: bool,52	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,53) -> ArrValue {54	#[cfg(feature = "exp-preserve-order")]55	let preserve_order = preserve_order.unwrap_or(false);56	o.values_ex(57		include_hidden,58		#[cfg(feature = "exp-preserve-order")]59		preserve_order,60	)61}62#[builtin]63pub fn builtin_object_values(64	o: ObjValue,65	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,66) -> ArrValue {67	builtin_object_values_ex(68		o,69		false,70		#[cfg(feature = "exp-preserve-order")]71		preserve_order,72	)73}74#[builtin]75pub fn builtin_object_values_all(76	o: ObjValue,77	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,78) -> ArrValue {79	builtin_object_values_ex(80		o,81		true,82		#[cfg(feature = "exp-preserve-order")]83		preserve_order,84	)85}8687pub fn builtin_object_keys_values_ex(88	o: ObjValue,89	include_hidden: bool,90	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,91) -> ArrValue {92	#[cfg(feature = "exp-preserve-order")]93	let preserve_order = preserve_order.unwrap_or(false);94	o.key_values_ex(95		include_hidden,96		#[cfg(feature = "exp-preserve-order")]97		preserve_order,98	)99}100#[builtin]101pub fn builtin_object_keys_values(102	o: ObjValue,103	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,104) -> ArrValue {105	builtin_object_keys_values_ex(106		o,107		false,108		#[cfg(feature = "exp-preserve-order")]109		preserve_order,110	)111}112#[builtin]113pub fn builtin_object_keys_values_all(114	o: ObjValue,115	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,116) -> ArrValue {117	builtin_object_keys_values_ex(118		o,119		true,120		#[cfg(feature = "exp-preserve-order")]121		preserve_order,122	)123}124125#[builtin]126pub fn builtin_object_has_ex(obj: ObjValue, fname: IStr, hidden: bool) -> bool {127	obj.has_field_ex(fname, hidden)128}129130#[builtin]131pub fn builtin_object_has(o: ObjValue, f: IStr) -> bool {132	o.has_field(f)133}134135#[builtin]136pub fn builtin_object_has_all(o: ObjValue, f: IStr) -> bool {137	o.has_field_include_hidden(f)138}139140#[builtin]141pub fn builtin_object_remove_key(142	obj: ObjValue,143	key: IStr,144	// Standard implementation uses std.objectFields without such argument, we can't145	// assume order preservation should always be enabled/disabled146	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,147) -> ObjValue {148	#[cfg(feature = "exp-preserve-order")]149	let preserve_order = preserve_order.unwrap_or(false);150	let mut new_obj = ObjValueBuilder::with_capacity(obj.len() - 1);151	for (k, v) in obj.iter(152		#[cfg(feature = "exp-preserve-order")]153		preserve_order,154	) {155		if k == key {156			continue;157		}158		new_obj.field(k).value(v.unwrap())159	}160161	new_obj.build()162}
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())
+}