Skip to content

Commit 89a6508

Browse files
committed
perf: move more stdlib functions to native
1 parent 218d8cc commit 89a6508

File tree

7 files changed

+146
-63
lines changed

7 files changed

+146
-63
lines changed

crates/jrsonnet-stdlib/src/arrays.rs

+28
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,15 @@ pub fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {
102102
arr.filter(|val| bool::from_untyped(func.evaluate_simple(&(val.clone(),), false)?))
103103
}
104104

105+
#[builtin]
106+
pub fn builtin_filter_map(
107+
filter_func: FuncVal,
108+
map_func: FuncVal,
109+
arr: ArrValue,
110+
) -> Result<ArrValue> {
111+
Ok(builtin_filter(filter_func, arr)?.map(map_func))
112+
}
113+
105114
#[builtin]
106115
pub fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Val) -> Result<Val> {
107116
let mut acc = init;
@@ -274,3 +283,22 @@ pub fn builtin_remove(arr: ArrValue, elem: Val) -> Result<ArrValue> {
274283
}
275284
Ok(arr)
276285
}
286+
287+
#[builtin]
288+
pub fn builtin_flatten_arrays(arrs: Vec<ArrValue>) -> ArrValue {
289+
pub fn flatten_inner(values: &[ArrValue]) -> ArrValue {
290+
if values.len() == 1 {
291+
return values[0].clone();
292+
} else if values.len() == 2 {
293+
return ArrValue::extended(values[0].clone(), values[1].clone());
294+
}
295+
let (a, b) = values.split_at(values.len() / 2);
296+
ArrValue::extended(flatten_inner(a), flatten_inner(b))
297+
}
298+
if arrs.is_empty() {
299+
return ArrValue::empty();
300+
} else if arrs.len() == 1 {
301+
return arrs.into_iter().next().expect("single");
302+
}
303+
flatten_inner(&arrs)
304+
}

crates/jrsonnet-stdlib/src/lib.rs

+15-10
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {
8484
("avg", builtin_avg::INST),
8585
("removeAt", builtin_remove_at::INST),
8686
("remove", builtin_remove::INST),
87+
("flattenArrays", builtin_flatten_arrays::INST),
88+
("filterMap", builtin_filter_map::INST),
8789
// Math
8890
("abs", builtin_abs::INST),
8991
("sign", builtin_sign::INST),
@@ -137,17 +139,22 @@ pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {
137139
("base64DecodeBytes", builtin_base64_decode_bytes::INST),
138140
// Objects
139141
("objectFieldsEx", builtin_object_fields_ex::INST),
142+
("objectFields", builtin_object_fields::INST),
143+
("objectFieldsAll", builtin_object_fields_all::INST),
140144
("objectValues", builtin_object_values::INST),
141145
("objectValuesAll", builtin_object_values_all::INST),
142146
("objectKeysValues", builtin_object_keys_values::INST),
143147
("objectKeysValuesAll", builtin_object_keys_values_all::INST),
144148
("objectHasEx", builtin_object_has_ex::INST),
149+
("objectHas", builtin_object_has::INST),
150+
("objectHasAll", builtin_object_has_all::INST),
145151
("objectRemoveKey", builtin_object_remove_key::INST),
146152
// Manifest
147153
("escapeStringJson", builtin_escape_string_json::INST),
148154
("manifestJsonEx", builtin_manifest_json_ex::INST),
149155
("manifestYamlDoc", builtin_manifest_yaml_doc::INST),
150156
("manifestTomlEx", builtin_manifest_toml_ex::INST),
157+
("toString", builtin_to_string::INST),
151158
// Parsing
152159
("parseJson", builtin_parse_json::INST),
153160
("parseYaml", builtin_parse_yaml::INST),
@@ -167,6 +174,7 @@ pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {
167174
("bigint", builtin_bigint::INST),
168175
("parseOctal", builtin_parse_octal::INST),
169176
("parseHex", builtin_parse_hex::INST),
177+
("stringChars", builtin_string_chars::INST),
170178
// Misc
171179
("length", builtin_length::INST),
172180
("startsWith", builtin_starts_with::INST),
@@ -175,6 +183,7 @@ pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {
175183
("setMember", builtin_set_member::INST),
176184
("setInter", builtin_set_inter::INST),
177185
("setDiff", builtin_set_diff::INST),
186+
("setUnion", builtin_set_union::INST),
178187
// Compat
179188
("__compare", builtin___compare::INST),
180189
]
@@ -347,19 +356,15 @@ impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {
347356

348357
let mut std = ObjValueBuilder::new();
349358
std.with_super(self.stdlib_obj.clone());
350-
std.field("thisFile".into())
359+
std.field("thisFile")
351360
.hide()
352-
.value(Val::string(match source.source_path().path() {
353-
Some(p) => self.settings().path_resolver.resolve(p).into(),
354-
None => source.source_path().to_string().into(),
355-
}))
356-
.expect("this object builder is empty");
361+
.value(match source.source_path().path() {
362+
Some(p) => self.settings().path_resolver.resolve(p),
363+
None => source.source_path().to_string(),
364+
});
357365
let stdlib_with_this_file = std.build();
358366

359-
builder.bind(
360-
"std".into(),
361-
Thunk::evaluated(Val::Obj(stdlib_with_this_file)),
362-
);
367+
builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));
363368
}
364369
fn as_any(&self) -> &dyn std::any::Any {
365370
self

crates/jrsonnet-stdlib/src/manifest/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,8 @@ pub fn builtin_manifest_toml_ex(
6060
preserve_order.unwrap_or(false),
6161
))
6262
}
63+
64+
#[builtin]
65+
pub fn builtin_to_string(a: Val) -> Result<IStr> {
66+
a.to_string()
67+
}

crates/jrsonnet-stdlib/src/objects.rs

+38-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use jrsonnet_evaluator::{
22
function::builtin,
3-
val::{ArrValue, StrValue, Val},
3+
val::{ArrValue, Val},
44
IStr, ObjValue, ObjValueBuilder,
55
};
66

@@ -17,10 +17,33 @@ pub fn builtin_object_fields_ex(
1717
#[cfg(feature = "exp-preserve-order")]
1818
preserve_order,
1919
);
20-
out.into_iter()
21-
.map(StrValue::Flat)
22-
.map(Val::Str)
23-
.collect::<Vec<_>>()
20+
out.into_iter().map(Val::string).collect::<Vec<_>>()
21+
}
22+
23+
#[builtin]
24+
pub 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+
}
35+
36+
#[builtin]
37+
pub 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+
)
2447
}
2548

2649
pub fn builtin_object_values_ex(
@@ -104,6 +127,16 @@ pub fn builtin_object_has_ex(obj: ObjValue, fname: IStr, hidden: bool) -> bool {
104127
obj.has_field_ex(fname, hidden)
105128
}
106129

130+
#[builtin]
131+
pub fn builtin_object_has(o: ObjValue, f: IStr) -> bool {
132+
o.has_field(f)
133+
}
134+
135+
#[builtin]
136+
pub fn builtin_object_has_all(o: ObjValue, f: IStr) -> bool {
137+
o.has_field_include_hidden(f)
138+
}
139+
107140
#[builtin]
108141
pub fn builtin_object_remove_key(
109142
obj: ObjValue,

crates/jrsonnet-stdlib/src/sets.rs

+55
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ pub fn builtin_set_inter(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Res
7070
}
7171
Ok(ArrValue::lazy(out))
7272
}
73+
7374
#[builtin]
7475
#[allow(non_snake_case, clippy::redundant_closure)]
7576
pub fn builtin_set_diff(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
@@ -115,3 +116,57 @@ pub fn builtin_set_diff(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Resu
115116
}
116117
Ok(ArrValue::lazy(out))
117118
}
119+
120+
#[builtin]
121+
#[allow(non_snake_case, clippy::redundant_closure)]
122+
pub fn builtin_set_union(a: ArrValue, b: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {
123+
let mut a = a.iter_lazy();
124+
let mut b = b.iter_lazy();
125+
126+
let keyF = keyF
127+
.unwrap_or(FuncVal::identity())
128+
.into_native::<((Thunk<Val>,), Val)>();
129+
let keyF = |v| keyF(v);
130+
131+
let mut av = a.next();
132+
let mut bv = b.next();
133+
let mut ak = av.clone().map(keyF).transpose()?;
134+
let mut bk = bv.clone().map(keyF).transpose()?;
135+
136+
let mut out = Vec::new();
137+
while let (Some(ac), Some(bc)) = (&ak, &bk) {
138+
match evaluate_compare_op(ac, bc, BinaryOpType::Lt)? {
139+
Ordering::Less => {
140+
out.push(av.clone().expect("ak != None"));
141+
av = a.next();
142+
ak = av.clone().map(keyF).transpose()?;
143+
}
144+
Ordering::Greater => {
145+
out.push(bv.clone().expect("bk != None"));
146+
bv = b.next();
147+
bk = bv.clone().map(keyF).transpose()?;
148+
}
149+
Ordering::Equal => {
150+
// NOTE: order matters, values in `a` win
151+
out.push(av.clone().expect("ak != None"));
152+
av = a.next();
153+
ak = av.clone().map(keyF).transpose()?;
154+
bv = b.next();
155+
bk = bv.clone().map(keyF).transpose()?;
156+
}
157+
};
158+
}
159+
// a.len() > b.len()
160+
while let Some(_ac) = &ak {
161+
out.push(av.clone().expect("ak != None"));
162+
av = a.next();
163+
ak = av.clone().map(keyF).transpose()?;
164+
}
165+
// b.len() > a.len()
166+
while let Some(_bc) = &bk {
167+
out.push(bv.clone().expect("ak != None"));
168+
bv = b.next();
169+
bk = bv.clone().map(keyF).transpose()?;
170+
}
171+
Ok(ArrValue::lazy(out))
172+
}

crates/jrsonnet-stdlib/src/std.jsonnet

-48
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44

55
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',
66

7-
toString(a):: '' + a,
8-
97
lstripChars(str, chars)::
108
if std.length(str) > 0 && std.member(chars, str[0]) then
119
std.lstripChars(str[1:], chars)
@@ -22,9 +20,6 @@
2220
stripChars(str, chars)::
2321
std.lstripChars(std.rstripChars(str, chars), chars),
2422

25-
stringChars(str)::
26-
std.makeArray(std.length(str), function(i) str[i]),
27-
2823
splitLimitR(str, c, maxsplits)::
2924
if maxsplits == -1 then
3025
std.splitLimit(str, c, -1)
@@ -61,16 +56,6 @@
6156
else
6257
error 'Expected string or array, got %s' % std.type(arr),
6358

64-
filterMap(filter_func, map_func, arr)::
65-
if !std.isFunction(filter_func) then
66-
error ('std.filterMap first param must be function, got ' + std.type(filter_func))
67-
else if !std.isFunction(map_func) then
68-
error ('std.filterMap second param must be function, got ' + std.type(map_func))
69-
else if !std.isArray(arr) then
70-
error ('std.filterMap third param must be array, got ' + std.type(arr))
71-
else
72-
std.map(map_func, std.filter(filter_func, arr)),
73-
7459
assertEqual(a, b)::
7560
if a == b then
7661
true
@@ -82,9 +67,6 @@
8267
else if x > maxVal then maxVal
8368
else x,
8469

85-
flattenArrays(arrs)::
86-
std.foldl(function(a, b) a + b, arrs, []),
87-
8870
manifestIni(ini)::
8971
local body_lines(body) =
9072
std.join([], [
@@ -196,24 +178,6 @@
196178

197179
aux(value),
198180

199-
setUnion(a, b, keyF=id)::
200-
// NOTE: order matters, values in `a` win
201-
local aux(a, b, i, j, acc) =
202-
if i >= std.length(a) then
203-
acc + b[j:]
204-
else if j >= std.length(b) then
205-
acc + a[i:]
206-
else
207-
local ak = keyF(a[i]);
208-
local bk = keyF(b[j]);
209-
if ak == bk then
210-
aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict
211-
else if ak < bk then
212-
aux(a, b, i + 1, j, acc + [a[i]]) tailstrict
213-
else
214-
aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;
215-
aux(a, b, 0, 0, []),
216-
217181
mergePatch(target, patch)::
218182
if std.isObject(patch) then
219183
local target_object =
@@ -241,18 +205,6 @@
241205
get(o, f, default=null, inc_hidden=true)::
242206
if std.objectHasEx(o, f, inc_hidden) then o[f] else default,
243207

244-
objectFields(o)::
245-
std.objectFieldsEx(o, false),
246-
247-
objectFieldsAll(o)::
248-
std.objectFieldsEx(o, true),
249-
250-
objectHas(o, f)::
251-
std.objectHasEx(o, f, false),
252-
253-
objectHasAll(o, f)::
254-
std.objectHasEx(o, f, true),
255-
256208
resolvePath(f, r)::
257209
local arr = std.split(f, '/');
258210
std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),

crates/jrsonnet-stdlib/src/strings.rs

+5
Original file line numberDiff line numberDiff line change
@@ -198,3 +198,8 @@ mod tests {
198198
assert_eq!(parse_nat::<16>("BbC").unwrap(), 0xBBC as f64);
199199
}
200200
}
201+
202+
#[builtin]
203+
pub fn builtin_string_chars(str: IStr) -> ArrValue {
204+
ArrValue::chars(str.chars())
205+
}

0 commit comments

Comments
 (0)