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

difftreelog

feat enable std.thisFile by default

Yaroslav Bolyukin2024-06-18parent: #4f26f96.patch.diff
in: master

6 files changed

modifiedcmds/jrsonnet/Cargo.tomldiffbeforeafterboth
--- a/cmds/jrsonnet/Cargo.toml
+++ b/cmds/jrsonnet/Cargo.toml
@@ -44,9 +44,6 @@
 # --exp-apply
 exp-apply = []
 
-# std.thisFile support
-legacy-this-file = ["jrsonnet-cli/legacy-this-file"]
-
 nightly = ["jrsonnet-evaluator/nightly"]
 
 [dependencies]
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -170,7 +170,7 @@
 	let import_resolver = opts.misc.import_resolver();
 	s.set_import_resolver(import_resolver);
 
-	let std = opts.std.context_initializer(s)?;
+	let std = opts.std.context_initializer()?;
 	if let Some(std) = std {
 		s.set_context_initializer(std);
 	}
modifiedcrates/jrsonnet-cli/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-cli/Cargo.toml
+++ b/crates/jrsonnet-cli/Cargo.toml
@@ -26,7 +26,6 @@
 exp-regex = [
     "jrsonnet-stdlib/exp-regex",
 ]
-legacy-this-file = ["jrsonnet-stdlib/legacy-this-file"]
 
 [dependencies]
 jrsonnet-evaluator = { workspace = true, features = ["explaining-traces"] }
modifiedcrates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -1,7 +1,7 @@
 use std::{fs::read_to_string, str::FromStr};
 
 use clap::Parser;
-use jrsonnet_evaluator::{trace::PathResolver, Result, State};
+use jrsonnet_evaluator::{trace::PathResolver, Result};
 use jrsonnet_stdlib::ContextInitializer;
 
 #[derive(Clone)]
@@ -104,11 +104,11 @@
 	ext_code_file: Vec<ExtFile>,
 }
 impl StdOpts {
-	pub fn context_initializer(&self, s: &State) -> Result<Option<ContextInitializer>> {
+	pub fn context_initializer(&self) -> Result<Option<ContextInitializer>> {
 		if self.no_stdlib {
 			return Ok(None);
 		}
-		let ctx = ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback());
+		let ctx = ContextInitializer::new(PathResolver::new_cwd_fallback());
 		for ext in &self.ext_str {
 			ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());
 		}
modifiedcrates/jrsonnet-stdlib/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/Cargo.toml
+++ b/crates/jrsonnet-stdlib/Cargo.toml
@@ -11,8 +11,6 @@
 workspace = true
 
 [features]
-# Enables legacy `std.thisFile` support, at the cost of worse caching
-legacy-this-file = []
 # Add order preservation flag to some functions
 exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
 # Bigint type
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/lib.rs
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 hash;40mod manifest;41mod math;42mod misc;43mod objects;44mod operator;45mod parse;46#[cfg(feature = "exp-regex")]47mod regex;48mod sets;49mod sort;50mod strings;51mod types;5253#[allow(clippy::too_many_lines)]54pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {55	let mut builder = ObjValueBuilder::new();5657	// FIXME: Use PHF58	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		("mapWithIndex", builtin_map_with_index::INST),73		("mapWithKey", builtin_map_with_key::INST),74		("flatMap", builtin_flatmap::INST),75		("filter", builtin_filter::INST),76		("foldl", builtin_foldl::INST),77		("foldr", builtin_foldr::INST),78		("range", builtin_range::INST),79		("join", builtin_join::INST),80		("lines", builtin_lines::INST),81		("resolvePath", builtin_resolve_path::INST),82		("deepJoin", builtin_deep_join::INST),83		("reverse", builtin_reverse::INST),84		("any", builtin_any::INST),85		("all", builtin_all::INST),86		("member", builtin_member::INST),87		("find", builtin_find::INST),88		("contains", builtin_contains::INST),89		("count", builtin_count::INST),90		("avg", builtin_avg::INST),91		("removeAt", builtin_remove_at::INST),92		("remove", builtin_remove::INST),93		("flattenArrays", builtin_flatten_arrays::INST),94		("flattenDeepArray", builtin_flatten_deep_array::INST),95		("prune", builtin_prune::INST),96		("filterMap", builtin_filter_map::INST),97		// Math98		("abs", builtin_abs::INST),99		("sign", builtin_sign::INST),100		("max", builtin_max::INST),101		("min", builtin_min::INST),102		("clamp", builtin_clamp::INST),103		("sum", builtin_sum::INST),104		("modulo", builtin_modulo::INST),105		("floor", builtin_floor::INST),106		("ceil", builtin_ceil::INST),107		("log", builtin_log::INST),108		("pow", builtin_pow::INST),109		("sqrt", builtin_sqrt::INST),110		("sin", builtin_sin::INST),111		("cos", builtin_cos::INST),112		("tan", builtin_tan::INST),113		("asin", builtin_asin::INST),114		("acos", builtin_acos::INST),115		("atan", builtin_atan::INST),116		("atan2", builtin_atan2::INST),117		("exp", builtin_exp::INST),118		("mantissa", builtin_mantissa::INST),119		("exponent", builtin_exponent::INST),120		("round", builtin_round::INST),121		("isEven", builtin_is_even::INST),122		("isOdd", builtin_is_odd::INST),123		("isInteger", builtin_is_integer::INST),124		("isDecimal", builtin_is_decimal::INST),125		// Operator126		("mod", builtin_mod::INST),127		("primitiveEquals", builtin_primitive_equals::INST),128		("equals", builtin_equals::INST),129		("xor", builtin_xor::INST),130		("xnor", builtin_xnor::INST),131		("format", builtin_format::INST),132		// Sort133		("sort", builtin_sort::INST),134		("uniq", builtin_uniq::INST),135		("set", builtin_set::INST),136		("minArray", builtin_min_array::INST),137		("maxArray", builtin_max_array::INST),138		// Hash139		("md5", builtin_md5::INST),140		("sha1", builtin_sha1::INST),141		("sha256", builtin_sha256::INST),142		("sha512", builtin_sha512::INST),143		("sha3", builtin_sha3::INST),144		// Encoding145		("encodeUTF8", builtin_encode_utf8::INST),146		("decodeUTF8", builtin_decode_utf8::INST),147		("base64", builtin_base64::INST),148		("base64Decode", builtin_base64_decode::INST),149		("base64DecodeBytes", builtin_base64_decode_bytes::INST),150		// Objects151		("objectFieldsEx", builtin_object_fields_ex::INST),152		("objectFields", builtin_object_fields::INST),153		("objectFieldsAll", builtin_object_fields_all::INST),154		("objectValues", builtin_object_values::INST),155		("objectValuesAll", builtin_object_values_all::INST),156		("objectKeysValues", builtin_object_keys_values::INST),157		("objectKeysValuesAll", builtin_object_keys_values_all::INST),158		("objectHasEx", builtin_object_has_ex::INST),159		("objectHas", builtin_object_has::INST),160		("objectHasAll", builtin_object_has_all::INST),161		("objectRemoveKey", builtin_object_remove_key::INST),162		// Manifest163		("escapeStringJson", builtin_escape_string_json::INST),164		("escapeStringPython", builtin_escape_string_python::INST),165		("escapeStringXML", builtin_escape_string_xml::INST),166		("manifestJsonEx", builtin_manifest_json_ex::INST),167		("manifestJson", builtin_manifest_json::INST),168		("manifestJsonMinified", builtin_manifest_json_minified::INST),169		("manifestYamlDoc", builtin_manifest_yaml_doc::INST),170		("manifestYamlStream", builtin_manifest_yaml_stream::INST),171		("manifestTomlEx", builtin_manifest_toml_ex::INST),172		("manifestToml", builtin_manifest_toml::INST),173		("toString", builtin_to_string::INST),174		("manifestPython", builtin_manifest_python::INST),175		("manifestPythonVars", builtin_manifest_python_vars::INST),176		("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),177		("manifestIni", builtin_manifest_ini::INST),178		// Parse179		("parseJson", builtin_parse_json::INST),180		("parseYaml", builtin_parse_yaml::INST),181		// Strings182		("codepoint", builtin_codepoint::INST),183		("substr", builtin_substr::INST),184		("char", builtin_char::INST),185		("strReplace", builtin_str_replace::INST),186		("escapeStringBash", builtin_escape_string_bash::INST),187		("escapeStringDollars", builtin_escape_string_dollars::INST),188		("isEmpty", builtin_is_empty::INST),189		("equalsIgnoreCase", builtin_equals_ignore_case::INST),190		("splitLimit", builtin_splitlimit::INST),191		("splitLimitR", builtin_splitlimitr::INST),192		("split", builtin_split::INST),193		("asciiUpper", builtin_ascii_upper::INST),194		("asciiLower", builtin_ascii_lower::INST),195		("findSubstr", builtin_find_substr::INST),196		("parseInt", builtin_parse_int::INST),197		#[cfg(feature = "exp-bigint")]198		("bigint", builtin_bigint::INST),199		("parseOctal", builtin_parse_octal::INST),200		("parseHex", builtin_parse_hex::INST),201		("stringChars", builtin_string_chars::INST),202		("lstripChars", builtin_lstrip_chars::INST),203		("rstripChars", builtin_rstrip_chars::INST),204		("stripChars", builtin_strip_chars::INST),205		// Misc206		("length", builtin_length::INST),207		("get", builtin_get::INST),208		("startsWith", builtin_starts_with::INST),209		("endsWith", builtin_ends_with::INST),210		("assertEqual", builtin_assert_equal::INST),211		("mergePatch", builtin_merge_patch::INST),212		// Sets213		("setMember", builtin_set_member::INST),214		("setInter", builtin_set_inter::INST),215		("setDiff", builtin_set_diff::INST),216		("setUnion", builtin_set_union::INST),217		// Regex218		#[cfg(feature = "exp-regex")]219		("regexQuoteMeta", builtin_regex_quote_meta::INST),220		// Compat221		("__compare", builtin___compare::INST),222		("__compare_array", builtin___compare_array::INST),223		("__array_less", builtin___array_less::INST),224		("__array_greater", builtin___array_greater::INST),225		("__array_less_or_equal", builtin___array_less_or_equal::INST),226		(227			"__array_greater_or_equal",228			builtin___array_greater_or_equal::INST,229		),230	]231	.iter()232	.copied()233	{234		builder.method(name, builtin);235	}236237	builder.method(238		"extVar",239		builtin_ext_var {240			settings: settings.clone(),241		},242	);243	builder.method(244		"native",245		builtin_native {246			settings: settings.clone(),247		},248	);249	builder.method("trace", builtin_trace { settings });250	builder.method("id", FuncVal::Id);251252	#[cfg(feature = "exp-regex")]253	{254		// Regex255		let regex_cache = RegexCache::default();256		builder.method(257			"regexFullMatch",258			builtin_regex_full_match {259				cache: regex_cache.clone(),260			},261		);262		builder.method(263			"regexPartialMatch",264			builtin_regex_partial_match {265				cache: regex_cache.clone(),266			},267		);268		builder.method(269			"regexReplace",270			builtin_regex_replace {271				cache: regex_cache.clone(),272			},273		);274		builder.method(275			"regexGlobalReplace",276			builtin_regex_global_replace { cache: regex_cache },277		);278	};279280	builder.build()281}282283pub trait TracePrinter {284	fn print_trace(&self, loc: CallLocation, value: IStr);285}286287pub struct StdTracePrinter {288	resolver: PathResolver,289}290impl StdTracePrinter {291	pub fn new(resolver: PathResolver) -> Self {292		Self { resolver }293	}294}295impl TracePrinter for StdTracePrinter {296	fn print_trace(&self, loc: CallLocation, value: IStr) {297		eprint!("TRACE:");298		if let Some(loc) = loc.0 {299			let locs = loc.0.map_source_locations(&[loc.1]);300			eprint!(301				" {}:{}",302				loc.0.source_path().path().map_or_else(303					|| loc.0.source_path().to_string(),304					|p| self.resolver.resolve(p)305				),306				locs[0].line307			);308		}309		eprintln!(" {value}");310	}311}312313pub struct Settings {314	/// Used for `std.extVar`315	pub ext_vars: HashMap<IStr, TlaArg>,316	/// Used for `std.native`317	pub ext_natives: HashMap<IStr, FuncVal>,318	/// Used for `std.trace`319	pub trace_printer: Box<dyn TracePrinter>,320	/// Used for `std.thisFile`321	pub path_resolver: PathResolver,322}323324fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {325	let source_name = format!("<extvar:{name}>");326	Source::new_virtual(source_name.into(), code.into())327}328329#[derive(Trace, Clone)]330pub struct ContextInitializer {331	/// When we don't need to support legacy-this-file, we can reuse same context for all files332	#[cfg(not(feature = "legacy-this-file"))]333	context: jrsonnet_evaluator::Context,334	/// For `populate`335	#[cfg(not(feature = "legacy-this-file"))]336	stdlib_thunk: Thunk<Val>,337	/// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it338	#[cfg(feature = "legacy-this-file")]339	stdlib_obj: ObjValue,340	settings: Rc<RefCell<Settings>>,341}342impl ContextInitializer {343	pub fn new(s: State, resolver: PathResolver) -> Self {344		let settings = Settings {345			ext_vars: HashMap::new(),346			ext_natives: HashMap::new(),347			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),348			path_resolver: resolver,349		};350		let settings = Rc::new(RefCell::new(settings));351		let stdlib_obj = stdlib_uncached(settings.clone());352		#[cfg(not(feature = "legacy-this-file"))]353		let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));354		#[cfg(feature = "legacy-this-file")]355		let _ = s;356		Self {357			#[cfg(not(feature = "legacy-this-file"))]358			context: {359				let mut context = ContextBuilder::with_capacity(s, 1);360				context.bind("std", stdlib_thunk.clone());361				context.build()362			},363			#[cfg(not(feature = "legacy-this-file"))]364			stdlib_thunk,365			#[cfg(feature = "legacy-this-file")]366			stdlib_obj,367			settings,368		}369	}370	pub fn settings(&self) -> Ref<Settings> {371		self.settings.borrow()372	}373	pub fn settings_mut(&self) -> RefMut<Settings> {374		self.settings.borrow_mut()375	}376	pub fn add_ext_var(&self, name: IStr, value: Val) {377		self.settings_mut()378			.ext_vars379			.insert(name, TlaArg::Val(value));380	}381	pub fn add_ext_str(&self, name: IStr, value: IStr) {382		self.settings_mut()383			.ext_vars384			.insert(name, TlaArg::String(value));385	}386	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {387		let code = code.into();388		let source = extvar_source(name, code.clone());389		let parsed = jrsonnet_parser::parse(390			&code,391			&jrsonnet_parser::ParserSettings {392				source: source.clone(),393			},394		)395		.map_err(|e| ImportSyntaxError {396			path: source,397			error: Box::new(e),398		})?;399		// self.data_mut().volatile_files.insert(source_name, code);400		self.settings_mut()401			.ext_vars402			.insert(name.into(), TlaArg::Code(parsed));403		Ok(())404	}405	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {406		self.settings_mut()407			.ext_natives408			.insert(name.into(), cb.into());409	}410}411impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {412	fn reserve_vars(&self) -> usize {413		1414	}415	#[cfg(not(feature = "legacy-this-file"))]416	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {417		self.context.clone()418	}419	#[cfg(not(feature = "legacy-this-file"))]420	fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {421		builder.bind("std", self.stdlib_thunk.clone());422	}423	#[cfg(feature = "legacy-this-file")]424	fn populate(&self, source: Source, builder: &mut ContextBuilder) {425		let mut std = ObjValueBuilder::new();426		std.with_super(self.stdlib_obj.clone());427		std.field("thisFile").hide().value({428			let source_path = source.source_path();429			source_path.path().map_or_else(430				|| source_path.to_string(),431				|p| self.settings().path_resolver.resolve(p),432			)433		});434		let stdlib_with_this_file = std.build();435436		builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));437	}438	fn as_any(&self) -> &dyn std::any::Any {439		self440	}441}442443pub trait StateExt {444	/// This method was previously implemented in jrsonnet-evaluator itself445	fn with_stdlib(&self);446}447448impl StateExt for State {449	fn with_stdlib(&self) {450		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());451		self.settings_mut().context_initializer = tb!(initializer);452	}453}