git.delta.rocks / jrsonnet / refs/commits / 772afa0049b2

difftreelog

refactor saner imports from TLA/std.extVars

tkuxywosYaroslav Bolyukin2026-02-07parent: #66a4ff8.patch.diff
in: master

13 files changed

modifiedbindings/jsonnet/src/import.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -14,7 +14,7 @@
 use jrsonnet_evaluator::{
 	bail,
 	error::{ErrorKind::*, Result},
-	ImportResolver,
+	AsPathLike, ImportResolver, ResolvePath,
 };
 use jrsonnet_gcmodule::Acyclic;
 use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
@@ -38,7 +38,7 @@
 	out: RefCell<HashMap<SourcePath, Vec<u8>>>,
 }
 impl ImportResolver for CallbackImportResolver {
-	fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
+	fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {
 		let base = if let Some(p) = from.downcast_ref::<SourceFile>() {
 			let mut o = p.path().to_owned();
 			o.pop();
@@ -51,7 +51,11 @@
 			unreachable!("can't resolve this path");
 		};
 		let base = unsafe { crate::unparse_path(&base) };
-		let rel = CString::new(path).unwrap();
+		let rel = path.as_path();
+		let rel = match rel {
+			ResolvePath::Str(s) => CString::new(s.as_bytes()).unwrap(),
+			ResolvePath::Path(p) => unsafe { crate::unparse_path(p) },
+		};
 		let found_here: *mut c_char = null_mut();
 
 		let mut buf = null_mut();
modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -28,7 +28,7 @@
 	rustc_hash::FxHashMap,
 	stack::set_stack_depth_limit,
 	trace::{CompactFormat, PathResolver, TraceFormat},
-	FileImportResolver, IStr, ImportResolver, Result, State, Val,
+	AsPathLike, FileImportResolver, IStr, ImportResolver, Result, State, Val,
 };
 use jrsonnet_gcmodule::Acyclic;
 use jrsonnet_parser::SourcePath;
@@ -62,18 +62,18 @@
 	}
 }
 
-unsafe fn unparse_path(input: &Path) -> Cow<'_, CStr> {
+unsafe fn unparse_path(input: &Path) -> CString {
 	#[cfg(target_family = "unix")]
 	{
 		use std::os::unix::ffi::OsStrExt;
 		let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");
-		Cow::Owned(str)
+		str
 	}
 	#[cfg(not(target_family = "unix"))]
 	{
 		let str = input.as_os_str().to_str().expect("bad utf-8");
 		let cstr = CString::new(str).expect("input has NUL inside");
-		Cow::Owned(cstr)
+		cstr
 	}
 }
 
@@ -93,16 +93,12 @@
 		self.inner.borrow().load_file_contents(resolved)
 	}
 
-	fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
+	fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {
 		self.inner.borrow().resolve_from(from, path)
 	}
 
-	fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+	fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {
 		self.inner.borrow().resolve_from_default(path)
-	}
-
-	fn resolve(&self, path: &Path) -> Result<SourcePath> {
-		self.inner.borrow().resolve(path)
 	}
 }
 
modifiedbindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -3,7 +3,6 @@
 use std::{ffi::CStr, os::raw::c_char};
 
 use jrsonnet_evaluator::{function::TlaArg, IStr};
-use jrsonnet_parser::{ParserSettings, Source};
 
 use crate::VM;
 
@@ -84,14 +83,7 @@
 	let code = unsafe { CStr::from_ptr(code) };
 
 	let name: IStr = name.to_str().expect("name is not utf-8").into();
-	let code: IStr = code.to_str().expect("code is not utf-8").into();
-	let code = jrsonnet_parser::parse(
-		&code,
-		&ParserSettings {
-			source: Source::new_virtual(format!("<top-level-arg:{name}>").into(), code.clone()),
-		},
-	)
-	.expect("can't parse TLA code");
+	let code: String = code.to_str().expect("code is not utf-8").to_owned();
 
-	vm.tla_args.insert(name, TlaArg::Code(code));
+	vm.tla_args.insert(name, TlaArg::InlineCode(code));
 }
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -182,7 +182,7 @@
 		let input_str = std::str::from_utf8(&input)?;
 		s.evaluate_snippet("<stdin>".to_owned(), input_str)?
 	} else {
-		s.import(&input)?
+		s.import(input.as_str())?
 	};
 
 	let tla = opts.tla.tla_opts()?;
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 std::str::FromStr;
 
 use clap::Parser;
-use jrsonnet_evaluator::{trace::PathResolver, Result};
+use jrsonnet_evaluator::{function::TlaArg, trace::PathResolver, Result};
 use jrsonnet_stdlib::ContextInitializer;
 
 #[derive(Clone)]
@@ -54,25 +54,20 @@
 #[derive(Clone)]
 pub struct ExtFile {
 	pub name: String,
-	pub value: String,
+	pub path: String,
 }
 
 impl FromStr for ExtFile {
 	type Err = String;
 
 	fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
-		let out: Vec<&str> = s.split('=').collect();
-		if out.len() != 2 {
+		let Some((name, path)) = s.split_once('=') else {
 			return Err("bad ext-file syntax".to_owned());
-		}
-		let file = read_to_string(out[1]);
-		match file {
-			Ok(content) => Ok(Self {
-				name: out[0].into(),
-				value: content,
-			}),
-			Err(e) => Err(format!("{e}")),
-		}
+		};
+		Ok(Self {
+			name: name.into(),
+			path: path.into(),
+		})
 	}
 }
 
@@ -110,16 +105,27 @@
 		}
 		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());
+			ctx.settings_mut().ext_vars.insert(
+				ext.name.as_str().into(),
+				TlaArg::String(ext.value.as_str().into()),
+			);
 		}
 		for ext in &self.ext_str_file {
-			ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());
+			ctx.settings_mut().ext_vars.insert(
+				ext.name.as_str().into(),
+				TlaArg::ImportStr(ext.path.clone()),
+			);
 		}
 		for ext in &self.ext_code {
-			ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;
+			ctx.settings_mut().ext_vars.insert(
+				ext.name.as_str().into(),
+				TlaArg::InlineCode(ext.value.clone()),
+			);
 		}
 		for ext in &self.ext_code_file {
-			ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;
+			ctx.settings_mut()
+				.ext_vars
+				.insert(ext.name.as_str().into(), TlaArg::Import(ext.path.clone()));
 		}
 		Ok(Some(ctx))
 	}
modifiedcrates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,12 +1,5 @@
 use clap::Parser;
-use jrsonnet_evaluator::{
-	error::{ErrorKind, Result},
-	function::TlaArg,
-	gc::WithCapacityExt as _,
-	rustc_hash::FxHashMap,
-	IStr,
-};
-use jrsonnet_parser::{ParserSettings, Source};
+use jrsonnet_evaluator::{IStr, error::Result, function::TlaArg, gc::WithCapacityExt as _, rustc_hash::FxHashMap};
 
 use crate::{ExtFile, ExtStr};
 
@@ -35,37 +28,27 @@
 impl TlaOpts {
 	pub fn tla_opts(&self) -> Result<FxHashMap<IStr, TlaArg>> {
 		let mut out = FxHashMap::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 ext in &self.tla_str {
+			out.insert(
+				ext.name.as_str().into(),
+				TlaArg::String(ext.value.as_str().into()),
+			);
 		}
-		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());
+		for ext in &self.tla_str_file {
 			out.insert(
-				(name as &str).into(),
-				TlaArg::Code(
-					jrsonnet_parser::parse(
-						code,
-						&ParserSettings {
-							source: source.clone(),
-						},
-					)
-					.map_err(|e| ErrorKind::ImportSyntaxError {
-						path: source,
-						error: Box::new(e),
-					})?,
-				),
+				ext.name.as_str().into(),
+				TlaArg::ImportStr(ext.name.as_str().into()),
+			);
+		}
+		for ext in &self.tla_code {
+			out.insert(
+				ext.name.as_str().into(),
+				TlaArg::InlineCode(ext.value.clone()),
 			);
 		}
+		for ext in &self.tla_code_file {
+			out.insert(ext.name.as_str().into(), TlaArg::Import(ext.path.clone()));
+		}
 		Ok(out)
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/async_import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/async_import.rs
+++ b/crates/jrsonnet-evaluator/src/async_import.rs
@@ -1,7 +1,6 @@
-use std::{any::Any, cell::RefCell, future::Future, path::Path};
+use std::{any::Any, cell::RefCell, future::Future};
 
 use jrsonnet_gcmodule::Acyclic;
-use jrsonnet_interner::IStr;
 use jrsonnet_parser::{
 	ArgsDesc, AssertStmt, BindSpec, CompSpec, Destruct, Expr, FieldMember, FieldName, ForSpecData,
 	IfSpecData, LocExpr, Member, ObjBody, Param, ParamsDesc, ParserSettings, SliceDesc, Source,
@@ -9,10 +8,10 @@
 };
 use rustc_hash::FxHashMap;
 
-use crate::{bail, FileData, ImportResolver, State};
+use crate::{AsPathLike, FileData, ImportResolver, ResolvePathOwned, State};
 
 pub struct Import {
-	path: IStr,
+	path: ResolvePathOwned,
 	expression: bool,
 }
 
@@ -137,7 +136,7 @@
 		Expr::Import(v) | Expr::ImportStr(v) | Expr::ImportBin(v) => {
 			if let Expr::Str(s) = &*v.expr() {
 				out.0.push(Import {
-					path: s.clone(),
+					path: ResolvePathOwned::Str(s.to_string()),
 					expression: matches!(&*expr.expr(), Expr::Import(_)),
 				});
 			}
@@ -229,16 +228,14 @@
 	fn resolve_from(
 		&self,
 		from: &SourcePath,
-		path: &str,
+		path: &dyn AsPathLike,
 	) -> impl Future<Output = Result<SourcePath, Self::Error>>;
 	fn resolve_from_default(
 		&self,
-		path: &str,
+		path: &dyn AsPathLike,
 	) -> impl Future<Output = Result<SourcePath, Self::Error>> {
 		async { self.resolve_from(&SourcePath::default(), path).await }
 	}
-	/// Resolves absolute path, doesn't supports jpath and other fancy things
-	fn resolve(&self, path: &Path) -> impl Future<Output = Result<SourcePath, Self::Error>>;
 
 	/// Load resolved file
 	/// This should only be called with value returned
@@ -253,31 +250,25 @@
 
 #[derive(Acyclic)]
 struct ResolvedImportResolver {
-	resolved: RefCell<FxHashMap<(SourcePath, IStr), (SourcePath, bool)>>,
+	resolved: RefCell<FxHashMap<(SourcePath, ResolvePathOwned), (SourcePath, bool)>>,
 }
 impl ImportResolver for ResolvedImportResolver {
 	fn load_file_contents(&self, _resolved: &SourcePath) -> crate::Result<Vec<u8>> {
 		unreachable!("all files should be loaded at this point");
 	}
 
-	fn resolve_from(&self, from: &SourcePath, path: &str) -> crate::Result<SourcePath> {
+	fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> crate::Result<SourcePath> {
 		Ok(self
 			.resolved
 			.borrow()
-			.get(&(from.clone(), path.into()))
+			.get(&(from.clone(), path.as_path().to_owned()))
 			.expect("all imports should be resolved at this point")
 			.0
 			.clone())
 	}
 
-	fn resolve_from_default(&self, path: &str) -> crate::Result<SourcePath> {
+	fn resolve_from_default(&self, path: &dyn AsPathLike) -> crate::Result<SourcePath> {
 		self.resolve_from(&SourcePath::default(), path)
-	}
-
-	fn resolve(&self, path: &Path) -> crate::Result<SourcePath> {
-		bail!(crate::error::ErrorKind::AbsoluteImportNotSupported(
-			path.to_owned()
-		))
 	}
 }
 
@@ -288,7 +279,7 @@
 }
 
 #[allow(clippy::future_not_send)]
-pub async fn async_import<H>(s: State, handler: H, path: impl AsRef<Path>) -> Result<(), H::Error>
+pub async fn async_import<H>(s: State, handler: H, path: &dyn AsPathLike) -> Result<(), H::Error>
 where
 	H: AsyncImportResolver,
 {
@@ -299,7 +290,7 @@
 	let mut resolved_map = resolved.resolved.borrow_mut();
 
 	let mut queue = vec![Job::LoadFile {
-		path: handler.resolve(path.as_ref()).await?,
+		path: handler.resolve_from_default(path).await?,
 		parse: true,
 	}];
 	while let Some(job) = queue.pop() {
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -2,7 +2,6 @@
 	cmp::Ordering,
 	convert::Infallible,
 	fmt::{Debug, Display},
-	path::PathBuf,
 };
 
 use jrsonnet_gcmodule::Trace;
@@ -16,7 +15,7 @@
 	stdlib::format::FormatError,
 	typed::TypeLocError,
 	val::ConvertNumValueError,
-	ObjValue,
+	ObjValue, ResolvePathOwned,
 };
 
 pub(crate) fn format_found(list: &[IStr], what: &str) -> String {
@@ -180,9 +179,7 @@
 	StandaloneSuper,
 
 	#[error("can't resolve {1} from {0}")]
-	ImportFileNotFound(SourcePath, String),
-	#[error("can't resolve absolute {0}")]
-	AbsoluteImportFileNotFound(PathBuf),
+	ImportFileNotFound(SourcePath, ResolvePathOwned),
 	#[error("resolved file not found: {:?}", .0)]
 	ResolvedFileNotFound(SourcePath),
 	#[error("can't import {0}: is a directory")]
@@ -192,9 +189,7 @@
 	#[error("import io error: {0}")]
 	ImportIo(String),
 	#[error("tried to import {1} from {0}, but imports are not supported")]
-	ImportNotSupported(SourcePath, String),
-	#[error("tried to import {0}, but absolute imports are not supported")]
-	AbsoluteImportNotSupported(PathBuf),
+	ImportNotSupported(SourcePath, ResolvePathOwned),
 	#[error("can't import from virtual file")]
 	CantImportFromVirtualFile,
 	#[error(
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -682,7 +682,7 @@
 			};
 			let tmp = loc.clone().0;
 			let s = ctx.state();
-			let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;
+			let resolved_path = s.resolve_from(tmp.source_path(), path)?;
 			match i {
 				Import(_) => in_frame(
 					CallLocation::new(&loc),
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/function/arglike.rs
1use std::collections::HashMap;23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::IStr;5use jrsonnet_parser::{ArgsDesc, LocExpr};67use crate::{evaluate, typed::Typed, Context, Result, Thunk, Val};89/// Marker for arguments, which can be evaluated with context set to None10pub trait OptionalContext {}1112pub trait ArgLike {13	fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>>;14}1516impl ArgLike for &LocExpr {17	fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {18		Ok(if tailstrict {19			Thunk::evaluated(evaluate(ctx, self)?)20		} else {21			let expr = (*self).clone();22			Thunk!(move || evaluate(ctx, &expr))23		})24	}25}2627impl<T> ArgLike for T28where29	T: Typed + Clone,30{31	fn evaluate_arg(&self, _ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {32		if T::provides_lazy() && !tailstrict {33			return Ok(T::into_lazy_untyped(self.clone()));34		}35		let val = T::into_untyped(self.clone())?;36		Ok(Thunk::evaluated(val))37	}38}39impl<T> OptionalContext for T where T: Typed + Clone {}4041#[derive(Clone, Trace)]42pub enum TlaArg {43	String(IStr),44	Code(LocExpr),45	Val(Val),46	Lazy(Thunk<Val>),47}48impl ArgLike for TlaArg {49	fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {50		match self {51			Self::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),52			Self::Code(code) => Ok(if tailstrict {53				Thunk::evaluated(evaluate(ctx, code)?)54			} else {55				let code = code.clone();56				Thunk!(move || evaluate(ctx, &code))57			}),58			Self::Val(val) => Ok(Thunk::evaluated(val.clone())),59			Self::Lazy(lazy) => Ok(lazy.clone()),60		}61	}62}6364pub trait ArgsLike {65	fn unnamed_len(&self) -> usize;66	fn unnamed_iter(67		&self,68		ctx: Context,69		tailstrict: bool,70		handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,71	) -> Result<()>;72	fn named_iter(73		&self,74		ctx: Context,75		tailstrict: bool,76		handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,77	) -> Result<()>;78	fn named_names(&self, handler: &mut dyn FnMut(&IStr));79	fn is_empty(&self) -> bool;80}8182impl ArgsLike for Vec<Val> {83	fn unnamed_len(&self) -> usize {84		self.len()85	}86	fn unnamed_iter(87		&self,88		_ctx: Context,89		_tailstrict: bool,90		handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,91	) -> Result<()> {92		for (idx, el) in self.iter().enumerate() {93			handler(idx, Thunk::evaluated(el.clone()))?;94		}95		Ok(())96	}97	fn named_iter(98		&self,99		_ctx: Context,100		_tailstrict: bool,101		_handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,102	) -> Result<()> {103		Ok(())104	}105	fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}106	fn is_empty(&self) -> bool {107		self.is_empty()108	}109}110111impl ArgsLike for ArgsDesc {112	fn unnamed_len(&self) -> usize {113		self.unnamed.len()114	}115116	fn unnamed_iter(117		&self,118		ctx: Context,119		tailstrict: bool,120		handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,121	) -> Result<()> {122		for (id, arg) in self.unnamed.iter().enumerate() {123			handler(124				id,125				if tailstrict {126					Thunk::evaluated(evaluate(ctx.clone(), arg)?)127				} else {128					let ctx = ctx.clone();129					let arg = arg.clone();130131					Thunk!(move || evaluate(ctx, &arg))132				},133			)?;134		}135		Ok(())136	}137138	fn named_iter(139		&self,140		ctx: Context,141		tailstrict: bool,142		handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,143	) -> Result<()> {144		for (name, arg) in &self.named {145			handler(146				name,147				if tailstrict {148					Thunk::evaluated(evaluate(ctx.clone(), arg)?)149				} else {150					let ctx = ctx.clone();151					let arg = arg.clone();152153					Thunk!(move || evaluate(ctx, &arg))154				},155			)?;156		}157		Ok(())158	}159160	fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {161		for (name, _) in &self.named {162			handler(name);163		}164	}165166	fn is_empty(&self) -> bool {167		self.unnamed.is_empty() && self.named.is_empty()168	}169}170171impl<V: ArgLike, S> ArgsLike for HashMap<IStr, V, S> {172	fn unnamed_len(&self) -> usize {173		0174	}175176	fn unnamed_iter(177		&self,178		_ctx: Context,179		_tailstrict: bool,180		_handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,181	) -> Result<()> {182		Ok(())183	}184185	fn named_iter(186		&self,187		ctx: Context,188		tailstrict: bool,189		handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,190	) -> Result<()> {191		for (name, value) in self {192			handler(name, value.evaluate_arg(ctx.clone(), tailstrict)?)?;193		}194		Ok(())195	}196197	fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {198		for (name, _) in self {199			handler(name);200		}201	}202203	fn is_empty(&self) -> bool {204		self.is_empty()205	}206}207impl<V, S> OptionalContext for HashMap<IStr, V, S> where V: ArgLike + OptionalContext {}208209macro_rules! impl_args_like {210	($count:expr; $($gen:ident)*) => {211		impl<$($gen: ArgLike,)*> ArgsLike for ($($gen,)*) {212			fn unnamed_len(&self) -> usize {213				$count214			}215			#[allow(non_snake_case, unused_assignments)]216			fn unnamed_iter(217				&self,218				ctx: Context,219				tailstrict: bool,220				handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,221			) -> Result<()> {222				let mut i = 0usize;223				let ($($gen,)*) = self;224				$(225					handler(i, $gen.evaluate_arg(ctx.clone(), tailstrict)?)?;226					i+=1;227				)*228				Ok(())229			}230			fn named_iter(231				&self,232				_ctx: Context,233				_tailstrict: bool,234				_handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,235			) -> Result<()> {236				Ok(())237			}238			fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}239240			fn is_empty(&self) -> bool {241				// impl_args_like only implements non-empty tuples.242				false243			}244		}245		impl<$($gen: ArgLike,)*> OptionalContext for ($($gen,)*) where $($gen: OptionalContext),* {}246	};247	($count:expr; $($cur:ident)* @ $c:ident $($rest:ident)*) => {248		impl_args_like!($count; $($cur)*);249		impl_args_like!($count + 1usize; $($cur)* $c @ $($rest)*);250	};251	($count:expr; $($cur:ident)* @) => {252		impl_args_like!($count; $($cur)*);253	}254}255impl_args_like! {256	// First argument is already in position, so count starts from 1257	1usize; A @ B C D E F G H I J K L258}259260impl ArgsLike for () {261	fn unnamed_len(&self) -> usize {262		0263	}264265	fn unnamed_iter(266		&self,267		_ctx: Context,268		_tailstrict: bool,269		_handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,270	) -> Result<()> {271		Ok(())272	}273274	fn named_iter(275		&self,276		_ctx: Context,277		_tailstrict: bool,278		_handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,279	) -> Result<()> {280		Ok(())281	}282283	fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}284	fn is_empty(&self) -> bool {285		true286	}287}288impl OptionalContext for () {}
after · crates/jrsonnet-evaluator/src/function/arglike.rs
1use std::collections::HashMap;23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::IStr;5use jrsonnet_parser::{ArgsDesc, LocExpr, SourceFifo, SourcePath};67use crate::{evaluate, typed::Typed, Context, Result, Thunk, Val};89/// Marker for arguments, which can be evaluated with context set to None10pub trait OptionalContext {}1112pub trait ArgLike {13	fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>>;14}1516impl ArgLike for &LocExpr {17	fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {18		Ok(if tailstrict {19			Thunk::evaluated(evaluate(ctx, self)?)20		} else {21			let expr = (*self).clone();22			Thunk!(move || evaluate(ctx, &expr))23		})24	}25}2627impl<T> ArgLike for T28where29	T: Typed + Clone,30{31	fn evaluate_arg(&self, _ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {32		if T::provides_lazy() && !tailstrict {33			return Ok(T::into_lazy_untyped(self.clone()));34		}35		let val = T::into_untyped(self.clone())?;36		Ok(Thunk::evaluated(val))37	}38}39impl<T> OptionalContext for T where T: Typed + Clone {}4041#[derive(Clone, Trace)]42pub enum TlaArg {43	String(IStr),44	Val(Val),45	Lazy(Thunk<Val>),46	Import(String),47	ImportStr(String),48	InlineCode(String),49}50impl ArgLike for TlaArg {51	fn evaluate_arg(&self, ctx: Context, _tailstrict: bool) -> Result<Thunk<Val>> {52		match self {53			Self::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),54			Self::Val(val) => Ok(Thunk::evaluated(val.clone())),55			Self::Lazy(lazy) => Ok(lazy.clone()),56			Self::Import(p) => {57				let resolved = ctx.state().resolve_from_default(&p.as_str())?;58				Ok(Thunk!(move || ctx.state().import_resolved(resolved)))59			}60			Self::ImportStr(p) => {61				let resolved = ctx.state().resolve_from_default(&p.as_str())?;62				Ok(Thunk!(move || ctx63					.state()64					.import_resolved_str(resolved)65					.map(Val::string)))66			}67			Self::InlineCode(p) => {68				let resolved =69					SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));70				Ok(Thunk!(move || ctx.state().import_resolved(resolved)))71			}72		}73	}74}7576pub trait ArgsLike {77	fn unnamed_len(&self) -> usize;78	fn unnamed_iter(79		&self,80		ctx: Context,81		tailstrict: bool,82		handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,83	) -> Result<()>;84	fn named_iter(85		&self,86		ctx: Context,87		tailstrict: bool,88		handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,89	) -> Result<()>;90	fn named_names(&self, handler: &mut dyn FnMut(&IStr));91	fn is_empty(&self) -> bool;92}9394impl ArgsLike for Vec<Val> {95	fn unnamed_len(&self) -> usize {96		self.len()97	}98	fn unnamed_iter(99		&self,100		_ctx: Context,101		_tailstrict: bool,102		handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,103	) -> Result<()> {104		for (idx, el) in self.iter().enumerate() {105			handler(idx, Thunk::evaluated(el.clone()))?;106		}107		Ok(())108	}109	fn named_iter(110		&self,111		_ctx: Context,112		_tailstrict: bool,113		_handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,114	) -> Result<()> {115		Ok(())116	}117	fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}118	fn is_empty(&self) -> bool {119		self.is_empty()120	}121}122123impl ArgsLike for ArgsDesc {124	fn unnamed_len(&self) -> usize {125		self.unnamed.len()126	}127128	fn unnamed_iter(129		&self,130		ctx: Context,131		tailstrict: bool,132		handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,133	) -> Result<()> {134		for (id, arg) in self.unnamed.iter().enumerate() {135			handler(136				id,137				if tailstrict {138					Thunk::evaluated(evaluate(ctx.clone(), arg)?)139				} else {140					let ctx = ctx.clone();141					let arg = arg.clone();142143					Thunk!(move || evaluate(ctx, &arg))144				},145			)?;146		}147		Ok(())148	}149150	fn named_iter(151		&self,152		ctx: Context,153		tailstrict: bool,154		handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,155	) -> Result<()> {156		for (name, arg) in &self.named {157			handler(158				name,159				if tailstrict {160					Thunk::evaluated(evaluate(ctx.clone(), arg)?)161				} else {162					let ctx = ctx.clone();163					let arg = arg.clone();164165					Thunk!(move || evaluate(ctx, &arg))166				},167			)?;168		}169		Ok(())170	}171172	fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {173		for (name, _) in &self.named {174			handler(name);175		}176	}177178	fn is_empty(&self) -> bool {179		self.unnamed.is_empty() && self.named.is_empty()180	}181}182183impl<V: ArgLike, S> ArgsLike for HashMap<IStr, V, S> {184	fn unnamed_len(&self) -> usize {185		0186	}187188	fn unnamed_iter(189		&self,190		_ctx: Context,191		_tailstrict: bool,192		_handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,193	) -> Result<()> {194		Ok(())195	}196197	fn named_iter(198		&self,199		ctx: Context,200		tailstrict: bool,201		handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,202	) -> Result<()> {203		for (name, value) in self {204			handler(name, value.evaluate_arg(ctx.clone(), tailstrict)?)?;205		}206		Ok(())207	}208209	fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {210		for (name, _) in self {211			handler(name);212		}213	}214215	fn is_empty(&self) -> bool {216		self.is_empty()217	}218}219impl<V, S> OptionalContext for HashMap<IStr, V, S> where V: ArgLike + OptionalContext {}220221macro_rules! impl_args_like {222	($count:expr; $($gen:ident)*) => {223		impl<$($gen: ArgLike,)*> ArgsLike for ($($gen,)*) {224			fn unnamed_len(&self) -> usize {225				$count226			}227			#[allow(non_snake_case, unused_assignments)]228			fn unnamed_iter(229				&self,230				ctx: Context,231				tailstrict: bool,232				handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,233			) -> Result<()> {234				let mut i = 0usize;235				let ($($gen,)*) = self;236				$(237					handler(i, $gen.evaluate_arg(ctx.clone(), tailstrict)?)?;238					i+=1;239				)*240				Ok(())241			}242			fn named_iter(243				&self,244				_ctx: Context,245				_tailstrict: bool,246				_handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,247			) -> Result<()> {248				Ok(())249			}250			fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}251252			fn is_empty(&self) -> bool {253				// impl_args_like only implements non-empty tuples.254				false255			}256		}257		impl<$($gen: ArgLike,)*> OptionalContext for ($($gen,)*) where $($gen: OptionalContext),* {}258	};259	($count:expr; $($cur:ident)* @ $c:ident $($rest:ident)*) => {260		impl_args_like!($count; $($cur)*);261		impl_args_like!($count + 1usize; $($cur)* $c @ $($rest)*);262	};263	($count:expr; $($cur:ident)* @) => {264		impl_args_like!($count; $($cur)*);265	}266}267impl_args_like! {268	// First argument is already in position, so count starts from 1269	1usize; A @ B C D E F G H I J K L270}271272impl ArgsLike for () {273	fn unnamed_len(&self) -> usize {274		0275	}276277	fn unnamed_iter(278		&self,279		_ctx: Context,280		_tailstrict: bool,281		_handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,282	) -> Result<()> {283		Ok(())284	}285286	fn named_iter(287		&self,288		_ctx: Context,289		_tailstrict: bool,290		_handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,291	) -> Result<()> {292		Ok(())293	}294295	fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}296	fn is_empty(&self) -> bool {297		true298	}299}300impl OptionalContext for () {}
modifiedcrates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -1,7 +1,8 @@
 use std::{
 	any::Any,
+	borrow::Cow,
 	env::current_dir,
-	fs,
+	fmt, fs,
 	io::{ErrorKind, Read},
 	path::{Path, PathBuf},
 };
@@ -9,12 +10,85 @@
 use fs::File;
 use jrsonnet_gcmodule::Acyclic;
 use jrsonnet_interner::IBytes;
-use jrsonnet_parser::{SourceDirectory, SourceFifo, SourceFile, SourcePath};
+use jrsonnet_parser::{IStr, SourceDirectory, SourceFifo, SourceFile, SourcePath};
 
 use crate::{
 	bail,
 	error::{ErrorKind::*, Result},
 };
+#[derive(Clone, Debug, Acyclic, Eq, Hash, PartialEq)]
+pub enum ResolvePathOwned {
+	Str(String),
+	Path(PathBuf),
+}
+impl fmt::Display for ResolvePathOwned {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		match self {
+			ResolvePathOwned::Str(s) => write!(f, "{s}"),
+			ResolvePathOwned::Path(p) => write!(f, "{}", p.display()),
+		}
+	}
+}
+#[derive(Clone, Copy)]
+pub enum ResolvePath<'s> {
+	Str(&'s str),
+	Path(&'s Path),
+}
+impl ResolvePath<'_> {
+	pub fn to_owned(self) -> ResolvePathOwned {
+		match self {
+			ResolvePath::Str(s) => ResolvePathOwned::Str(s.to_owned()),
+			ResolvePath::Path(p) => ResolvePathOwned::Path(p.to_owned()),
+		}
+	}
+}
+impl AsRef<Path> for ResolvePath<'_> {
+	fn as_ref(&self) -> &Path {
+		match self {
+			ResolvePath::Str(s) => s.as_ref(),
+			ResolvePath::Path(p) => p,
+		}
+	}
+}
+pub trait AsPathLike {
+	fn as_path(&self) -> ResolvePath<'_>;
+}
+impl<T> AsPathLike for &T
+where
+	T: AsPathLike + ?Sized,
+{
+	fn as_path(&self) -> ResolvePath<'_> {
+		(*self).as_path()
+	}
+}
+impl AsPathLike for str {
+	fn as_path(&self) -> ResolvePath<'_> {
+		ResolvePath::Str(self)
+	}
+}
+impl AsPathLike for IStr {
+	fn as_path(&self) -> ResolvePath<'_> {
+		ResolvePath::Str(self)
+	}
+}
+impl AsPathLike for Cow<'_, Path> {
+	fn as_path(&self) -> ResolvePath<'_> {
+		ResolvePath::Path(self.as_ref())
+	}
+}
+impl AsPathLike for Path {
+	fn as_path(&self) -> ResolvePath<'_> {
+		ResolvePath::Path(self)
+	}
+}
+impl AsPathLike for ResolvePathOwned {
+	fn as_path(&self) -> ResolvePath<'_> {
+		match self {
+			ResolvePathOwned::Str(s) => ResolvePath::Str(s),
+			ResolvePathOwned::Path(path_buf) => ResolvePath::Path(path_buf),
+		}
+	}
+}
 
 /// Implements file resolution logic for `import` and `importStr`
 pub trait ImportResolver: Acyclic + Any {
@@ -24,15 +98,11 @@
 	///
 	/// `from` should only be returned from [`ImportResolver::resolve`], or from other defined file, any other value
 	/// may result in panic
-	fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
-		bail!(ImportNotSupported(from.clone(), path.into()))
+	fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {
+		bail!(ImportNotSupported(from.clone(), path.as_path().to_owned()))
 	}
-	fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+	fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {
 		self.resolve_from(&SourcePath::default(), path)
-	}
-	/// Resolves absolute path, doesn't supports jpath and other fancy things
-	fn resolve(&self, path: &Path) -> Result<SourcePath> {
-		bail!(AbsoluteImportNotSupported(path.to_owned()))
 	}
 
 	/// Load resolved file
@@ -105,7 +175,8 @@
 }
 
 impl ImportResolver for FileImportResolver {
-	fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
+	fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {
+		let path = path.as_path();
 		let mut direct = if let Some(f) = from.downcast_ref::<SourceFile>() {
 			let mut o = f.path().to_owned();
 			o.pop();
@@ -130,12 +201,6 @@
 			}
 		}
 		bail!(ImportFileNotFound(from.clone(), path.to_owned()))
-	}
-	fn resolve(&self, path: &Path) -> Result<SourcePath> {
-		let Some(source) = check_path(path)? else {
-			bail!(AbsoluteImportFileNotFound(path.to_owned()))
-		};
-		Ok(source)
 	}
 
 	fn load_file_contents(&self, id: &SourcePath) -> Result<Vec<u8>> {
@@ -155,7 +220,7 @@
 		Ok(out)
 	}
 
-	fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+	fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {
 		self.resolve_from(&SourcePath::default(), path)
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -29,7 +29,6 @@
 	cell::{RefCell, RefMut},
 	collections::hash_map::Entry,
 	fmt::{self, Debug},
-	path::Path,
 	rc::Rc,
 };
 
@@ -349,12 +348,12 @@
 	}
 
 	/// Has same semantics as `import 'path'` called from `from` file
-	pub fn import_from(&self, from: &SourcePath, path: &str) -> Result<Val> {
-		let resolved = self.resolve_from(from, path)?;
+	pub fn import_from(&self, from: &SourcePath, path: impl AsPathLike) -> Result<Val> {
+		let resolved = self.resolve_from(from, &path)?;
 		self.import_resolved(resolved)
 	}
-	pub fn import(&self, path: impl AsRef<Path>) -> Result<Val> {
-		let resolved = self.resolve(path)?;
+	pub fn import(&self, path: impl AsPathLike) -> Result<Val> {
+		let resolved = self.resolve_from_default(&path)?;
 		self.import_resolved(resolved)
 	}
 
@@ -468,14 +467,12 @@
 impl State {
 	// Only panics in case of [`ImportResolver`] contract violation
 	#[allow(clippy::missing_panics_doc)]
-	pub fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
-		self.import_resolver().resolve_from(from, path.as_ref())
+	pub fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {
+		self.import_resolver().resolve_from(from, path)
 	}
-
-	// Only panics in case of [`ImportResolver`] contract violation
 	#[allow(clippy::missing_panics_doc)]
-	pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {
-		self.import_resolver().resolve(path.as_ref())
+	pub fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {
+		self.import_resolver().resolve_from_default(path)
 	}
 	pub fn import_resolver(&self) -> &dyn ImportResolver {
 		&*self.0.import_resolver
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -12,7 +12,7 @@
 pub use encoding::*;
 pub use hash::*;
 use jrsonnet_evaluator::{
-	error::{ErrorKind::*, Result},
+	error::Result,
 	function::{CallLocation, FuncVal, TlaArg},
 	trace::PathResolver,
 	val::NumValue,
@@ -377,23 +377,11 @@
 			.ext_vars
 			.insert(name, TlaArg::String(value));
 	}
-	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {
-		let code = code.into();
-		let source = extvar_source(name, code.clone());
-		let parsed = jrsonnet_parser::parse(
-			&code,
-			&jrsonnet_parser::ParserSettings {
-				source: source.clone(),
-			},
-		)
-		.map_err(|e| ImportSyntaxError {
-			path: source,
-			error: Box::new(e),
-		})?;
+	pub fn add_ext_code(&self, name: &str, code: impl AsRef<str>) -> Result<()> {
 		// self.data_mut().volatile_files.insert(source_name, code);
 		self.settings_mut()
 			.ext_vars
-			.insert(name.into(), TlaArg::Code(parsed));
+			.insert(name.into(), TlaArg::InlineCode(code.as_ref().to_owned()));
 		Ok(())
 	}
 	pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {