git.delta.rocks / jrsonnet / refs/commits / aee64ce2020d

difftreelog

feat add std.equalsIgnoreCase

Paweł Bęza2023-07-11parent: #e2787ae.patch.diff
in: master
Upstream issue: https://github.com/google/go-jsonnet/pull/699

4 files changed

modifiedCargo.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"
modifiedcrates/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
modifiedcrates/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()))
+}
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
after · crates/jrsonnet-stdlib/src/lib.rs
1use 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		("sha1", builtin_sha1::INST),128		("sha256", builtin_sha256::INST),129		("sha512", builtin_sha512::INST),130		("sha3", builtin_sha3::INST),131		// Encoding132		("encodeUTF8", builtin_encode_utf8::INST),133		("decodeUTF8", builtin_decode_utf8::INST),134		("base64", builtin_base64::INST),135		("base64Decode", builtin_base64_decode::INST),136		("base64DecodeBytes", builtin_base64_decode_bytes::INST),137		// Objects138		("objectFieldsEx", builtin_object_fields_ex::INST),139		("objectHasEx", builtin_object_has_ex::INST),140		// Manifest141		("escapeStringJson", builtin_escape_string_json::INST),142		("manifestJsonEx", builtin_manifest_json_ex::INST),143		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),144		("manifestTomlEx", builtin_manifest_toml_ex::INST),145		// Parsing146		("parseJson", builtin_parse_json::INST),147		("parseYaml", builtin_parse_yaml::INST),148		// Strings149		("codepoint", builtin_codepoint::INST),150		("substr", builtin_substr::INST),151		("char", builtin_char::INST),152		("strReplace", builtin_str_replace::INST),153		("isEmpty", builtin_is_empty::INST),154		("equalsIgnoreCase", builtin_equals_ignore_case::INST),155		("splitLimit", builtin_splitlimit::INST),156		("asciiUpper", builtin_ascii_upper::INST),157		("asciiLower", builtin_ascii_lower::INST),158		("findSubstr", builtin_find_substr::INST),159		("parseInt", builtin_parse_int::INST),160		#[cfg(feature = "exp-bigint")]161		("bigint", builtin_bigint::INST),162		("parseOctal", builtin_parse_octal::INST),163		("parseHex", builtin_parse_hex::INST),164		// Misc165		("length", builtin_length::INST),166		("startsWith", builtin_starts_with::INST),167		("endsWith", builtin_ends_with::INST),168		// Sets169		("setMember", builtin_set_member::INST),170		("setInter", builtin_set_inter::INST),171		// Compat172		("__compare", builtin___compare::INST),173	]174	.iter()175	.cloned()176	{177		builder178			.member(name.into())179			.hide()180			.value(Val::Func(FuncVal::StaticBuiltin(builtin)))181			.expect("no conflict");182	}183184	builder185		.member("extVar".into())186		.hide()187		.value(Val::Func(FuncVal::builtin(builtin_ext_var {188			settings: settings.clone(),189		})))190		.expect("no conflict");191	builder192		.member("native".into())193		.hide()194		.value(Val::Func(FuncVal::builtin(builtin_native {195			settings: settings.clone(),196		})))197		.expect("no conflict");198	builder199		.member("trace".into())200		.hide()201		.value(Val::Func(FuncVal::builtin(builtin_trace { settings })))202		.expect("no conflict");203204	builder205		.member("id".into())206		.hide()207		.value(Val::Func(FuncVal::Id))208		.expect("no conflict");209210	builder.build()211}212213pub trait TracePrinter {214	fn print_trace(&self, loc: CallLocation, value: IStr);215}216217pub struct StdTracePrinter {218	resolver: PathResolver,219}220impl StdTracePrinter {221	pub fn new(resolver: PathResolver) -> Self {222		Self { resolver }223	}224}225impl TracePrinter for StdTracePrinter {226	fn print_trace(&self, loc: CallLocation, value: IStr) {227		eprint!("TRACE:");228		if let Some(loc) = loc.0 {229			let locs = loc.0.map_source_locations(&[loc.1]);230			eprint!(231				" {}:{}",232				match loc.0.source_path().path() {233					Some(p) => self.resolver.resolve(p),234					None => loc.0.source_path().to_string(),235				},236				locs[0].line237			);238		}239		eprintln!(" {value}");240	}241}242243pub struct Settings {244	/// Used for `std.extVar`245	pub ext_vars: HashMap<IStr, TlaArg>,246	/// Used for `std.native`247	pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,248	/// Helper to add globals without implementing custom ContextInitializer249	pub globals: GcHashMap<IStr, Thunk<Val>>,250	/// Used for `std.trace`251	pub trace_printer: Box<dyn TracePrinter>,252	/// Used for `std.thisFile`253	pub path_resolver: PathResolver,254}255256fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {257	let source_name = format!("<extvar:{name}>");258	Source::new_virtual(source_name.into(), code.into())259}260261#[derive(Trace, Clone)]262pub struct ContextInitializer {263	// When we don't need to support legacy-this-file, we can reuse same context for all files264	#[cfg(not(feature = "legacy-this-file"))]265	context: Context,266	// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it267	#[cfg(feature = "legacy-this-file")]268	stdlib_obj: ObjValue,269	settings: Rc<RefCell<Settings>>,270}271impl ContextInitializer {272	pub fn new(_s: State, resolver: PathResolver) -> Self {273		let settings = Settings {274			ext_vars: Default::default(),275			ext_natives: Default::default(),276			globals: Default::default(),277			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),278			path_resolver: resolver,279		};280		let settings = Rc::new(RefCell::new(settings));281		Self {282			#[cfg(not(feature = "legacy-this-file"))]283			context: {284				let mut context = ContextBuilder::with_capacity(_s, 1);285				context.bind(286					"std".into(),287					Thunk::evaluated(Val::Obj(stdlib_uncached(settings.clone()))),288				);289				context.build()290			},291			#[cfg(feature = "legacy-this-file")]292			stdlib_obj: stdlib_uncached(settings.clone()),293			settings,294		}295	}296	pub fn settings(&self) -> Ref<Settings> {297		self.settings.borrow()298	}299	pub fn settings_mut(&self) -> RefMut<Settings> {300		self.settings.borrow_mut()301	}302	pub fn add_ext_var(&self, name: IStr, value: Val) {303		self.settings_mut()304			.ext_vars305			.insert(name, TlaArg::Val(value));306	}307	pub fn add_ext_str(&self, name: IStr, value: IStr) {308		self.settings_mut()309			.ext_vars310			.insert(name, TlaArg::String(value));311	}312	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {313		let code = code.into();314		let source = extvar_source(name, code.clone());315		let parsed = jrsonnet_parser::parse(316			&code,317			&jrsonnet_parser::ParserSettings {318				source: source.clone(),319			},320		)321		.map_err(|e| ImportSyntaxError {322			path: source,323			error: Box::new(e),324		})?;325		// self.data_mut().volatile_files.insert(source_name, code);326		self.settings_mut()327			.ext_vars328			.insert(name.into(), TlaArg::Code(parsed));329		Ok(())330	}331	pub fn add_native(&self, name: IStr, cb: impl Builtin) {332		self.settings_mut()333			.ext_natives334			.insert(name, Cc::new(tb!(cb)));335	}336}337impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {338	#[cfg(not(feature = "legacy-this-file"))]339	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {340		let out = self.context.clone();341		let globals = &self.settings().globals;342		if globals.is_empty() {343			return out;344		}345346		let mut out = ContextBuilder::extend(out);347		for (k, v) in globals.iter() {348			out.bind(k.clone(), v.clone());349		}350		out.build()351	}352	#[cfg(feature = "legacy-this-file")]353	fn initialize(&self, s: State, source: Source) -> Context {354		use jrsonnet_evaluator::val::StrValue;355356		let mut builder = ObjValueBuilder::new();357		builder.with_super(self.stdlib_obj.clone());358		builder359			.member("thisFile".into())360			.hide()361			.value(Val::Str(StrValue::Flat(362				match source.source_path().path() {363					Some(p) => self.settings().path_resolver.resolve(p).into(),364					None => source.source_path().to_string().into(),365				},366			)))367			.expect("this object builder is empty");368		let stdlib_with_this_file = builder.build();369370		let mut context = ContextBuilder::with_capacity(s, 1);371		context.bind(372			"std".into(),373			Thunk::evaluated(Val::Obj(stdlib_with_this_file)),374		);375		for (k, v) in self.settings().globals.iter() {376			context.bind(k.clone(), v.clone());377		}378		context.build()379	}380	fn as_any(&self) -> &dyn std::any::Any {381		self382	}383}384385pub trait StateExt {386	/// This method was previously implemented in jrsonnet-evaluator itself387	fn with_stdlib(&self);388	fn add_global(&self, name: IStr, value: Thunk<Val>);389}390391impl StateExt for State {392	fn with_stdlib(&self) {393		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());394		self.settings_mut().context_initializer = tb!(initializer)395	}396	fn add_global(&self, name: IStr, value: Thunk<Val>) {397		self.settings()398			.context_initializer399			.as_any()400			.downcast_ref::<ContextInitializer>()401			.expect("not standard context initializer")402			.settings_mut()403			.globals404			.insert(name, value);405	}406}