difftreelog
perf move deepJoin to native
in: master
3 files changed
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -204,10 +204,31 @@
pub fn builtin_lines(arr: ArrValue) -> Result<IndexableVal> {
builtin_join(
IndexableVal::Str("\n".into()),
- ArrValue::extended(arr, ArrValue::eager(vec![Val::string("")])).into(),
+ ArrValue::extended(arr, ArrValue::eager(vec![Val::string("")])),
)
}
+pub fn deep_join_inner(out: &mut String, arr: IndexableVal) -> Result<()> {
+ use std::fmt::Write;
+ match arr {
+ IndexableVal::Str(s) => write!(out, "{s}").expect("no error"),
+ IndexableVal::Arr(arr) => {
+ for ele in arr.iter() {
+ let indexable = IndexableVal::from_untyped(ele?)?;
+ deep_join_inner(out, indexable)?;
+ }
+ }
+ }
+ Ok(())
+}
+
+#[builtin]
+pub fn builtin_deep_join(arr: IndexableVal) -> Result<String> {
+ let mut out = String::new();
+ deep_join_inner(&mut out, arr)?;
+ Ok(out)
+}
+
#[builtin]
pub fn builtin_reverse(arr: ArrValue) -> ArrValue {
arr.reversed()
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth1#![allow(clippy::similar_names)]23use std::{4 cell::{Ref, RefCell, RefMut},5 collections::HashMap,6 rc::Rc,7};89pub use arrays::*;10pub use compat::*;11pub use encoding::*;12pub use hash::*;13use jrsonnet_evaluator::{14 error::{ErrorKind::*, Result},15 function::{CallLocation, FuncVal, TlaArg},16 tb,17 trace::PathResolver,18 ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,19};20use jrsonnet_gcmodule::Trace;21use jrsonnet_parser::Source;22pub use manifest::*;23pub use math::*;24pub use misc::*;25pub use objects::*;26pub use operator::*;27pub use parse::*;28pub use sets::*;29pub use sort::*;30pub use strings::*;31pub use types::*;3233#[cfg(feature = "exp-regex")]34pub use crate::regex::*;3536mod arrays;37mod compat;38mod encoding;39mod expr;40mod hash;41mod manifest;42mod math;43mod misc;44mod objects;45mod operator;46mod parse;47#[cfg(feature = "exp-regex")]48mod regex;49mod sets;50mod sort;51mod strings;52mod types;5354#[allow(clippy::too_many_lines)]55pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {56 let mut builder = ObjValueBuilder::new();5758 let expr = expr::stdlib_expr();59 let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)60 .expect("stdlib.jsonnet should have no errors")61 .as_obj()62 .expect("stdlib.jsonnet should evaluate to object");6364 builder.with_super(eval);6566 // FIXME: Use PHF67 for (name, builtin) in [68 // Types69 ("type", builtin_type::INST),70 ("isString", builtin_is_string::INST),71 ("isNumber", builtin_is_number::INST),72 ("isBoolean", builtin_is_boolean::INST),73 ("isObject", builtin_is_object::INST),74 ("isArray", builtin_is_array::INST),75 ("isFunction", builtin_is_function::INST),76 // Arrays77 ("makeArray", builtin_make_array::INST),78 ("repeat", builtin_repeat::INST),79 ("slice", builtin_slice::INST),80 ("map", builtin_map::INST),81 ("mapWithIndex", builtin_map_with_index::INST),82 ("flatMap", builtin_flatmap::INST),83 ("filter", builtin_filter::INST),84 ("foldl", builtin_foldl::INST),85 ("foldr", builtin_foldr::INST),86 ("range", builtin_range::INST),87 ("join", builtin_join::INST),88 ("lines", builtin_lines::INST),89 ("reverse", builtin_reverse::INST),90 ("any", builtin_any::INST),91 ("all", builtin_all::INST),92 ("member", builtin_member::INST),93 ("contains", builtin_contains::INST),94 ("count", builtin_count::INST),95 ("avg", builtin_avg::INST),96 ("removeAt", builtin_remove_at::INST),97 ("remove", builtin_remove::INST),98 ("flattenArrays", builtin_flatten_arrays::INST),99 ("flattenDeepArray", builtin_flatten_deep_array::INST),100 ("prune", builtin_prune::INST),101 ("filterMap", builtin_filter_map::INST),102 // Math103 ("abs", builtin_abs::INST),104 ("sign", builtin_sign::INST),105 ("max", builtin_max::INST),106 ("min", builtin_min::INST),107 ("clamp", builtin_clamp::INST),108 ("sum", builtin_sum::INST),109 ("modulo", builtin_modulo::INST),110 ("floor", builtin_floor::INST),111 ("ceil", builtin_ceil::INST),112 ("log", builtin_log::INST),113 ("pow", builtin_pow::INST),114 ("sqrt", builtin_sqrt::INST),115 ("sin", builtin_sin::INST),116 ("cos", builtin_cos::INST),117 ("tan", builtin_tan::INST),118 ("asin", builtin_asin::INST),119 ("acos", builtin_acos::INST),120 ("atan", builtin_atan::INST),121 ("atan2", builtin_atan2::INST),122 ("exp", builtin_exp::INST),123 ("mantissa", builtin_mantissa::INST),124 ("exponent", builtin_exponent::INST),125 ("round", builtin_round::INST),126 ("isEven", builtin_is_even::INST),127 ("isOdd", builtin_is_odd::INST),128 ("isInteger", builtin_is_integer::INST),129 ("isDecimal", builtin_is_decimal::INST),130 // Operator131 ("mod", builtin_mod::INST),132 ("primitiveEquals", builtin_primitive_equals::INST),133 ("equals", builtin_equals::INST),134 ("xor", builtin_xor::INST),135 ("xnor", builtin_xnor::INST),136 ("format", builtin_format::INST),137 // Sort138 ("sort", builtin_sort::INST),139 ("uniq", builtin_uniq::INST),140 ("set", builtin_set::INST),141 ("minArray", builtin_min_array::INST),142 ("maxArray", builtin_max_array::INST),143 // Hash144 ("md5", builtin_md5::INST),145 ("sha1", builtin_sha1::INST),146 ("sha256", builtin_sha256::INST),147 ("sha512", builtin_sha512::INST),148 ("sha3", builtin_sha3::INST),149 // Encoding150 ("encodeUTF8", builtin_encode_utf8::INST),151 ("decodeUTF8", builtin_decode_utf8::INST),152 ("base64", builtin_base64::INST),153 ("base64Decode", builtin_base64_decode::INST),154 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),155 // Objects156 ("objectFieldsEx", builtin_object_fields_ex::INST),157 ("objectFields", builtin_object_fields::INST),158 ("objectFieldsAll", builtin_object_fields_all::INST),159 ("objectValues", builtin_object_values::INST),160 ("objectValuesAll", builtin_object_values_all::INST),161 ("objectKeysValues", builtin_object_keys_values::INST),162 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),163 ("objectHasEx", builtin_object_has_ex::INST),164 ("objectHas", builtin_object_has::INST),165 ("objectHasAll", builtin_object_has_all::INST),166 ("objectRemoveKey", builtin_object_remove_key::INST),167 // Manifest168 ("escapeStringJson", builtin_escape_string_json::INST),169 ("escapeStringPython", builtin_escape_string_python::INST),170 ("escapeStringXML", builtin_escape_string_xml::INST),171 ("manifestJsonEx", builtin_manifest_json_ex::INST),172 ("manifestJson", builtin_manifest_json::INST),173 ("manifestJsonMinified", builtin_manifest_json_minified::INST),174 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),175 ("manifestYamlStream", builtin_manifest_yaml_stream::INST),176 ("manifestTomlEx", builtin_manifest_toml_ex::INST),177 ("manifestToml", builtin_manifest_toml::INST),178 ("toString", builtin_to_string::INST),179 ("manifestPython", builtin_manifest_python::INST),180 ("manifestPythonVars", builtin_manifest_python_vars::INST),181 ("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),182 ("manifestIni", builtin_manifest_ini::INST),183 // Parse184 ("parseJson", builtin_parse_json::INST),185 ("parseYaml", builtin_parse_yaml::INST),186 // Strings187 ("codepoint", builtin_codepoint::INST),188 ("substr", builtin_substr::INST),189 ("char", builtin_char::INST),190 ("strReplace", builtin_str_replace::INST),191 ("escapeStringBash", builtin_escape_string_bash::INST),192 ("escapeStringDollars", builtin_escape_string_dollars::INST),193 ("isEmpty", builtin_is_empty::INST),194 ("equalsIgnoreCase", builtin_equals_ignore_case::INST),195 ("splitLimit", builtin_splitlimit::INST),196 ("splitLimitR", builtin_splitlimitr::INST),197 ("split", builtin_split::INST),198 ("asciiUpper", builtin_ascii_upper::INST),199 ("asciiLower", builtin_ascii_lower::INST),200 ("findSubstr", builtin_find_substr::INST),201 ("parseInt", builtin_parse_int::INST),202 #[cfg(feature = "exp-bigint")]203 ("bigint", builtin_bigint::INST),204 ("parseOctal", builtin_parse_octal::INST),205 ("parseHex", builtin_parse_hex::INST),206 ("stringChars", builtin_string_chars::INST),207 ("lstripChars", builtin_lstrip_chars::INST),208 ("rstripChars", builtin_rstrip_chars::INST),209 ("stripChars", builtin_strip_chars::INST),210 // Misc211 ("length", builtin_length::INST),212 ("get", builtin_get::INST),213 ("startsWith", builtin_starts_with::INST),214 ("endsWith", builtin_ends_with::INST),215 // Sets216 ("setMember", builtin_set_member::INST),217 ("setInter", builtin_set_inter::INST),218 ("setDiff", builtin_set_diff::INST),219 ("setUnion", builtin_set_union::INST),220 // Regex221 #[cfg(feature = "exp-regex")]222 ("regexQuoteMeta", builtin_regex_quote_meta::INST),223 // Compat224 ("__compare", builtin___compare::INST),225 ("__compare_array", builtin___compare_array::INST),226 ("__array_less", builtin___array_less::INST),227 ("__array_greater", builtin___array_greater::INST),228 ("__array_less_or_equal", builtin___array_less_or_equal::INST),229 (230 "__array_greater_or_equal",231 builtin___array_greater_or_equal::INST,232 ),233 ]234 .iter()235 .copied()236 {237 builder.method(name, builtin);238 }239240 builder.method(241 "extVar",242 builtin_ext_var {243 settings: settings.clone(),244 },245 );246 builder.method(247 "native",248 builtin_native {249 settings: settings.clone(),250 },251 );252 builder.method("trace", builtin_trace { settings });253 builder.method("id", FuncVal::Id);254255 #[cfg(feature = "exp-regex")]256 {257 // Regex258 let regex_cache = RegexCache::default();259 builder.method(260 "regexFullMatch",261 builtin_regex_full_match {262 cache: regex_cache.clone(),263 },264 );265 builder.method(266 "regexPartialMatch",267 builtin_regex_partial_match {268 cache: regex_cache.clone(),269 },270 );271 builder.method(272 "regexReplace",273 builtin_regex_replace {274 cache: regex_cache.clone(),275 },276 );277 builder.method(278 "regexGlobalReplace",279 builtin_regex_global_replace { cache: regex_cache },280 );281 };282283 builder.build()284}285286pub trait TracePrinter {287 fn print_trace(&self, loc: CallLocation, value: IStr);288}289290pub struct StdTracePrinter {291 resolver: PathResolver,292}293impl StdTracePrinter {294 pub fn new(resolver: PathResolver) -> Self {295 Self { resolver }296 }297}298impl TracePrinter for StdTracePrinter {299 fn print_trace(&self, loc: CallLocation, value: IStr) {300 eprint!("TRACE:");301 if let Some(loc) = loc.0 {302 let locs = loc.0.map_source_locations(&[loc.1]);303 eprint!(304 " {}:{}",305 loc.0.source_path().path().map_or_else(306 || loc.0.source_path().to_string(),307 |p| self.resolver.resolve(p)308 ),309 locs[0].line310 );311 }312 eprintln!(" {value}");313 }314}315316pub struct Settings {317 /// Used for `std.extVar`318 pub ext_vars: HashMap<IStr, TlaArg>,319 /// Used for `std.native`320 pub ext_natives: HashMap<IStr, FuncVal>,321 /// Used for `std.trace`322 pub trace_printer: Box<dyn TracePrinter>,323 /// Used for `std.thisFile`324 pub path_resolver: PathResolver,325}326327fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {328 let source_name = format!("<extvar:{name}>");329 Source::new_virtual(source_name.into(), code.into())330}331332#[derive(Trace, Clone)]333pub struct ContextInitializer {334 /// When we don't need to support legacy-this-file, we can reuse same context for all files335 #[cfg(not(feature = "legacy-this-file"))]336 context: jrsonnet_evaluator::Context,337 /// For `populate`338 #[cfg(not(feature = "legacy-this-file"))]339 stdlib_thunk: Thunk<Val>,340 /// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it341 #[cfg(feature = "legacy-this-file")]342 stdlib_obj: ObjValue,343 settings: Rc<RefCell<Settings>>,344}345impl ContextInitializer {346 pub fn new(s: State, resolver: PathResolver) -> Self {347 let settings = Settings {348 ext_vars: HashMap::new(),349 ext_natives: HashMap::new(),350 trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),351 path_resolver: resolver,352 };353 let settings = Rc::new(RefCell::new(settings));354 let stdlib_obj = stdlib_uncached(settings.clone());355 #[cfg(not(feature = "legacy-this-file"))]356 let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));357 #[cfg(feature = "legacy-this-file")]358 let _ = s;359 Self {360 #[cfg(not(feature = "legacy-this-file"))]361 context: {362 let mut context = ContextBuilder::with_capacity(s, 1);363 context.bind("std", stdlib_thunk.clone());364 context.build()365 },366 #[cfg(not(feature = "legacy-this-file"))]367 stdlib_thunk,368 #[cfg(feature = "legacy-this-file")]369 stdlib_obj,370 settings,371 }372 }373 pub fn settings(&self) -> Ref<Settings> {374 self.settings.borrow()375 }376 pub fn settings_mut(&self) -> RefMut<Settings> {377 self.settings.borrow_mut()378 }379 pub fn add_ext_var(&self, name: IStr, value: Val) {380 self.settings_mut()381 .ext_vars382 .insert(name, TlaArg::Val(value));383 }384 pub fn add_ext_str(&self, name: IStr, value: IStr) {385 self.settings_mut()386 .ext_vars387 .insert(name, TlaArg::String(value));388 }389 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {390 let code = code.into();391 let source = extvar_source(name, code.clone());392 let parsed = jrsonnet_parser::parse(393 &code,394 &jrsonnet_parser::ParserSettings {395 source: source.clone(),396 },397 )398 .map_err(|e| ImportSyntaxError {399 path: source,400 error: Box::new(e),401 })?;402 // self.data_mut().volatile_files.insert(source_name, code);403 self.settings_mut()404 .ext_vars405 .insert(name.into(), TlaArg::Code(parsed));406 Ok(())407 }408 pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {409 self.settings_mut()410 .ext_natives411 .insert(name.into(), cb.into());412 }413}414impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {415 fn reserve_vars(&self) -> usize {416 1417 }418 #[cfg(not(feature = "legacy-this-file"))]419 fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {420 self.context.clone()421 }422 #[cfg(not(feature = "legacy-this-file"))]423 fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {424 builder.bind("std", self.stdlib_thunk.clone());425 }426 #[cfg(feature = "legacy-this-file")]427 fn populate(&self, source: Source, builder: &mut ContextBuilder) {428 let mut std = ObjValueBuilder::new();429 std.with_super(self.stdlib_obj.clone());430 std.field("thisFile").hide().value({431 let source_path = source.source_path();432 source_path.path().map_or_else(433 || source_path.to_string(),434 |p| self.settings().path_resolver.resolve(p),435 )436 });437 let stdlib_with_this_file = std.build();438439 builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));440 }441 fn as_any(&self) -> &dyn std::any::Any {442 self443 }444}445446pub trait StateExt {447 /// This method was previously implemented in jrsonnet-evaluator itself448 fn with_stdlib(&self);449}450451impl StateExt for State {452 fn with_stdlib(&self) {453 let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());454 self.settings_mut().context_initializer = tb!(initializer);455 }456}1#![allow(clippy::similar_names)]23use std::{4 cell::{Ref, RefCell, RefMut},5 collections::HashMap,6 rc::Rc,7};89pub use arrays::*;10pub use compat::*;11pub use encoding::*;12pub use hash::*;13use jrsonnet_evaluator::{14 error::{ErrorKind::*, Result},15 function::{CallLocation, FuncVal, TlaArg},16 tb,17 trace::PathResolver,18 ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,19};20use jrsonnet_gcmodule::Trace;21use jrsonnet_parser::Source;22pub use manifest::*;23pub use math::*;24pub use misc::*;25pub use objects::*;26pub use operator::*;27pub use parse::*;28pub use sets::*;29pub use sort::*;30pub use strings::*;31pub use types::*;3233#[cfg(feature = "exp-regex")]34pub use crate::regex::*;3536mod arrays;37mod compat;38mod encoding;39mod expr;40mod hash;41mod manifest;42mod math;43mod misc;44mod objects;45mod operator;46mod parse;47#[cfg(feature = "exp-regex")]48mod regex;49mod sets;50mod sort;51mod strings;52mod types;5354#[allow(clippy::too_many_lines)]55pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {56 let mut builder = ObjValueBuilder::new();5758 let expr = expr::stdlib_expr();59 let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)60 .expect("stdlib.jsonnet should have no errors")61 .as_obj()62 .expect("stdlib.jsonnet should evaluate to object");6364 builder.with_super(eval);6566 // FIXME: Use PHF67 for (name, builtin) in [68 // Types69 ("type", builtin_type::INST),70 ("isString", builtin_is_string::INST),71 ("isNumber", builtin_is_number::INST),72 ("isBoolean", builtin_is_boolean::INST),73 ("isObject", builtin_is_object::INST),74 ("isArray", builtin_is_array::INST),75 ("isFunction", builtin_is_function::INST),76 // Arrays77 ("makeArray", builtin_make_array::INST),78 ("repeat", builtin_repeat::INST),79 ("slice", builtin_slice::INST),80 ("map", builtin_map::INST),81 ("mapWithIndex", builtin_map_with_index::INST),82 ("flatMap", builtin_flatmap::INST),83 ("filter", builtin_filter::INST),84 ("foldl", builtin_foldl::INST),85 ("foldr", builtin_foldr::INST),86 ("range", builtin_range::INST),87 ("join", builtin_join::INST),88 ("lines", builtin_lines::INST),89 ("deepJoin", builtin_deep_join::INST),90 ("reverse", builtin_reverse::INST),91 ("any", builtin_any::INST),92 ("all", builtin_all::INST),93 ("member", builtin_member::INST),94 ("contains", builtin_contains::INST),95 ("count", builtin_count::INST),96 ("avg", builtin_avg::INST),97 ("removeAt", builtin_remove_at::INST),98 ("remove", builtin_remove::INST),99 ("flattenArrays", builtin_flatten_arrays::INST),100 ("flattenDeepArray", builtin_flatten_deep_array::INST),101 ("prune", builtin_prune::INST),102 ("filterMap", builtin_filter_map::INST),103 // Math104 ("abs", builtin_abs::INST),105 ("sign", builtin_sign::INST),106 ("max", builtin_max::INST),107 ("min", builtin_min::INST),108 ("clamp", builtin_clamp::INST),109 ("sum", builtin_sum::INST),110 ("modulo", builtin_modulo::INST),111 ("floor", builtin_floor::INST),112 ("ceil", builtin_ceil::INST),113 ("log", builtin_log::INST),114 ("pow", builtin_pow::INST),115 ("sqrt", builtin_sqrt::INST),116 ("sin", builtin_sin::INST),117 ("cos", builtin_cos::INST),118 ("tan", builtin_tan::INST),119 ("asin", builtin_asin::INST),120 ("acos", builtin_acos::INST),121 ("atan", builtin_atan::INST),122 ("atan2", builtin_atan2::INST),123 ("exp", builtin_exp::INST),124 ("mantissa", builtin_mantissa::INST),125 ("exponent", builtin_exponent::INST),126 ("round", builtin_round::INST),127 ("isEven", builtin_is_even::INST),128 ("isOdd", builtin_is_odd::INST),129 ("isInteger", builtin_is_integer::INST),130 ("isDecimal", builtin_is_decimal::INST),131 // Operator132 ("mod", builtin_mod::INST),133 ("primitiveEquals", builtin_primitive_equals::INST),134 ("equals", builtin_equals::INST),135 ("xor", builtin_xor::INST),136 ("xnor", builtin_xnor::INST),137 ("format", builtin_format::INST),138 // Sort139 ("sort", builtin_sort::INST),140 ("uniq", builtin_uniq::INST),141 ("set", builtin_set::INST),142 ("minArray", builtin_min_array::INST),143 ("maxArray", builtin_max_array::INST),144 // Hash145 ("md5", builtin_md5::INST),146 ("sha1", builtin_sha1::INST),147 ("sha256", builtin_sha256::INST),148 ("sha512", builtin_sha512::INST),149 ("sha3", builtin_sha3::INST),150 // Encoding151 ("encodeUTF8", builtin_encode_utf8::INST),152 ("decodeUTF8", builtin_decode_utf8::INST),153 ("base64", builtin_base64::INST),154 ("base64Decode", builtin_base64_decode::INST),155 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),156 // Objects157 ("objectFieldsEx", builtin_object_fields_ex::INST),158 ("objectFields", builtin_object_fields::INST),159 ("objectFieldsAll", builtin_object_fields_all::INST),160 ("objectValues", builtin_object_values::INST),161 ("objectValuesAll", builtin_object_values_all::INST),162 ("objectKeysValues", builtin_object_keys_values::INST),163 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),164 ("objectHasEx", builtin_object_has_ex::INST),165 ("objectHas", builtin_object_has::INST),166 ("objectHasAll", builtin_object_has_all::INST),167 ("objectRemoveKey", builtin_object_remove_key::INST),168 // Manifest169 ("escapeStringJson", builtin_escape_string_json::INST),170 ("escapeStringPython", builtin_escape_string_python::INST),171 ("escapeStringXML", builtin_escape_string_xml::INST),172 ("manifestJsonEx", builtin_manifest_json_ex::INST),173 ("manifestJson", builtin_manifest_json::INST),174 ("manifestJsonMinified", builtin_manifest_json_minified::INST),175 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),176 ("manifestYamlStream", builtin_manifest_yaml_stream::INST),177 ("manifestTomlEx", builtin_manifest_toml_ex::INST),178 ("manifestToml", builtin_manifest_toml::INST),179 ("toString", builtin_to_string::INST),180 ("manifestPython", builtin_manifest_python::INST),181 ("manifestPythonVars", builtin_manifest_python_vars::INST),182 ("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),183 ("manifestIni", builtin_manifest_ini::INST),184 // Parse185 ("parseJson", builtin_parse_json::INST),186 ("parseYaml", builtin_parse_yaml::INST),187 // Strings188 ("codepoint", builtin_codepoint::INST),189 ("substr", builtin_substr::INST),190 ("char", builtin_char::INST),191 ("strReplace", builtin_str_replace::INST),192 ("escapeStringBash", builtin_escape_string_bash::INST),193 ("escapeStringDollars", builtin_escape_string_dollars::INST),194 ("isEmpty", builtin_is_empty::INST),195 ("equalsIgnoreCase", builtin_equals_ignore_case::INST),196 ("splitLimit", builtin_splitlimit::INST),197 ("splitLimitR", builtin_splitlimitr::INST),198 ("split", builtin_split::INST),199 ("asciiUpper", builtin_ascii_upper::INST),200 ("asciiLower", builtin_ascii_lower::INST),201 ("findSubstr", builtin_find_substr::INST),202 ("parseInt", builtin_parse_int::INST),203 #[cfg(feature = "exp-bigint")]204 ("bigint", builtin_bigint::INST),205 ("parseOctal", builtin_parse_octal::INST),206 ("parseHex", builtin_parse_hex::INST),207 ("stringChars", builtin_string_chars::INST),208 ("lstripChars", builtin_lstrip_chars::INST),209 ("rstripChars", builtin_rstrip_chars::INST),210 ("stripChars", builtin_strip_chars::INST),211 // Misc212 ("length", builtin_length::INST),213 ("get", builtin_get::INST),214 ("startsWith", builtin_starts_with::INST),215 ("endsWith", builtin_ends_with::INST),216 // Sets217 ("setMember", builtin_set_member::INST),218 ("setInter", builtin_set_inter::INST),219 ("setDiff", builtin_set_diff::INST),220 ("setUnion", builtin_set_union::INST),221 // Regex222 #[cfg(feature = "exp-regex")]223 ("regexQuoteMeta", builtin_regex_quote_meta::INST),224 // Compat225 ("__compare", builtin___compare::INST),226 ("__compare_array", builtin___compare_array::INST),227 ("__array_less", builtin___array_less::INST),228 ("__array_greater", builtin___array_greater::INST),229 ("__array_less_or_equal", builtin___array_less_or_equal::INST),230 (231 "__array_greater_or_equal",232 builtin___array_greater_or_equal::INST,233 ),234 ]235 .iter()236 .copied()237 {238 builder.method(name, builtin);239 }240241 builder.method(242 "extVar",243 builtin_ext_var {244 settings: settings.clone(),245 },246 );247 builder.method(248 "native",249 builtin_native {250 settings: settings.clone(),251 },252 );253 builder.method("trace", builtin_trace { settings });254 builder.method("id", FuncVal::Id);255256 #[cfg(feature = "exp-regex")]257 {258 // Regex259 let regex_cache = RegexCache::default();260 builder.method(261 "regexFullMatch",262 builtin_regex_full_match {263 cache: regex_cache.clone(),264 },265 );266 builder.method(267 "regexPartialMatch",268 builtin_regex_partial_match {269 cache: regex_cache.clone(),270 },271 );272 builder.method(273 "regexReplace",274 builtin_regex_replace {275 cache: regex_cache.clone(),276 },277 );278 builder.method(279 "regexGlobalReplace",280 builtin_regex_global_replace { cache: regex_cache },281 );282 };283284 builder.build()285}286287pub trait TracePrinter {288 fn print_trace(&self, loc: CallLocation, value: IStr);289}290291pub struct StdTracePrinter {292 resolver: PathResolver,293}294impl StdTracePrinter {295 pub fn new(resolver: PathResolver) -> Self {296 Self { resolver }297 }298}299impl TracePrinter for StdTracePrinter {300 fn print_trace(&self, loc: CallLocation, value: IStr) {301 eprint!("TRACE:");302 if let Some(loc) = loc.0 {303 let locs = loc.0.map_source_locations(&[loc.1]);304 eprint!(305 " {}:{}",306 loc.0.source_path().path().map_or_else(307 || loc.0.source_path().to_string(),308 |p| self.resolver.resolve(p)309 ),310 locs[0].line311 );312 }313 eprintln!(" {value}");314 }315}316317pub struct Settings {318 /// Used for `std.extVar`319 pub ext_vars: HashMap<IStr, TlaArg>,320 /// Used for `std.native`321 pub ext_natives: HashMap<IStr, FuncVal>,322 /// Used for `std.trace`323 pub trace_printer: Box<dyn TracePrinter>,324 /// Used for `std.thisFile`325 pub path_resolver: PathResolver,326}327328fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {329 let source_name = format!("<extvar:{name}>");330 Source::new_virtual(source_name.into(), code.into())331}332333#[derive(Trace, Clone)]334pub struct ContextInitializer {335 /// When we don't need to support legacy-this-file, we can reuse same context for all files336 #[cfg(not(feature = "legacy-this-file"))]337 context: jrsonnet_evaluator::Context,338 /// For `populate`339 #[cfg(not(feature = "legacy-this-file"))]340 stdlib_thunk: Thunk<Val>,341 /// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it342 #[cfg(feature = "legacy-this-file")]343 stdlib_obj: ObjValue,344 settings: Rc<RefCell<Settings>>,345}346impl ContextInitializer {347 pub fn new(s: State, resolver: PathResolver) -> Self {348 let settings = Settings {349 ext_vars: HashMap::new(),350 ext_natives: HashMap::new(),351 trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),352 path_resolver: resolver,353 };354 let settings = Rc::new(RefCell::new(settings));355 let stdlib_obj = stdlib_uncached(settings.clone());356 #[cfg(not(feature = "legacy-this-file"))]357 let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));358 #[cfg(feature = "legacy-this-file")]359 let _ = s;360 Self {361 #[cfg(not(feature = "legacy-this-file"))]362 context: {363 let mut context = ContextBuilder::with_capacity(s, 1);364 context.bind("std", stdlib_thunk.clone());365 context.build()366 },367 #[cfg(not(feature = "legacy-this-file"))]368 stdlib_thunk,369 #[cfg(feature = "legacy-this-file")]370 stdlib_obj,371 settings,372 }373 }374 pub fn settings(&self) -> Ref<Settings> {375 self.settings.borrow()376 }377 pub fn settings_mut(&self) -> RefMut<Settings> {378 self.settings.borrow_mut()379 }380 pub fn add_ext_var(&self, name: IStr, value: Val) {381 self.settings_mut()382 .ext_vars383 .insert(name, TlaArg::Val(value));384 }385 pub fn add_ext_str(&self, name: IStr, value: IStr) {386 self.settings_mut()387 .ext_vars388 .insert(name, TlaArg::String(value));389 }390 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {391 let code = code.into();392 let source = extvar_source(name, code.clone());393 let parsed = jrsonnet_parser::parse(394 &code,395 &jrsonnet_parser::ParserSettings {396 source: source.clone(),397 },398 )399 .map_err(|e| ImportSyntaxError {400 path: source,401 error: Box::new(e),402 })?;403 // self.data_mut().volatile_files.insert(source_name, code);404 self.settings_mut()405 .ext_vars406 .insert(name.into(), TlaArg::Code(parsed));407 Ok(())408 }409 pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {410 self.settings_mut()411 .ext_natives412 .insert(name.into(), cb.into());413 }414}415impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {416 fn reserve_vars(&self) -> usize {417 1418 }419 #[cfg(not(feature = "legacy-this-file"))]420 fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {421 self.context.clone()422 }423 #[cfg(not(feature = "legacy-this-file"))]424 fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {425 builder.bind("std", self.stdlib_thunk.clone());426 }427 #[cfg(feature = "legacy-this-file")]428 fn populate(&self, source: Source, builder: &mut ContextBuilder) {429 let mut std = ObjValueBuilder::new();430 std.with_super(self.stdlib_obj.clone());431 std.field("thisFile").hide().value({432 let source_path = source.source_path();433 source_path.path().map_or_else(434 || source_path.to_string(),435 |p| self.settings().path_resolver.resolve(p),436 )437 });438 let stdlib_with_this_file = std.build();439440 builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));441 }442 fn as_any(&self) -> &dyn std::any::Any {443 self444 }445}446447pub trait StateExt {448 /// This method was previously implemented in jrsonnet-evaluator itself449 fn with_stdlib(&self);450}451452impl StateExt for State {453 fn with_stdlib(&self) {454 let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());455 self.settings_mut().context_initializer = tb!(initializer);456 }457}crates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/std.jsonnet
+++ b/crates/jrsonnet-stdlib/src/std.jsonnet
@@ -11,14 +11,6 @@
else
{ [k]: func(k, obj[k]) for k in std.objectFields(obj) },
- deepJoin(arr)::
- if std.isString(arr) then
- arr
- else if std.isArray(arr) then
- std.join('', [std.deepJoin(x) for x in arr])
- else
- error 'Expected string or array, got %s' % std.type(arr),
-
assertEqual(a, b)::
if a == b then
true