difftreelog
feat add std.equalsIgnoreCase
in: master
Upstream issue: https://github.com/google/go-jsonnet/pull/699
4 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -375,7 +375,9 @@
"serde",
"serde_json",
"serde_yaml_with_quirks",
+ "sha1",
"sha2",
+ "sha3",
"structdump",
]
@@ -388,6 +390,15 @@
]
[[package]]
+name = "keccak"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f6d5ed8676d904364de097082f4e7d240b571b67989ced0240f08b7f966f940"
+dependencies = [
+ "cpufeatures",
+]
+
+[[package]]
name = "libc"
version = "0.2.139"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -676,6 +687,17 @@
]
[[package]]
+name = "sha1"
+version = "0.10.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
name = "sha2"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -687,6 +709,16 @@
]
[[package]]
+name = "sha3"
+version = "0.10.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60"
+dependencies = [
+ "digest",
+ "keccak",
+]
+
+[[package]]
name = "smallvec"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
crates/jrsonnet-stdlib/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-stdlib/Cargo.toml
+++ b/crates/jrsonnet-stdlib/Cargo.toml
@@ -32,8 +32,12 @@
# std.md5
md5 = "0.7.0"
+# std.sha1
+sha1 = "0.10.5"
# std.sha256, std.sha512
sha2 = "0.10.6"
+# std.sha3
+sha3 = "0.10.8"
# std.base64
base64 = "0.21.0"
# std.parseJson
crates/jrsonnet-stdlib/src/hash.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/hash.rs
+++ b/crates/jrsonnet-stdlib/src/hash.rs
@@ -16,3 +16,15 @@
use sha2::digest::Digest;
format!("{:x}", sha2::Sha512::digest(s.as_bytes()))
}
+
+#[builtin]
+pub fn builtin_sha1(s: IStr) -> String {
+ use sha1::digest::Digest;
+ format!("{:x}", sha1::Sha1::digest(s.as_bytes()))
+}
+
+#[builtin]
+pub fn builtin_sha3(s: IStr) -> String {
+ use sha3::digest::Digest;
+ format!("{:x}", sha3::Sha3_512::digest(s.as_bytes()))
+}
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::{builtin::Builtin, CallLocation, FuncVal, TlaArg},10 gc::{GcHashMap, TraceBox},11 tb,12 trace::PathResolver,13 Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,14};15use jrsonnet_gcmodule::{Cc, Trace};16use jrsonnet_parser::Source;1718mod expr;19mod types;20pub use types::*;21mod arrays;22pub use arrays::*;23mod math;24pub use math::*;25mod operator;26pub use operator::*;27mod sort;28pub use sort::*;29mod hash;30pub use hash::*;31mod encoding;32pub use encoding::*;33mod objects;34pub use objects::*;35mod manifest;36pub use manifest::*;37mod parse;38pub use parse::*;39mod strings;40pub use strings::*;41mod misc;42pub use misc::*;43mod sets;44pub use sets::*;45mod compat;46pub use compat::*;4748pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {49 let mut builder = ObjValueBuilder::new();5051 let expr = expr::stdlib_expr();52 let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)53 .expect("stdlib.jsonnet should have no errors")54 .as_obj()55 .expect("stdlib.jsonnet should evaluate to object");5657 builder.with_super(eval);5859 for (name, builtin) in [60 // Types61 ("type", builtin_type::INST),62 ("isString", builtin_is_string::INST),63 ("isNumber", builtin_is_number::INST),64 ("isBoolean", builtin_is_boolean::INST),65 ("isObject", builtin_is_object::INST),66 ("isArray", builtin_is_array::INST),67 ("isFunction", builtin_is_function::INST),68 // Arrays69 ("makeArray", builtin_make_array::INST),70 ("repeat", builtin_repeat::INST),71 ("slice", builtin_slice::INST),72 ("map", builtin_map::INST),73 ("flatMap", builtin_flatmap::INST),74 ("filter", builtin_filter::INST),75 ("foldl", builtin_foldl::INST),76 ("foldr", builtin_foldr::INST),77 ("range", builtin_range::INST),78 ("join", builtin_join::INST),79 ("reverse", builtin_reverse::INST),80 ("any", builtin_any::INST),81 ("all", builtin_all::INST),82 ("member", builtin_member::INST),83 ("contains", builtin_member::INST),84 ("count", builtin_count::INST),85 ("avg", builtin_avg::INST),86 // Math87 ("abs", builtin_abs::INST),88 ("sign", builtin_sign::INST),89 ("max", builtin_max::INST),90 ("min", builtin_min::INST),91 ("sum", builtin_sum::INST),92 ("modulo", builtin_modulo::INST),93 ("floor", builtin_floor::INST),94 ("ceil", builtin_ceil::INST),95 ("log", builtin_log::INST),96 ("pow", builtin_pow::INST),97 ("sqrt", builtin_sqrt::INST),98 ("sin", builtin_sin::INST),99 ("cos", builtin_cos::INST),100 ("tan", builtin_tan::INST),101 ("asin", builtin_asin::INST),102 ("acos", builtin_acos::INST),103 ("atan", builtin_atan::INST),104 ("exp", builtin_exp::INST),105 ("mantissa", builtin_mantissa::INST),106 ("exponent", builtin_exponent::INST),107 ("round", builtin_round::INST),108 ("isEven", builtin_is_even::INST),109 ("isOdd", builtin_is_odd::INST),110 ("isInteger", builtin_is_integer::INST),111 ("isDecimal", builtin_is_decimal::INST),112 // Operator113 ("mod", builtin_mod::INST),114 ("primitiveEquals", builtin_primitive_equals::INST),115 ("equals", builtin_equals::INST),116 ("xor", builtin_xor::INST),117 ("xnor", builtin_xnor::INST),118 ("format", builtin_format::INST),119 // Sort120 ("sort", builtin_sort::INST),121 ("uniq", builtin_uniq::INST),122 ("set", builtin_set::INST),123 ("minArray", builtin_min_array::INST),124 ("maxArray", builtin_max_array::INST),125 // Hash126 ("md5", builtin_md5::INST),127 ("sha256", builtin_sha256::INST),128 ("sha512", builtin_sha512::INST),129 // Encoding130 ("encodeUTF8", builtin_encode_utf8::INST),131 ("decodeUTF8", builtin_decode_utf8::INST),132 ("base64", builtin_base64::INST),133 ("base64Decode", builtin_base64_decode::INST),134 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),135 // Objects136 ("objectFieldsEx", builtin_object_fields_ex::INST),137 ("objectHasEx", builtin_object_has_ex::INST),138 // Manifest139 ("escapeStringJson", builtin_escape_string_json::INST),140 ("manifestJsonEx", builtin_manifest_json_ex::INST),141 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),142 ("manifestTomlEx", builtin_manifest_toml_ex::INST),143 // Parsing144 ("parseJson", builtin_parse_json::INST),145 ("parseYaml", builtin_parse_yaml::INST),146 // Strings147 ("codepoint", builtin_codepoint::INST),148 ("substr", builtin_substr::INST),149 ("char", builtin_char::INST),150 ("strReplace", builtin_str_replace::INST),151 ("isEmpty", builtin_is_empty::INST),152 ("equalsIgnoreCase", builtin_equals_ignore_case::INST),153 ("splitLimit", builtin_splitlimit::INST),154 ("asciiUpper", builtin_ascii_upper::INST),155 ("asciiLower", builtin_ascii_lower::INST),156 ("findSubstr", builtin_find_substr::INST),157 ("parseInt", builtin_parse_int::INST),158 #[cfg(feature = "exp-bigint")]159 ("bigint", builtin_bigint::INST),160 ("parseOctal", builtin_parse_octal::INST),161 ("parseHex", builtin_parse_hex::INST),162 // Misc163 ("length", builtin_length::INST),164 ("startsWith", builtin_starts_with::INST),165 ("endsWith", builtin_ends_with::INST),166 // Sets167 ("setMember", builtin_set_member::INST),168 ("setInter", builtin_set_inter::INST),169 // Compat170 ("__compare", builtin___compare::INST),171 ]172 .iter()173 .cloned()174 {175 builder176 .member(name.into())177 .hide()178 .value(Val::Func(FuncVal::StaticBuiltin(builtin)))179 .expect("no conflict");180 }181182 builder183 .member("extVar".into())184 .hide()185 .value(Val::Func(FuncVal::builtin(builtin_ext_var {186 settings: settings.clone(),187 })))188 .expect("no conflict");189 builder190 .member("native".into())191 .hide()192 .value(Val::Func(FuncVal::builtin(builtin_native {193 settings: settings.clone(),194 })))195 .expect("no conflict");196 builder197 .member("trace".into())198 .hide()199 .value(Val::Func(FuncVal::builtin(builtin_trace { settings })))200 .expect("no conflict");201202 builder203 .member("id".into())204 .hide()205 .value(Val::Func(FuncVal::Id))206 .expect("no conflict");207208 builder.build()209}210211pub trait TracePrinter {212 fn print_trace(&self, loc: CallLocation, value: IStr);213}214215pub struct StdTracePrinter {216 resolver: PathResolver,217}218impl StdTracePrinter {219 pub fn new(resolver: PathResolver) -> Self {220 Self { resolver }221 }222}223impl TracePrinter for StdTracePrinter {224 fn print_trace(&self, loc: CallLocation, value: IStr) {225 eprint!("TRACE:");226 if let Some(loc) = loc.0 {227 let locs = loc.0.map_source_locations(&[loc.1]);228 eprint!(229 " {}:{}",230 match loc.0.source_path().path() {231 Some(p) => self.resolver.resolve(p),232 None => loc.0.source_path().to_string(),233 },234 locs[0].line235 );236 }237 eprintln!(" {value}");238 }239}240241pub struct Settings {242 /// Used for `std.extVar`243 pub ext_vars: HashMap<IStr, TlaArg>,244 /// Used for `std.native`245 pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,246 /// Helper to add globals without implementing custom ContextInitializer247 pub globals: GcHashMap<IStr, Thunk<Val>>,248 /// Used for `std.trace`249 pub trace_printer: Box<dyn TracePrinter>,250 /// Used for `std.thisFile`251 pub path_resolver: PathResolver,252}253254fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {255 let source_name = format!("<extvar:{name}>");256 Source::new_virtual(source_name.into(), code.into())257}258259#[derive(Trace, Clone)]260pub struct ContextInitializer {261 // When we don't need to support legacy-this-file, we can reuse same context for all files262 #[cfg(not(feature = "legacy-this-file"))]263 context: Context,264 // Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it265 #[cfg(feature = "legacy-this-file")]266 stdlib_obj: ObjValue,267 settings: Rc<RefCell<Settings>>,268}269impl ContextInitializer {270 pub fn new(_s: State, resolver: PathResolver) -> Self {271 let settings = Settings {272 ext_vars: Default::default(),273 ext_natives: Default::default(),274 globals: Default::default(),275 trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),276 path_resolver: resolver,277 };278 let settings = Rc::new(RefCell::new(settings));279 Self {280 #[cfg(not(feature = "legacy-this-file"))]281 context: {282 let mut context = ContextBuilder::with_capacity(_s, 1);283 context.bind(284 "std".into(),285 Thunk::evaluated(Val::Obj(stdlib_uncached(settings.clone()))),286 );287 context.build()288 },289 #[cfg(feature = "legacy-this-file")]290 stdlib_obj: stdlib_uncached(settings.clone()),291 settings,292 }293 }294 pub fn settings(&self) -> Ref<Settings> {295 self.settings.borrow()296 }297 pub fn settings_mut(&self) -> RefMut<Settings> {298 self.settings.borrow_mut()299 }300 pub fn add_ext_var(&self, name: IStr, value: Val) {301 self.settings_mut()302 .ext_vars303 .insert(name, TlaArg::Val(value));304 }305 pub fn add_ext_str(&self, name: IStr, value: IStr) {306 self.settings_mut()307 .ext_vars308 .insert(name, TlaArg::String(value));309 }310 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {311 let code = code.into();312 let source = extvar_source(name, code.clone());313 let parsed = jrsonnet_parser::parse(314 &code,315 &jrsonnet_parser::ParserSettings {316 source: source.clone(),317 },318 )319 .map_err(|e| ImportSyntaxError {320 path: source,321 error: Box::new(e),322 })?;323 // self.data_mut().volatile_files.insert(source_name, code);324 self.settings_mut()325 .ext_vars326 .insert(name.into(), TlaArg::Code(parsed));327 Ok(())328 }329 pub fn add_native(&self, name: IStr, cb: impl Builtin) {330 self.settings_mut()331 .ext_natives332 .insert(name, Cc::new(tb!(cb)));333 }334}335impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {336 #[cfg(not(feature = "legacy-this-file"))]337 fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {338 let out = self.context.clone();339 let globals = &self.settings().globals;340 if globals.is_empty() {341 return out;342 }343344 let mut out = ContextBuilder::extend(out);345 for (k, v) in globals.iter() {346 out.bind(k.clone(), v.clone());347 }348 out.build()349 }350 #[cfg(feature = "legacy-this-file")]351 fn initialize(&self, s: State, source: Source) -> Context {352 use jrsonnet_evaluator::val::StrValue;353354 let mut builder = ObjValueBuilder::new();355 builder.with_super(self.stdlib_obj.clone());356 builder357 .member("thisFile".into())358 .hide()359 .value(Val::Str(StrValue::Flat(360 match source.source_path().path() {361 Some(p) => self.settings().path_resolver.resolve(p).into(),362 None => source.source_path().to_string().into(),363 },364 )))365 .expect("this object builder is empty");366 let stdlib_with_this_file = builder.build();367368 let mut context = ContextBuilder::with_capacity(s, 1);369 context.bind(370 "std".into(),371 Thunk::evaluated(Val::Obj(stdlib_with_this_file)),372 );373 for (k, v) in self.settings().globals.iter() {374 context.bind(k.clone(), v.clone());375 }376 context.build()377 }378 fn as_any(&self) -> &dyn std::any::Any {379 self380 }381}382383pub trait StateExt {384 /// This method was previously implemented in jrsonnet-evaluator itself385 fn with_stdlib(&self);386 fn add_global(&self, name: IStr, value: Thunk<Val>);387}388389impl StateExt for State {390 fn with_stdlib(&self) {391 let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());392 self.settings_mut().context_initializer = tb!(initializer)393 }394 fn add_global(&self, name: IStr, value: Thunk<Val>) {395 self.settings()396 .context_initializer397 .as_any()398 .downcast_ref::<ContextInitializer>()399 .expect("not standard context initializer")400 .settings_mut()401 .globals402 .insert(name, value);403 }404}