git.delta.rocks / jrsonnet / refs/commits / 5f620e2b9aa7

difftreelog

refactor remove tla from state

Yaroslav Bolyukin2022-11-09parent: #7b01ecb.patch.diff
in: master

6 files changed

modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -5,8 +5,8 @@
 
 use clap::{CommandFactory, Parser};
 use clap_complete::Shell;
-use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts};
-use jrsonnet_evaluator::{error::LocError, State};
+use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts, TraceOpts};
+use jrsonnet_evaluator::{apply_tla, error::LocError, throw, ResultExt, State, Val};
 
 #[cfg(feature = "mimalloc")]
 #[global_allocator]
@@ -121,8 +121,8 @@
 }
 
 fn main_real(s: &State, opts: Opts) -> Result<(), Error> {
-	let _guards = opts.general.configure(s)?;
-	opts.manifest.configure(s)?;
+	let (_stack_guard, tla, _gc_guard) = opts.general.configure(s)?;
+	let manifest_format = opts.manifest.configure(s)?;
 
 	let input = opts.input.input.ok_or(Error::MissingInputArgument)?;
 	let val = if opts.input.exec {
@@ -136,7 +136,7 @@
 		s.import(&input)?
 	};
 
-	let val = s.with_tla(val)?;
+	let val = apply_tla(s.clone(), &tla, val)?;
 
 	if let Some(multi) = opts.output.multi {
 		if opts.output.create_output_dirs {
modifiedcrates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -71,7 +71,7 @@
 	misc: MiscOpts,
 
 	#[clap(flatten)]
-	tla: TLAOpts,
+	tla: TlaOpts,
 	#[clap(flatten)]
 	std: StdOpts,
 
@@ -85,16 +85,17 @@
 impl ConfigureState for GeneralOpts {
 	type Guards = (
 		<MiscOpts as ConfigureState>::Guards,
+		<TlaOpts as ConfigureState>::Guards,
 		<GcOpts as ConfigureState>::Guards,
 	);
 	fn configure(&self, s: &State) -> Result<Self::Guards> {
 		// Configure trace first, because tla-code/ext-code can throw
 		self.trace.configure(s)?;
 		let misc_guards = self.misc.configure(s)?;
-		self.tla.configure(s)?;
+		let tla_guards = self.tla.configure(s)?;
 		self.std.configure(s)?;
 		let gc_guards = self.gc.configure(s)?;
-		Ok((misc_guards, gc_guards))
+		Ok((misc_guards, tla_guards, gc_guards))
 	}
 }
 
modifiedcrates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,11 +1,17 @@
 use clap::Parser;
-use jrsonnet_evaluator::{error::Result, State};
+use jrsonnet_evaluator::{
+	error::{Error, Result},
+	function::TlaArg,
+	gc::GcHashMap,
+	IStr, State,
+};
+use jrsonnet_parser::{ParserSettings, Source};
 
 use crate::{ConfigureState, ExtFile, ExtStr};
 
 #[derive(Parser)]
 #[clap(next_help_heading = "TOP LEVEL ARGUMENTS")]
-pub struct TLAOpts {
+pub struct TlaOpts {
 	/// Add top level string argument.
 	/// Top level arguments will be passed to function before manifestification stage.
 	/// This is preferred to ExtVars method.
@@ -25,21 +31,41 @@
 	#[clap(long, name = "name=tla code path", number_of_values = 1)]
 	tla_code_file: Vec<ExtFile>,
 }
-impl ConfigureState for TLAOpts {
-	type Guards = ();
-	fn configure(&self, s: &State) -> Result<()> {
-		for tla in self.tla_str.iter() {
-			s.add_tla_str((&tla.name as &str).into(), (&tla.value as &str).into());
+impl ConfigureState for TlaOpts {
+	type Guards = GcHashMap<IStr, TlaArg>;
+	fn configure(&self, _s: &State) -> Result<Self::Guards> {
+		let mut out = GcHashMap::new();
+		for (name, value) in self
+			.tla_str
+			.iter()
+			.map(|c| (&c.name, &c.value))
+			.chain(self.tla_str_file.iter().map(|c| (&c.name, &c.value)))
+		{
+			out.insert(name.into(), TlaArg::String(value.into()));
 		}
-		for tla in self.tla_str_file.iter() {
-			s.add_tla_str((&tla.name as &str).into(), (&tla.value as &str).into())
-		}
-		for tla in self.tla_code.iter() {
-			s.add_tla_code((&tla.name as &str).into(), &tla.value as &str)?;
-		}
-		for tla in self.tla_code_file.iter() {
-			s.add_tla_code((&tla.name as &str).into(), &tla.value as &str)?;
+		for (name, code) in self
+			.tla_code
+			.iter()
+			.map(|c| (&c.name, &c.value))
+			.chain(self.tla_code_file.iter().map(|c| (&c.name, &c.value)))
+		{
+			let source = Source::new_virtual(format!("<top-level-arg:{name}>").into(), code.into());
+			out.insert(
+				(&name as &str).into(),
+				TlaArg::Code(
+					jrsonnet_parser::parse(
+						&code,
+						&ParserSettings {
+							source: source.clone(),
+						},
+					)
+					.map_err(|e| Error::ImportSyntaxError {
+						path: source,
+						error: Box::new(e),
+					})?,
+				),
+			);
 		}
-		Ok(())
+		Ok(out)
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -1,10 +1,11 @@
-use std::collections::HashMap;
-
+use hashbrown::HashMap;
 use jrsonnet_gcmodule::Trace;
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{ArgsDesc, LocExpr};
 
-use crate::{error::Result, evaluate, tb, typed::Typed, val::ThunkValue, Context, Thunk, Val};
+use crate::{
+	error::Result, evaluate, gc::GcHashMap, tb, typed::Typed, val::ThunkValue, Context, Thunk, Val,
+};
 
 /// Marker for arguments, which can be evaluated with context set to None
 pub trait OptionalContext {}
@@ -214,6 +215,34 @@
 }
 impl<A, S> OptionalContext for HashMap<IStr, A, S> where A: ArgLike + OptionalContext {}
 
+impl<A: ArgLike> ArgsLike for GcHashMap<IStr, A> {
+	fn unnamed_len(&self) -> usize {
+		self.0.unnamed_len()
+	}
+
+	fn unnamed_iter(
+		&self,
+		ctx: Context,
+		tailstrict: bool,
+		handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
+	) -> Result<()> {
+		self.0.unnamed_iter(ctx, tailstrict, handler)
+	}
+
+	fn named_iter(
+		&self,
+		ctx: Context,
+		tailstrict: bool,
+		handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
+	) -> Result<()> {
+		self.0.named_iter(ctx, tailstrict, handler)
+	}
+
+	fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
+		self.0.named_names(handler)
+	}
+}
+
 macro_rules! impl_args_like {
 	($count:expr; $($gen:ident)*) => {
 		impl<$($gen: ArgLike,)*> sealed::Unnamed for ($($gen,)*) {}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/lib.rs
1//! jsonnet interpreter implementation2#![cfg_attr(feature = "nightly", feature(thread_local))]3#![deny(unsafe_op_in_unsafe_fn)]4#![warn(5	clippy::all,6	clippy::nursery,7	clippy::pedantic,8	// missing_docs,9	elided_lifetimes_in_paths,10	explicit_outlives_requirements,11	noop_method_call,12	single_use_lifetimes,13	variant_size_differences,14	rustdoc::all15)]16#![allow(17	macro_expanded_macro_exports_accessed_by_absolute_paths,18	clippy::ptr_arg,19	// Too verbose20	clippy::must_use_candidate,21	// A lot of functions pass around errors thrown by code22	clippy::missing_errors_doc,23	// A lot of pointers have interior Rc24	clippy::needless_pass_by_value,25	// Its fine26	clippy::wildcard_imports,27	clippy::enum_glob_use,28	clippy::module_name_repetitions,29	// TODO: fix individual issues, however this works as intended almost everywhere30	clippy::cast_precision_loss,31	clippy::cast_possible_wrap,32	clippy::cast_possible_truncation,33	clippy::cast_sign_loss,34	// False positives35	// https://github.com/rust-lang/rust-clippy/issues/690236	clippy::use_self,37	// https://github.com/rust-lang/rust-clippy/issues/853938	clippy::iter_with_drain,39	// ci is being run with nightly, but library should work on stable40	clippy::missing_const_for_fn,41)]4243// For jrsonnet-macros44extern crate self as jrsonnet_evaluator;4546mod ctx;47mod dynamic;48pub mod error;49mod evaluate;50pub mod function;51pub mod gc;52mod import;53mod integrations;54mod map;55mod obj;56pub mod stack;57pub mod stdlib;58pub mod trace;59pub mod typed;60pub mod val;6162use std::{63	any::Any,64	cell::{Ref, RefCell, RefMut},65	collections::HashMap,66	fmt::{self, Debug},67	path::Path,68};6970pub use ctx::*;71pub use dynamic::*;72use error::{Error::*, LocError, Result, ResultExt};73pub use evaluate::*;74use function::{CallLocation, TlaArg};75use gc::{GcHashMap, TraceBox};76use hashbrown::hash_map::RawEntryMut;77pub use import::*;78use jrsonnet_gcmodule::{Cc, Trace};79pub use jrsonnet_interner::{IBytes, IStr};80pub use jrsonnet_parser as parser;81use jrsonnet_parser::*;82pub use obj::*;83use stack::check_depth;84use trace::{CompactFormat, TraceFormat};85pub use val::{ManifestFormat, Thunk, Val};8687/// Thunk without bound `super`/`this`88/// object inheritance may be overriden multiple times, and will be fixed only on field read89pub trait Unbound: Trace {90	/// Type of value after object context is bound91	type Bound;92	/// Create value bound to specified object context93	fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;94}9596/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code97/// Standard jsonnet fields are always unbound98#[derive(Clone, Trace)]99pub enum MaybeUnbound {100	/// Value needs to be bound to `this`/`super`101	Unbound(Cc<TraceBox<dyn Unbound<Bound = Val>>>),102	/// Value is object-independent103	Bound(Thunk<Val>),104}105106impl Debug for MaybeUnbound {107	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {108		write!(f, "MaybeUnbound")109	}110}111impl MaybeUnbound {112	/// Attach object context to value, if required113	pub fn evaluate(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {114		match self {115			Self::Unbound(v) => v.bind(sup, this),116			Self::Bound(v) => Ok(v.evaluate()?),117		}118	}119}120121/// During import, this trait will be called to create initial context for file.122/// It may initialize global variables, stdlib for example.123pub trait ContextInitializer: Trace {124	/// Initialize default file context.125	fn initialize(&self, state: State, for_file: Source) -> Context;126	/// Allows upcasting from abstract to concrete context initializer.127	/// jrsonnet by itself doesn't use this method, it is allowed for it to panic.128	fn as_any(&self) -> &dyn Any;129}130131/// Context initializer which adds nothing.132#[derive(Trace)]133pub struct DummyContextInitializer;134impl ContextInitializer for DummyContextInitializer {135	fn initialize(&self, state: State, _for_file: Source) -> Context {136		ContextBuilder::new(state).build()137	}138	fn as_any(&self) -> &dyn Any {139		self140	}141}142143/// Dynamically reconfigurable evaluation settings144#[derive(Trace)]145pub struct EvaluationSettings {146	/// Limits amount of stack trace items preserved147	pub max_trace: usize,148	/// TLA vars149	pub tla_vars: HashMap<IStr, TlaArg>,150	/// Context initializer, which will be used for imports and everything151	/// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`152	pub context_initializer: TraceBox<dyn ContextInitializer>,153	/// Used to resolve file locations/contents154	pub import_resolver: TraceBox<dyn ImportResolver>,155	/// Used in manifestification functions156	pub manifest_format: ManifestFormat,157	/// Used for bindings158	pub trace_format: TraceBox<dyn TraceFormat>,159}160impl Default for EvaluationSettings {161	fn default() -> Self {162		Self {163			max_trace: 20,164			context_initializer: tb!(DummyContextInitializer),165			tla_vars: HashMap::default(),166			import_resolver: tb!(DummyImportResolver),167			manifest_format: ManifestFormat::Json {168				padding: 4,169				#[cfg(feature = "exp-preserve-order")]170				preserve_order: false,171			},172			trace_format: tb!(CompactFormat {173				padding: 4,174				resolver: trace::PathResolver::Absolute,175			}),176		}177	}178}179180#[derive(Trace)]181struct FileData {182	string: Option<IStr>,183	bytes: Option<IBytes>,184	parsed: Option<LocExpr>,185	evaluated: Option<Val>,186187	evaluating: bool,188}189impl FileData {190	fn new_string(data: IStr) -> Self {191		Self {192			string: Some(data),193			bytes: None,194			parsed: None,195			evaluated: None,196			evaluating: false,197		}198	}199	fn new_bytes(data: IBytes) -> Self {200		Self {201			string: None,202			bytes: Some(data),203			parsed: None,204			evaluated: None,205			evaluating: false,206		}207	}208}209210#[derive(Default, Trace)]211pub struct EvaluationStateInternals {212	/// Internal state213	file_cache: RefCell<GcHashMap<SourcePath, FileData>>,214	/// Settings, safe to change at runtime215	settings: RefCell<EvaluationSettings>,216}217218/// Maintains stack trace and import resolution219#[derive(Default, Clone, Trace)]220pub struct State(Cc<EvaluationStateInternals>);221222impl State {223	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise224	pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {225		let mut file_cache = self.file_cache();226		let mut file = file_cache.raw_entry_mut().from_key(&path);227228		let file = match file {229			RawEntryMut::Occupied(ref mut d) => d.get_mut(),230			RawEntryMut::Vacant(v) => {231				let data = self.settings().import_resolver.load_file_contents(&path)?;232				v.insert(233					path.clone(),234					FileData::new_string(235						std::str::from_utf8(&data)236							.map_err(|_| ImportBadFileUtf8(path.clone()))?237							.into(),238					),239				)240				.1241			}242		};243		if let Some(str) = &file.string {244			return Ok(str.clone());245		}246		if file.string.is_none() {247			file.string = Some(248				file.bytes249					.as_ref()250					.expect("either string or bytes should be set")251					.clone()252					.cast_str()253					.ok_or_else(|| ImportBadFileUtf8(path.clone()))?,254			);255		}256		Ok(file.string.as_ref().expect("just set").clone())257	}258	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise259	pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {260		let mut file_cache = self.file_cache();261		let mut file = file_cache.raw_entry_mut().from_key(&path);262263		let file = match file {264			RawEntryMut::Occupied(ref mut d) => d.get_mut(),265			RawEntryMut::Vacant(v) => {266				let data = self.settings().import_resolver.load_file_contents(&path)?;267				v.insert(path.clone(), FileData::new_bytes(data.as_slice().into()))268					.1269			}270		};271		if let Some(str) = &file.bytes {272			return Ok(str.clone());273		}274		if file.bytes.is_none() {275			file.bytes = Some(276				file.string277					.as_ref()278					.expect("either string or bytes should be set")279					.clone()280					.cast_bytes(),281			);282		}283		Ok(file.bytes.as_ref().expect("just set").clone())284	}285	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise286	pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {287		let mut file_cache = self.file_cache();288		let mut file = file_cache.raw_entry_mut().from_key(&path);289290		let file = match file {291			RawEntryMut::Occupied(ref mut d) => d.get_mut(),292			RawEntryMut::Vacant(v) => {293				let data = self.settings().import_resolver.load_file_contents(&path)?;294				v.insert(295					path.clone(),296					FileData::new_string(297						std::str::from_utf8(&data)298							.map_err(|_| ImportBadFileUtf8(path.clone()))?299							.into(),300					),301				)302				.1303			}304		};305		if let Some(val) = &file.evaluated {306			return Ok(val.clone());307		}308		if file.string.is_none() {309			file.string = Some(310				std::str::from_utf8(311					file.bytes312						.as_ref()313						.expect("either string or bytes should be set"),314				)315				.map_err(|_| ImportBadFileUtf8(path.clone()))?316				.into(),317			);318		}319		let code = file.string.as_ref().expect("just set");320		let file_name = Source::new(path.clone(), code.clone());321		if file.parsed.is_none() {322			file.parsed = Some(323				jrsonnet_parser::parse(324					code,325					&ParserSettings {326						file_name: file_name.clone(),327					},328				)329				.map_err(|e| ImportSyntaxError {330					path: file_name.clone(),331					error: Box::new(e),332				})?,333			);334		}335		let parsed = file.parsed.as_ref().expect("just set").clone();336		if file.evaluating {337			throw!(InfiniteRecursionDetected)338		}339		file.evaluating = true;340		// Dropping file cache guard here, as evaluation may use this map too341		drop(file_cache);342		let res = evaluate(self.create_default_context(file_name), &parsed);343344		let mut file_cache = self.file_cache();345		let mut file = file_cache.raw_entry_mut().from_key(&path);346347		let RawEntryMut::Occupied(file) = &mut file else {348			unreachable!("this file was just here!")349		};350		let file = file.get_mut();351		file.evaluating = false;352		match res {353			Ok(v) => {354				file.evaluated = Some(v.clone());355				Ok(v)356			}357			Err(e) => Err(e),358		}359	}360361	/// Has same semantics as `import 'path'` called from `from` file362	pub fn import_from(&self, from: &SourcePath, path: &str) -> Result<Val> {363		let resolved = self.resolve_from(from, path)?;364		self.import_resolved(resolved)365	}366	pub fn import(&self, path: impl AsRef<Path>) -> Result<Val> {367		let resolved = self.resolve(path)?;368		self.import_resolved(resolved)369	}370371	/// Creates context with all passed global variables372	pub fn create_default_context(&self, source: Source) -> Context {373		let context_initializer = &self.settings().context_initializer;374		context_initializer.initialize(self.clone(), source)375	}376377	/// Executes code creating a new stack frame378	pub fn push<T>(379		e: CallLocation<'_>,380		frame_desc: impl FnOnce() -> String,381		f: impl FnOnce() -> Result<T>,382	) -> Result<T> {383		let _guard = check_depth()?;384385		f().with_description_src(e, frame_desc)386	}387388	/// Executes code creating a new stack frame389	pub fn push_val(390		&self,391		e: &ExprLocation,392		frame_desc: impl FnOnce() -> String,393		f: impl FnOnce() -> Result<Val>,394	) -> Result<Val> {395		let _guard = check_depth()?;396397		f().with_description_src(e, frame_desc)398	}399	/// Executes code creating a new stack frame400	pub fn push_description<T>(401		frame_desc: impl FnOnce() -> String,402		f: impl FnOnce() -> Result<T>,403	) -> Result<T> {404		let _guard = check_depth()?;405406		f().with_description(frame_desc)407	}408409	/// # Panics410	/// In case of formatting failure411	pub fn stringify_err(&self, e: &LocError) -> String {412		let mut out = String::new();413		self.settings()414			.trace_format415			.write_trace(&mut out, self, e)416			.unwrap();417		out418	}419420	pub fn manifest(&self, val: Val) -> Result<IStr> {421		Self::push_description(422			|| "manifestification".to_string(),423			|| val.manifest(&self.manifest_format()),424		)425	}426	pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {427		val.manifest_multi(&self.manifest_format())428	}429	pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {430		val.manifest_stream(&self.manifest_format())431	}432433	/// If passed value is function then call with set TLA434	pub fn with_tla(&self, val: Val) -> Result<Val> {435		Ok(match val {436			Val::Func(func) => State::push_description(437				|| "during TLA call".to_owned(),438				|| {439					func.evaluate(440						self.create_default_context(Source::new_virtual(441							"<tla>".into(),442							IStr::empty(),443						)),444						CallLocation::native(),445						&self.settings().tla_vars,446						true,447					)448				},449			)?,450			v => v,451		})452	}453}454455/// Internals456impl State {457	fn file_cache(&self) -> RefMut<'_, GcHashMap<SourcePath, FileData>> {458		self.0.file_cache.borrow_mut()459	}460	pub fn settings(&self) -> Ref<'_, EvaluationSettings> {461		self.0.settings.borrow()462	}463	pub fn settings_mut(&self) -> RefMut<'_, EvaluationSettings> {464		self.0.settings.borrow_mut()465	}466}467468/// Raw methods evaluate passed values but don't perform TLA execution469impl State {470	/// Parses and evaluates the given snippet471	pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {472		let code = code.into();473		let source = Source::new_virtual(name.into(), code.clone());474		let parsed = jrsonnet_parser::parse(475			&code,476			&ParserSettings {477				file_name: source.clone(),478			},479		)480		.map_err(|e| ImportSyntaxError {481			path: source.clone(),482			error: Box::new(e),483		})?;484		evaluate(self.create_default_context(source), &parsed)485	}486}487488/// Settings utilities489impl State {490	pub fn add_tla(&self, name: IStr, value: Val) {491		self.settings_mut()492			.tla_vars493			.insert(name, TlaArg::Val(value));494	}495	pub fn add_tla_str(&self, name: IStr, value: IStr) {496		self.settings_mut()497			.tla_vars498			.insert(name, TlaArg::String(value));499	}500	pub fn add_tla_code(&self, name: IStr, code: &str) -> Result<()> {501		let source_name = format!("<top-level-arg:{name}>");502		let source = Source::new_virtual(source_name.into(), code.into());503		let parsed = jrsonnet_parser::parse(504			code,505			&ParserSettings {506				file_name: source.clone(),507			},508		)509		.map_err(|e| ImportSyntaxError {510			path: source,511			error: Box::new(e),512		})?;513		self.settings_mut()514			.tla_vars515			.insert(name, TlaArg::Code(parsed));516		Ok(())517	}518519	// Only panics in case of [`ImportResolver`] contract violation520	#[allow(clippy::missing_panics_doc)]521	pub fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {522		self.import_resolver().resolve_from(from, path.as_ref())523	}524525	// Only panics in case of [`ImportResolver`] contract violation526	#[allow(clippy::missing_panics_doc)]527	pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {528		self.import_resolver().resolve(path.as_ref())529	}530	pub fn import_resolver(&self) -> Ref<'_, dyn ImportResolver> {531		Ref::map(self.settings(), |s| &*s.import_resolver)532	}533	pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {534		self.settings_mut().import_resolver = TraceBox(resolver);535	}536	pub fn context_initializer(&self) -> Ref<'_, dyn ContextInitializer> {537		Ref::map(self.settings(), |s| &*s.context_initializer)538	}539540	pub fn manifest_format(&self) -> ManifestFormat {541		self.settings().manifest_format.clone()542	}543	pub fn set_manifest_format(&self, format: ManifestFormat) {544		self.settings_mut().manifest_format = format;545	}546547	pub fn trace_format(&self) -> Ref<'_, dyn TraceFormat> {548		Ref::map(self.settings(), |s| &*s.trace_format)549	}550	pub fn set_trace_format(&self, format: impl TraceFormat) {551		self.settings_mut().trace_format = tb!(format);552	}553554	pub fn max_trace(&self) -> usize {555		self.settings().max_trace556	}557	pub fn set_max_trace(&self, trace: usize) {558		self.settings_mut().max_trace = trace;559	}560}
after · crates/jrsonnet-evaluator/src/lib.rs
1//! jsonnet interpreter implementation2#![cfg_attr(feature = "nightly", feature(thread_local))]3#![deny(unsafe_op_in_unsafe_fn)]4#![warn(5	clippy::all,6	clippy::nursery,7	clippy::pedantic,8	// missing_docs,9	elided_lifetimes_in_paths,10	explicit_outlives_requirements,11	noop_method_call,12	single_use_lifetimes,13	variant_size_differences,14	rustdoc::all15)]16#![allow(17	macro_expanded_macro_exports_accessed_by_absolute_paths,18	clippy::ptr_arg,19	// Too verbose20	clippy::must_use_candidate,21	// A lot of functions pass around errors thrown by code22	clippy::missing_errors_doc,23	// A lot of pointers have interior Rc24	clippy::needless_pass_by_value,25	// Its fine26	clippy::wildcard_imports,27	clippy::enum_glob_use,28	clippy::module_name_repetitions,29	// TODO: fix individual issues, however this works as intended almost everywhere30	clippy::cast_precision_loss,31	clippy::cast_possible_wrap,32	clippy::cast_possible_truncation,33	clippy::cast_sign_loss,34	// False positives35	// https://github.com/rust-lang/rust-clippy/issues/690236	clippy::use_self,37	// https://github.com/rust-lang/rust-clippy/issues/853938	clippy::iter_with_drain,39	// ci is being run with nightly, but library should work on stable40	clippy::missing_const_for_fn,41)]4243// For jrsonnet-macros44extern crate self as jrsonnet_evaluator;4546mod ctx;47mod dynamic;48pub mod error;49mod evaluate;50pub mod function;51pub mod gc;52mod import;53mod integrations;54mod map;55mod obj;56pub mod stack;57pub mod stdlib;58mod tla;59pub mod trace;60pub mod typed;61pub mod val;6263use std::{64	any::Any,65	cell::{Ref, RefCell, RefMut},66	collections::HashMap,67	fmt::{self, Debug},68	path::Path,69};7071pub use ctx::*;72pub use dynamic::*;73use error::{Error::*, LocError, Result, ResultExt};74pub use evaluate::*;75use function::{CallLocation, TlaArg};76use gc::{GcHashMap, TraceBox};77use hashbrown::hash_map::RawEntryMut;78pub use import::*;79use jrsonnet_gcmodule::{Cc, Trace};80pub use jrsonnet_interner::{IBytes, IStr};81pub use jrsonnet_parser as parser;82use jrsonnet_parser::*;83pub use obj::*;84use stack::check_depth;85pub use tla::apply_tla;86pub use val::{ManifestFormat, Thunk, Val};8788/// Thunk without bound `super`/`this`89/// object inheritance may be overriden multiple times, and will be fixed only on field read90pub trait Unbound: Trace {91	/// Type of value after object context is bound92	type Bound;93	/// Create value bound to specified object context94	fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;95}9697/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code98/// Standard jsonnet fields are always unbound99#[derive(Clone, Trace)]100pub enum MaybeUnbound {101	/// Value needs to be bound to `this`/`super`102	Unbound(Cc<TraceBox<dyn Unbound<Bound = Val>>>),103	/// Value is object-independent104	Bound(Thunk<Val>),105}106107impl Debug for MaybeUnbound {108	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {109		write!(f, "MaybeUnbound")110	}111}112impl MaybeUnbound {113	/// Attach object context to value, if required114	pub fn evaluate(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {115		match self {116			Self::Unbound(v) => v.bind(sup, this),117			Self::Bound(v) => Ok(v.evaluate()?),118		}119	}120}121122/// During import, this trait will be called to create initial context for file.123/// It may initialize global variables, stdlib for example.124pub trait ContextInitializer: Trace {125	/// Initialize default file context.126	fn initialize(&self, state: State, for_file: Source) -> Context;127	/// Allows upcasting from abstract to concrete context initializer.128	/// jrsonnet by itself doesn't use this method, it is allowed for it to panic.129	fn as_any(&self) -> &dyn Any;130}131132/// Context initializer which adds nothing.133#[derive(Trace)]134pub struct DummyContextInitializer;135impl ContextInitializer for DummyContextInitializer {136	fn initialize(&self, state: State, _for_file: Source) -> Context {137		ContextBuilder::new(state).build()138	}139	fn as_any(&self) -> &dyn Any {140		self141	}142}143144/// Dynamically reconfigurable evaluation settings145#[derive(Trace)]146pub struct EvaluationSettings {147	/// Context initializer, which will be used for imports and everything148	/// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`149	pub context_initializer: TraceBox<dyn ContextInitializer>,150	/// Used to resolve file locations/contents151	pub import_resolver: TraceBox<dyn ImportResolver>,152	/// Used in manifestification functions153	pub manifest_format: ManifestFormat,154	/// Used for bindings155	pub trace_format: TraceBox<dyn TraceFormat>,156}157impl Default for EvaluationSettings {158	fn default() -> Self {159		Self {160			context_initializer: tb!(DummyContextInitializer),161			import_resolver: tb!(DummyImportResolver),162		}163	}164}165166#[derive(Trace)]167struct FileData {168	string: Option<IStr>,169	bytes: Option<IBytes>,170	parsed: Option<LocExpr>,171	evaluated: Option<Val>,172173	evaluating: bool,174}175impl FileData {176	fn new_string(data: IStr) -> Self {177		Self {178			string: Some(data),179			bytes: None,180			parsed: None,181			evaluated: None,182			evaluating: false,183		}184	}185	fn new_bytes(data: IBytes) -> Self {186		Self {187			string: None,188			bytes: Some(data),189			parsed: None,190			evaluated: None,191			evaluating: false,192		}193	}194}195196#[derive(Default, Trace)]197pub struct EvaluationStateInternals {198	/// Internal state199	file_cache: RefCell<GcHashMap<SourcePath, FileData>>,200	/// Settings, safe to change at runtime201	settings: RefCell<EvaluationSettings>,202}203204/// Maintains stack trace and import resolution205#[derive(Default, Clone, Trace)]206pub struct State(Cc<EvaluationStateInternals>);207208impl State {209	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise210	pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {211		let mut file_cache = self.file_cache();212		let mut file = file_cache.raw_entry_mut().from_key(&path);213214		let file = match file {215			RawEntryMut::Occupied(ref mut d) => d.get_mut(),216			RawEntryMut::Vacant(v) => {217				let data = self.settings().import_resolver.load_file_contents(&path)?;218				v.insert(219					path.clone(),220					FileData::new_string(221						std::str::from_utf8(&data)222							.map_err(|_| ImportBadFileUtf8(path.clone()))?223							.into(),224					),225				)226				.1227			}228		};229		if let Some(str) = &file.string {230			return Ok(str.clone());231		}232		if file.string.is_none() {233			file.string = Some(234				file.bytes235					.as_ref()236					.expect("either string or bytes should be set")237					.clone()238					.cast_str()239					.ok_or_else(|| ImportBadFileUtf8(path.clone()))?,240			);241		}242		Ok(file.string.as_ref().expect("just set").clone())243	}244	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise245	pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {246		let mut file_cache = self.file_cache();247		let mut file = file_cache.raw_entry_mut().from_key(&path);248249		let file = match file {250			RawEntryMut::Occupied(ref mut d) => d.get_mut(),251			RawEntryMut::Vacant(v) => {252				let data = self.settings().import_resolver.load_file_contents(&path)?;253				v.insert(path.clone(), FileData::new_bytes(data.as_slice().into()))254					.1255			}256		};257		if let Some(str) = &file.bytes {258			return Ok(str.clone());259		}260		if file.bytes.is_none() {261			file.bytes = Some(262				file.string263					.as_ref()264					.expect("either string or bytes should be set")265					.clone()266					.cast_bytes(),267			);268		}269		Ok(file.bytes.as_ref().expect("just set").clone())270	}271	/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise272	pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {273		let mut file_cache = self.file_cache();274		let mut file = file_cache.raw_entry_mut().from_key(&path);275276		let file = match file {277			RawEntryMut::Occupied(ref mut d) => d.get_mut(),278			RawEntryMut::Vacant(v) => {279				let data = self.settings().import_resolver.load_file_contents(&path)?;280				v.insert(281					path.clone(),282					FileData::new_string(283						std::str::from_utf8(&data)284							.map_err(|_| ImportBadFileUtf8(path.clone()))?285							.into(),286					),287				)288				.1289			}290		};291		if let Some(val) = &file.evaluated {292			return Ok(val.clone());293		}294		if file.string.is_none() {295			file.string = Some(296				std::str::from_utf8(297					file.bytes298						.as_ref()299						.expect("either string or bytes should be set"),300				)301				.map_err(|_| ImportBadFileUtf8(path.clone()))?302				.into(),303			);304		}305		let code = file.string.as_ref().expect("just set");306		let file_name = Source::new(path.clone(), code.clone());307		if file.parsed.is_none() {308			file.parsed = Some(309				jrsonnet_parser::parse(310					code,311					&ParserSettings {312						file_name: file_name.clone(),313					},314				)315				.map_err(|e| ImportSyntaxError {316					path: file_name.clone(),317					error: Box::new(e),318				})?,319			);320		}321		let parsed = file.parsed.as_ref().expect("just set").clone();322		if file.evaluating {323			throw!(InfiniteRecursionDetected)324		}325		file.evaluating = true;326		// Dropping file cache guard here, as evaluation may use this map too327		drop(file_cache);328		let res = evaluate(self.create_default_context(file_name), &parsed);329330		let mut file_cache = self.file_cache();331		let mut file = file_cache.raw_entry_mut().from_key(&path);332333		let RawEntryMut::Occupied(file) = &mut file else {334			unreachable!("this file was just here!")335		};336		let file = file.get_mut();337		file.evaluating = false;338		match res {339			Ok(v) => {340				file.evaluated = Some(v.clone());341				Ok(v)342			}343			Err(e) => Err(e),344		}345	}346347	/// Has same semantics as `import 'path'` called from `from` file348	pub fn import_from(&self, from: &SourcePath, path: &str) -> Result<Val> {349		let resolved = self.resolve_from(from, path)?;350		self.import_resolved(resolved)351	}352	pub fn import(&self, path: impl AsRef<Path>) -> Result<Val> {353		let resolved = self.resolve(path)?;354		self.import_resolved(resolved)355	}356357	/// Creates context with all passed global variables358	pub fn create_default_context(&self, source: Source) -> Context {359		let context_initializer = &self.settings().context_initializer;360		context_initializer.initialize(self.clone(), source)361	}362363	/// Executes code creating a new stack frame364	pub fn push<T>(365		e: CallLocation<'_>,366		frame_desc: impl FnOnce() -> String,367		f: impl FnOnce() -> Result<T>,368	) -> Result<T> {369		let _guard = check_depth()?;370371		f().with_description_src(e, frame_desc)372	}373374	/// Executes code creating a new stack frame375	pub fn push_val(376		&self,377		e: &ExprLocation,378		frame_desc: impl FnOnce() -> String,379		f: impl FnOnce() -> Result<Val>,380	) -> Result<Val> {381		let _guard = check_depth()?;382383		f().with_description_src(e, frame_desc)384	}385	/// Executes code creating a new stack frame386	pub fn push_description<T>(387		frame_desc: impl FnOnce() -> String,388		f: impl FnOnce() -> Result<T>,389	) -> Result<T> {390		let _guard = check_depth()?;391392		f().with_description(frame_desc)393	}394}395396/// Internals397impl State {398	fn file_cache(&self) -> RefMut<'_, GcHashMap<SourcePath, FileData>> {399		self.0.file_cache.borrow_mut()400	}401	pub fn settings(&self) -> Ref<'_, EvaluationSettings> {402		self.0.settings.borrow()403	}404	pub fn settings_mut(&self) -> RefMut<'_, EvaluationSettings> {405		self.0.settings.borrow_mut()406	}407}408409/// Raw methods evaluate passed values but don't perform TLA execution410impl State {411	/// Parses and evaluates the given snippet412	pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {413		let code = code.into();414		let source = Source::new_virtual(name.into(), code.clone());415		let parsed = jrsonnet_parser::parse(416			&code,417			&ParserSettings {418				file_name: source.clone(),419			},420		)421		.map_err(|e| ImportSyntaxError {422			path: source.clone(),423			error: Box::new(e),424		})?;425		evaluate(self.create_default_context(source), &parsed)426	}427}428429/// Settings utilities430impl State {431	// Only panics in case of [`ImportResolver`] contract violation432	#[allow(clippy::missing_panics_doc)]433	pub fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {434		self.import_resolver().resolve_from(from, path.as_ref())435	}436437	// Only panics in case of [`ImportResolver`] contract violation438	#[allow(clippy::missing_panics_doc)]439	pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {440		self.import_resolver().resolve(path.as_ref())441	}442	pub fn import_resolver(&self) -> Ref<'_, dyn ImportResolver> {443		Ref::map(self.settings(), |s| &*s.import_resolver)444	}445	pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {446		self.settings_mut().import_resolver = TraceBox(resolver);447	}448	pub fn context_initializer(&self) -> Ref<'_, dyn ContextInitializer> {449		Ref::map(self.settings(), |s| &*s.context_initializer)450	}451452	pub fn manifest_format(&self) -> ManifestFormat {453		self.settings().manifest_format.clone()454	}455	pub fn set_manifest_format(&self, format: ManifestFormat) {456		self.settings_mut().manifest_format = format;457	}458459	pub fn trace_format(&self) -> Ref<'_, dyn TraceFormat> {460		Ref::map(self.settings(), |s| &*s.trace_format)461	}462	pub fn set_trace_format(&self, format: impl TraceFormat) {463		self.settings_mut().trace_format = tb!(format);464	}465466	pub fn max_trace(&self) -> usize {467		self.settings().max_trace468	}469	pub fn set_max_trace(&self, trace: usize) {470		self.settings_mut().max_trace = trace;471	}472}
addedcrates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -0,0 +1,25 @@
+use jrsonnet_interner::IStr;
+use jrsonnet_parser::Source;
+
+use crate::{
+	function::{ArgsLike, CallLocation},
+	Result, State, Val,
+};
+
+pub fn apply_tla<A: ArgsLike>(s: State, args: &A, val: Val) -> Result<Val> {
+	Ok(if let Val::Func(func) = val {
+		State::push_description(
+			|| "during TLA call".to_owned(),
+			|| {
+				func.evaluate(
+					s.create_default_context(Source::new_virtual("<top-level-arg>".into(), IStr::empty())),
+					CallLocation::native(),
+					args,
+					false,
+				)
+			},
+		)?
+	} else {
+		val
+	})
+}