difftreelog
perf move more stdlib functions to native
in: master
7 files changed
crates/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)
+}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth1use 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::*;4647pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {48 let mut builder = ObjValueBuilder::new();4950 let expr = expr::stdlib_expr();51 let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)52 .expect("stdlib.jsonnet should have no errors")53 .as_obj()54 .expect("stdlib.jsonnet should evaluate to object");5556 builder.with_super(eval);5758 for (name, builtin) in [59 // Types60 ("type", builtin_type::INST),61 ("isString", builtin_is_string::INST),62 ("isNumber", builtin_is_number::INST),63 ("isBoolean", builtin_is_boolean::INST),64 ("isObject", builtin_is_object::INST),65 ("isArray", builtin_is_array::INST),66 ("isFunction", builtin_is_function::INST),67 // Arrays68 ("makeArray", builtin_make_array::INST),69 ("repeat", builtin_repeat::INST),70 ("slice", builtin_slice::INST),71 ("map", builtin_map::INST),72 ("flatMap", builtin_flatmap::INST),73 ("filter", builtin_filter::INST),74 ("foldl", builtin_foldl::INST),75 ("foldr", builtin_foldr::INST),76 ("range", builtin_range::INST),77 ("join", builtin_join::INST),78 ("reverse", builtin_reverse::INST),79 ("any", builtin_any::INST),80 ("all", builtin_all::INST),81 ("member", builtin_member::INST),82 ("contains", builtin_contains::INST),83 ("count", builtin_count::INST),84 ("avg", builtin_avg::INST),85 ("removeAt", builtin_remove_at::INST),86 ("remove", builtin_remove::INST),87 // Math88 ("abs", builtin_abs::INST),89 ("sign", builtin_sign::INST),90 ("max", builtin_max::INST),91 ("min", builtin_min::INST),92 ("sum", builtin_sum::INST),93 ("modulo", builtin_modulo::INST),94 ("floor", builtin_floor::INST),95 ("ceil", builtin_ceil::INST),96 ("log", builtin_log::INST),97 ("pow", builtin_pow::INST),98 ("sqrt", builtin_sqrt::INST),99 ("sin", builtin_sin::INST),100 ("cos", builtin_cos::INST),101 ("tan", builtin_tan::INST),102 ("asin", builtin_asin::INST),103 ("acos", builtin_acos::INST),104 ("atan", builtin_atan::INST),105 ("exp", builtin_exp::INST),106 ("mantissa", builtin_mantissa::INST),107 ("exponent", builtin_exponent::INST),108 ("round", builtin_round::INST),109 ("isEven", builtin_is_even::INST),110 ("isOdd", builtin_is_odd::INST),111 ("isInteger", builtin_is_integer::INST),112 ("isDecimal", builtin_is_decimal::INST),113 // Operator114 ("mod", builtin_mod::INST),115 ("primitiveEquals", builtin_primitive_equals::INST),116 ("equals", builtin_equals::INST),117 ("xor", builtin_xor::INST),118 ("xnor", builtin_xnor::INST),119 ("format", builtin_format::INST),120 // Sort121 ("sort", builtin_sort::INST),122 ("uniq", builtin_uniq::INST),123 ("set", builtin_set::INST),124 ("minArray", builtin_min_array::INST),125 ("maxArray", builtin_max_array::INST),126 // Hash127 ("md5", builtin_md5::INST),128 ("sha1", builtin_sha1::INST),129 ("sha256", builtin_sha256::INST),130 ("sha512", builtin_sha512::INST),131 ("sha3", builtin_sha3::INST),132 // Encoding133 ("encodeUTF8", builtin_encode_utf8::INST),134 ("decodeUTF8", builtin_decode_utf8::INST),135 ("base64", builtin_base64::INST),136 ("base64Decode", builtin_base64_decode::INST),137 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),138 // Objects139 ("objectFieldsEx", builtin_object_fields_ex::INST),140 ("objectValues", builtin_object_values::INST),141 ("objectValuesAll", builtin_object_values_all::INST),142 ("objectKeysValues", builtin_object_keys_values::INST),143 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),144 ("objectHasEx", builtin_object_has_ex::INST),145 ("objectRemoveKey", builtin_object_remove_key::INST),146 // Manifest147 ("escapeStringJson", builtin_escape_string_json::INST),148 ("manifestJsonEx", builtin_manifest_json_ex::INST),149 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),150 ("manifestTomlEx", builtin_manifest_toml_ex::INST),151 // Parsing152 ("parseJson", builtin_parse_json::INST),153 ("parseYaml", builtin_parse_yaml::INST),154 // Strings155 ("codepoint", builtin_codepoint::INST),156 ("substr", builtin_substr::INST),157 ("char", builtin_char::INST),158 ("strReplace", builtin_str_replace::INST),159 ("isEmpty", builtin_is_empty::INST),160 ("equalsIgnoreCase", builtin_equals_ignore_case::INST),161 ("splitLimit", builtin_splitlimit::INST),162 ("asciiUpper", builtin_ascii_upper::INST),163 ("asciiLower", builtin_ascii_lower::INST),164 ("findSubstr", builtin_find_substr::INST),165 ("parseInt", builtin_parse_int::INST),166 #[cfg(feature = "exp-bigint")]167 ("bigint", builtin_bigint::INST),168 ("parseOctal", builtin_parse_octal::INST),169 ("parseHex", builtin_parse_hex::INST),170 // Misc171 ("length", builtin_length::INST),172 ("startsWith", builtin_starts_with::INST),173 ("endsWith", builtin_ends_with::INST),174 // Sets175 ("setMember", builtin_set_member::INST),176 ("setInter", builtin_set_inter::INST),177 ("setDiff", builtin_set_diff::INST),178 // Compat179 ("__compare", builtin___compare::INST),180 ]181 .iter()182 .cloned()183 {184 builder.method(name, builtin);185 }186187 builder.method(188 "extVar",189 builtin_ext_var {190 settings: settings.clone(),191 },192 );193 builder.method(194 "native",195 builtin_native {196 settings: settings.clone(),197 },198 );199 builder.method("trace", builtin_trace { settings });200201 builder.method("id", FuncVal::Id);202203 builder.build()204}205206pub trait TracePrinter {207 fn print_trace(&self, loc: CallLocation, value: IStr);208}209210pub struct StdTracePrinter {211 resolver: PathResolver,212}213impl StdTracePrinter {214 pub fn new(resolver: PathResolver) -> Self {215 Self { resolver }216 }217}218impl TracePrinter for StdTracePrinter {219 fn print_trace(&self, loc: CallLocation, value: IStr) {220 eprint!("TRACE:");221 if let Some(loc) = loc.0 {222 let locs = loc.0.map_source_locations(&[loc.1]);223 eprint!(224 " {}:{}",225 match loc.0.source_path().path() {226 Some(p) => self.resolver.resolve(p),227 None => loc.0.source_path().to_string(),228 },229 locs[0].line230 );231 }232 eprintln!(" {value}");233 }234}235236pub struct Settings {237 /// Used for `std.extVar`238 pub ext_vars: HashMap<IStr, TlaArg>,239 /// Used for `std.native`240 pub ext_natives: HashMap<IStr, FuncVal>,241 /// Used for `std.trace`242 pub trace_printer: Box<dyn TracePrinter>,243 /// Used for `std.thisFile`244 pub path_resolver: PathResolver,245}246247fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {248 let source_name = format!("<extvar:{name}>");249 Source::new_virtual(source_name.into(), code.into())250}251252#[derive(Trace, Clone)]253pub struct ContextInitializer {254 /// When we don't need to support legacy-this-file, we can reuse same context for all files255 #[cfg(not(feature = "legacy-this-file"))]256 context: jrsonnet_evaluator::Context,257 /// For `populate`258 #[cfg(not(feature = "legacy-this-file"))]259 stdlib_thunk: Thunk<Val>,260 /// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it261 #[cfg(feature = "legacy-this-file")]262 stdlib_obj: ObjValue,263 settings: Rc<RefCell<Settings>>,264}265impl ContextInitializer {266 pub fn new(_s: State, resolver: PathResolver) -> Self {267 let settings = Settings {268 ext_vars: Default::default(),269 ext_natives: Default::default(),270 trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),271 path_resolver: resolver,272 };273 let settings = Rc::new(RefCell::new(settings));274 let stdlib_obj = stdlib_uncached(settings.clone());275 #[cfg(not(feature = "legacy-this-file"))]276 let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));277 Self {278 #[cfg(not(feature = "legacy-this-file"))]279 context: {280 let mut context = ContextBuilder::with_capacity(_s, 1);281 context.bind("std", stdlib_thunk.clone());282 context.build()283 },284 #[cfg(not(feature = "legacy-this-file"))]285 stdlib_thunk,286 #[cfg(feature = "legacy-this-file")]287 stdlib_obj,288 settings,289 }290 }291 pub fn settings(&self) -> Ref<Settings> {292 self.settings.borrow()293 }294 pub fn settings_mut(&self) -> RefMut<Settings> {295 self.settings.borrow_mut()296 }297 pub fn add_ext_var(&self, name: IStr, value: Val) {298 self.settings_mut()299 .ext_vars300 .insert(name, TlaArg::Val(value));301 }302 pub fn add_ext_str(&self, name: IStr, value: IStr) {303 self.settings_mut()304 .ext_vars305 .insert(name, TlaArg::String(value));306 }307 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {308 let code = code.into();309 let source = extvar_source(name, code.clone());310 let parsed = jrsonnet_parser::parse(311 &code,312 &jrsonnet_parser::ParserSettings {313 source: source.clone(),314 },315 )316 .map_err(|e| ImportSyntaxError {317 path: source,318 error: Box::new(e),319 })?;320 // self.data_mut().volatile_files.insert(source_name, code);321 self.settings_mut()322 .ext_vars323 .insert(name.into(), TlaArg::Code(parsed));324 Ok(())325 }326 pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {327 self.settings_mut()328 .ext_natives329 .insert(name.into(), cb.into());330 }331}332impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {333 fn reserve_vars(&self) -> usize {334 1335 }336 #[cfg(not(feature = "legacy-this-file"))]337 fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {338 self.context.clone()339 }340 #[cfg(not(feature = "legacy-this-file"))]341 fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {342 builder.bind("std", self.stdlib_thunk.clone());343 }344 #[cfg(feature = "legacy-this-file")]345 fn populate(&self, source: Source, builder: &mut ContextBuilder) {346 use jrsonnet_evaluator::val::StrValue;347348 let mut std = ObjValueBuilder::new();349 std.with_super(self.stdlib_obj.clone());350 std.field("thisFile".into())351 .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");357 let stdlib_with_this_file = std.build();358359 builder.bind(360 "std".into(),361 Thunk::evaluated(Val::Obj(stdlib_with_this_file)),362 );363 }364 fn as_any(&self) -> &dyn std::any::Any {365 self366 }367}368369pub trait StateExt {370 /// This method was previously implemented in jrsonnet-evaluator itself371 fn with_stdlib(&self);372}373374impl StateExt for State {375 fn with_stdlib(&self) {376 let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());377 self.settings_mut().context_initializer = tb!(initializer)378 }379}crates/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()
+}
crates/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,
crates/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))
+}
crates/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, '/');
crates/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())
+}