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
after · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember, FieldName,7	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;10use rustc_hash::FxHashMap;1112use self::destructure::destruct;13use crate::{14	arr::ArrValue,15	bail,16	destructure::evaluate_dest,17	error::{suggest_object_fields, ErrorKind::*},18	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},19	function::{CallLocation, FuncDesc, FuncVal},20	gc::WithCapacityExt as _,21	in_frame,22	typed::Typed,23	val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},24	Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt,25	Unbound, Val,26};27pub mod destructure;28pub mod operator;2930// This is the amount of bytes that need to be left on the stack before increasing the size.31// It must be at least as large as the stack required by any code that does not call32// `ensure_sufficient_stack`.33const RED_ZONE: usize = 100 * 1024; // 100k3435// Only the first stack that is pushed, grows exponentially (2^n * STACK_PER_RECURSION) from then36// on. This flag has performance relevant characteristics. Don't set it too high.37const STACK_PER_RECURSION: usize = 1024 * 1024; // 1MB3839/// Grows the stack on demand to prevent stack overflow. Call this in strategic locations40/// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit41/// from this.42///43/// Should not be sprinkled around carelessly, as it causes a little bit of overhead.44#[inline]45pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {46	stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f)47}4849pub fn evaluate_trivial(expr: &LocExpr) -> Option<Val> {50	fn is_trivial(expr: &LocExpr) -> bool {51		match expr.expr() {52			Expr::Str(_)53			| Expr::Num(_)54			| Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,55			Expr::Arr(a) => a.iter().all(is_trivial),56			Expr::Parened(e) => is_trivial(e),57			_ => false,58		}59	}60	Some(match expr.expr() {61		Expr::Str(s) => Val::string(s.clone()),62		Expr::Num(n) => {63			Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))64		}65		Expr::Literal(LiteralType::False) => Val::Bool(false),66		Expr::Literal(LiteralType::True) => Val::Bool(true),67		Expr::Literal(LiteralType::Null) => Val::Null,68		Expr::Arr(n) => {69			if n.iter().any(|e| !is_trivial(e)) {70				return None;71			}72			Val::Arr(ArrValue::eager(73				n.iter()74					.map(evaluate_trivial)75					.map(|e| e.expect("checked trivial"))76					.collect(),77			))78		}79		Expr::Parened(e) => evaluate_trivial(e)?,80		_ => return None,81	})82}8384pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {85	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {86		name,87		ctx,88		params,89		body,90	})))91}9293pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {94	Ok(match field_name {95		FieldName::Fixed(n) => Some(n.clone()),96		FieldName::Dyn(expr) => in_frame(97			CallLocation::new(&expr.span()),98			|| "evaluating field name".to_string(),99			|| {100				let value = evaluate(ctx, expr)?;101				if matches!(value, Val::Null) {102					Ok(None)103				} else {104					Ok(Some(IStr::from_untyped(value)?))105				}106			},107		)?,108	})109}110111pub fn evaluate_comp(112	ctx: Context,113	specs: &[CompSpec],114	callback: &mut impl FnMut(Context) -> Result<()>,115) -> Result<()> {116	match specs.first() {117		None => callback(ctx)?,118		Some(CompSpec::IfSpec(IfSpecData(cond))) => {119			if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {120				evaluate_comp(ctx, &specs[1..], callback)?;121			}122		}123		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {124			Val::Arr(list) => {125				for item in list.iter_lazy() {126					let fctx = Pending::new();127					let mut new_bindings = FxHashMap::with_capacity(var.capacity_hint());128					destruct(var, item, fctx.clone(), &mut new_bindings)?;129					let ctx = ctx130						.clone()131						.extend(new_bindings, None, None, None)132						.into_future(fctx);133134					evaluate_comp(ctx, &specs[1..], callback)?;135				}136			}137			#[cfg(feature = "exp-object-iteration")]138			Val::Obj(obj) => {139				for field in obj.fields(140					// TODO: Should there be ability to preserve iteration order?141					#[cfg(feature = "exp-preserve-order")]142					false,143				) {144					let fctx = Pending::new();145					let mut new_bindings = FxHashMap::with_capacity(var.capacity_hint());146					let obj = obj.clone();147					let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![148						Thunk::evaluated(Val::string(field.clone())),149						Thunk!(move || obj.get(field).transpose().expect(150							"field exists, as field name was obtained from object.fields()",151						)),152					])));153					destruct(var, value, fctx.clone(), &mut new_bindings)?;154					let ctx = ctx155						.clone()156						.extend(new_bindings, None, None, None)157						.into_future(fctx);158159					evaluate_comp(ctx, &specs[1..], callback)?;160				}161			}162			_ => bail!(InComprehensionCanOnlyIterateOverArray),163		},164	}165	Ok(())166}167168trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}169impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}170171fn evaluate_object_locals(172	fctx: Pending<Context>,173	locals: Rc<Vec<BindSpec>>,174) -> impl CloneableUnbound<Context> {175	#[derive(Trace, Clone)]176	struct UnboundLocals {177		fctx: Pending<Context>,178		locals: Rc<Vec<BindSpec>>,179	}180	impl Unbound for UnboundLocals {181		type Bound = Context;182183		fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {184			let fctx = Context::new_future();185			let mut new_bindings =186				FxHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());187			for b in self.locals.iter() {188				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;189			}190191			let ctx = self.fctx.unwrap();192			let new_dollar = ctx.dollar().cloned().or_else(|| this.clone());193194			let ctx = ctx195				.extend(new_bindings, new_dollar, sup, this)196				.into_future(fctx);197198			Ok(ctx)199		}200	}201202	UnboundLocals { fctx, locals }203}204205pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(206	builder: &mut ObjValueBuilder,207	ctx: Context,208	uctx: B,209	field: &FieldMember,210) -> Result<()> {211	let name = evaluate_field_name(ctx, &field.name)?;212	let Some(name) = name else {213		return Ok(());214	};215216	match field {217		FieldMember {218			plus,219			params: None,220			visibility,221			value,222			..223		} => {224			#[derive(Trace)]225			struct UnboundValue<B: Trace> {226				uctx: B,227				value: LocExpr,228				name: IStr,229			}230			impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {231				type Bound = Val;232				fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {233					evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())234				}235			}236237			builder238				.field(name.clone())239				.with_add(*plus)240				.with_visibility(*visibility)241				.with_location(value.span())242				.bindable(UnboundValue {243					uctx,244					value: value.clone(),245					name,246				})?;247		}248		FieldMember {249			params: Some(params),250			visibility,251			value,252			..253		} => {254			#[derive(Trace)]255			struct UnboundMethod<B: Trace> {256				uctx: B,257				value: LocExpr,258				params: ParamsDesc,259				name: IStr,260			}261			impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {262				type Bound = Val;263				fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {264					Ok(evaluate_method(265						self.uctx.bind(sup, this)?,266						self.name.clone(),267						self.params.clone(),268						self.value.clone(),269					))270				}271			}272273			builder274				.field(name.clone())275				.with_visibility(*visibility)276				.with_location(value.span())277				.bindable(UnboundMethod {278					uctx,279					value: value.clone(),280					params: params.clone(),281					name,282				})?;283		}284	}285	Ok(())286}287288#[allow(clippy::too_many_lines)]289pub fn evaluate_member_list_object(ctx: Context, members: &[Member]) -> Result<ObjValue> {290	let mut builder = ObjValueBuilder::new();291	let locals = Rc::new(292		members293			.iter()294			.filter_map(|m| match m {295				Member::BindStmt(bind) => Some(bind.clone()),296				_ => None,297			})298			.collect::<Vec<_>>(),299	);300301	let fctx = Context::new_future();302303	// We have single context for all fields, so we can cache binds304	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));305306	for member in members {307		match member {308			Member::Field(field) => {309				evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;310			}311			Member::AssertStmt(stmt) => {312				#[derive(Trace)]313				struct ObjectAssert<B: Trace> {314					uctx: B,315					assert: AssertStmt,316				}317				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {318					fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {319						let ctx = self.uctx.bind(sup, this)?;320						evaluate_assert(ctx, &self.assert)321					}322				}323				builder.assert(ObjectAssert {324					uctx: uctx.clone(),325					assert: stmt.clone(),326				});327			}328			Member::BindStmt(_) => {329				// Already handled330			}331		}332	}333	let this = builder.build();334	fctx.fill(ctx.extend(FxHashMap::new(), None, None, Some(this.clone())));335	Ok(this)336}337338pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {339	Ok(match object {340		ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,341		ObjBody::ObjComp(obj) => {342			let mut builder = ObjValueBuilder::new();343			let locals = Rc::new(344				obj.pre_locals345					.iter()346					.chain(obj.post_locals.iter())347					.cloned()348					.collect::<Vec<_>>(),349			);350			let mut ctxs = vec![];351			evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {352				let fctx = Context::new_future();353				ctxs.push((ctx.clone(), fctx.clone()));354				let uctx = evaluate_object_locals(fctx, locals.clone());355356				evaluate_field_member(&mut builder, ctx, uctx, &obj.field)357			})?;358359			let this = builder.build();360			for (ctx, fctx) in ctxs {361				let _ctx = ctx362					.extend(FxHashMap::new(), None, None, Some(this.clone()))363					.into_future(fctx);364			}365			this366		}367	})368}369370pub fn evaluate_apply(371	ctx: Context,372	value: &LocExpr,373	args: &ArgsDesc,374	loc: CallLocation<'_>,375	tailstrict: bool,376) -> Result<Val> {377	let value = evaluate(ctx.clone(), value)?;378	Ok(match value {379		Val::Func(f) => {380			let body = || f.evaluate(ctx, loc, args, tailstrict);381			if tailstrict {382				body()?383			} else {384				in_frame(loc, || format!("function <{}> call", f.name()), body)?385			}386		}387		v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),388	})389}390391pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {392	let value = &assertion.0;393	let msg = &assertion.1;394	let assertion_result = in_frame(395		CallLocation::new(&value.span()),396		|| "assertion condition".to_owned(),397		|| bool::from_untyped(evaluate(ctx.clone(), value)?),398	)?;399	if !assertion_result {400		in_frame(401			CallLocation::new(&value.span()),402			|| "assertion failure".to_owned(),403			|| {404				if let Some(msg) = msg {405					bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));406				}407				bail!(AssertionFailed(Val::Null.to_string()?));408			},409		)?;410	}411	Ok(())412}413414pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {415	use Expr::*;416	Ok(match expr.expr() {417		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),418		_ => evaluate(ctx, expr)?,419	})420}421422#[allow(clippy::too_many_lines)]423pub fn evaluate(ctx: Context, expr: &LocExpr) -> Result<Val> {424	use Expr::*;425426	if let Some(trivial) = evaluate_trivial(expr) {427		return Ok(trivial);428	}429	let loc = expr.span();430	Ok(match expr.expr() {431		Literal(LiteralType::This) => {432			Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())433		}434		Literal(LiteralType::Super) => Val::Obj(435			ctx.super_obj().ok_or(NoSuperFound)?.with_this(436				ctx.this()437					.expect("if super exists - then this should too")438					.clone(),439			),440		),441		Literal(LiteralType::Dollar) => {442			Val::Obj(ctx.dollar().ok_or(NoTopLevelObjectFound)?.clone())443		}444		Literal(LiteralType::True) => Val::Bool(true),445		Literal(LiteralType::False) => Val::Bool(false),446		Literal(LiteralType::Null) => Val::Null,447		Parened(e) => evaluate(ctx, e)?,448		Str(v) => Val::string(v.clone()),449		Num(v) => Val::try_num(*v)?,450		// I have tried to remove special behavior from super by implementing standalone-super451		// expresion, but looks like this case still needs special treatment.452		//453		// Note that other jsonnet implementations will fail on `if value in (super)` expression,454		// because the standalone super literal is not supported, that is because in other455		// implementations `in super` treated differently from in `smth_else`.456		BinaryOp(field, BinaryOpType::In, e)457			if matches!(e.expr(), Expr::Literal(LiteralType::Super)) =>458		{459			let Some(super_obj) = ctx.super_obj() else {460				return Ok(Val::Bool(false));461			};462			let field = evaluate(ctx.clone(), field)?;463			Val::Bool(super_obj.has_field_ex(field.to_string()?, true))464		}465		BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,466		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,467		Var(name) => in_frame(468			CallLocation::new(&loc),469			|| format!("local <{name}> access"),470			|| ctx.binding(name.clone())?.evaluate(),471		)?,472		Index { indexable, parts } => ensure_sufficient_stack(|| {473			let mut parts = parts.iter();474			let mut indexable = if matches!(indexable.expr(), Expr::Literal(LiteralType::Super)) {475				let part = parts.next().expect("at least part should exist");476				let Some(super_obj) = ctx.super_obj() else {477					#[cfg(feature = "exp-null-coaelse")]478					if part.null_coaelse {479						return Ok(Val::Null);480					}481					bail!(NoSuperFound)482				};483				let name = evaluate(ctx.clone(), &part.value)?;484485				let Val::Str(name) = name else {486					bail!(ValueIndexMustBeTypeGot(487						ValType::Obj,488						ValType::Str,489						name.value_type(),490					))491				};492493				let this = ctx494					.this()495					.expect("no this found, while super present, should not happen");496				let name = name.into_flat();497				match super_obj498					.get_for(name.clone(), this.clone())499					.with_description_src(&part.value, || format!("field <{name}> access"))?500				{501					Some(v) => v,502					#[cfg(feature = "exp-null-coaelse")]503					None if part.null_coaelse => return Ok(Val::Null),504					None => {505						let suggestions = suggest_object_fields(super_obj, name.clone());506507						bail!(NoSuchField(name, suggestions))508					}509				}510			} else {511				evaluate(ctx.clone(), indexable)?512			};513514			for part in parts {515				indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {516					(Val::Obj(v), Val::Str(key)) => match v517						.get(key.clone().into_flat())518						.with_description_src(&part.value, || format!("field <{key}> access"))?519					{520						Some(v) => v,521						#[cfg(feature = "exp-null-coaelse")]522						None if part.null_coaelse => return Ok(Val::Null),523						None => {524							let suggestions = suggest_object_fields(&v, key.clone().into_flat());525526							return Err(Error::from(NoSuchField(527								key.clone().into_flat(),528								suggestions,529							)))530							.with_description_src(&part.value, || format!("field <{key}> access"));531						}532					},533					(Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(534						ValType::Obj,535						ValType::Str,536						n.value_type(),537					)),538					(Val::Arr(v), Val::Num(n)) => {539						let n = n.get();540						if n.fract() > f64::EPSILON {541							bail!(FractionalIndex)542						}543						if n < 0.0 {544							bail!(ArrayBoundsError(n as isize, v.len()));545						}546						v.get(n as usize)?547							.ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?548					}549					(Val::Arr(_), Val::Str(n)) => {550						bail!(AttemptedIndexAnArrayWithString(n.into_flat()))551					}552					(Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(553						ValType::Arr,554						ValType::Num,555						n.value_type(),556					)),557558					(Val::Str(s), Val::Num(n)) => Val::Str({559						let v: IStr = s560							.clone()561							.into_flat()562							.chars()563							.skip(n.get() as usize)564							.take(1)565							.collect::<String>()566							.into();567						if v.is_empty() {568							let size = s.into_flat().chars().count();569							bail!(StringBoundsError(n.get() as usize, size))570						}571						StrValue::Flat(v)572					}),573					(Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(574						ValType::Str,575						ValType::Num,576						n.value_type(),577					)),578					#[cfg(feature = "exp-null-coaelse")]579					(Val::Null, _) if part.null_coaelse => return Ok(Val::Null),580					(v, _) => bail!(CantIndexInto(v.value_type())),581				};582			}583			Ok(indexable)584		})?,585		LocalExpr(bindings, returned) => {586			let mut new_bindings: FxHashMap<IStr, Thunk<Val>> =587				FxHashMap::with_capacity(bindings.iter().map(BindSpec::capacity_hint).sum());588			let fctx = Context::new_future();589			for b in bindings {590				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;591			}592			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);593			evaluate(ctx, &returned.clone())?594		}595		Arr(items) => {596			if items.is_empty() {597				Val::Arr(ArrValue::empty())598			} else if items.len() == 1 {599				let item = items[0].clone();600				Val::Arr(ArrValue::lazy(vec![Thunk!(move || evaluate(ctx, &item))]))601			} else {602				Val::Arr(ArrValue::expr(ctx, items.iter().cloned()))603			}604		}605		ArrComp(expr, comp_specs) => {606			let mut out = Vec::new();607			evaluate_comp(ctx, comp_specs, &mut |ctx| {608				let expr = expr.clone();609				out.push(Thunk!(move || evaluate(ctx, &expr)));610				Ok(())611			})?;612			Val::Arr(ArrValue::lazy(out))613		}614		Obj(body) => Val::Obj(evaluate_object(ctx, body)?),615		ObjExtend(a, b) => evaluate_add_op(616			&evaluate(ctx.clone(), a)?,617			&Val::Obj(evaluate_object(ctx, b)?),618		)?,619		Apply(value, args, tailstrict) => ensure_sufficient_stack(|| {620			evaluate_apply(ctx, value, args, CallLocation::new(&loc), *tailstrict)621		})?,622		Function(params, body) => {623			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())624		}625		AssertExpr(assert, returned) => {626			evaluate_assert(ctx.clone(), assert)?;627			evaluate(ctx, returned)?628		}629		ErrorStmt(e) => in_frame(630			CallLocation::new(&loc),631			|| "error statement".to_owned(),632			|| bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),633		)?,634		IfElse {635			cond,636			cond_then,637			cond_else,638		} => {639			if in_frame(640				CallLocation::new(&loc),641				|| "if condition".to_owned(),642				|| bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),643			)? {644				evaluate(ctx, cond_then)?645			} else {646				match cond_else {647					Some(v) => evaluate(ctx, v)?,648					None => Val::Null,649				}650			}651		}652		Slice(value, desc) => {653			fn parse_idx<T: Typed>(654				loc: CallLocation<'_>,655				ctx: &Context,656				expr: Option<&LocExpr>,657				desc: &'static str,658			) -> Result<Option<T>> {659				if let Some(value) = expr {660					Ok(in_frame(661						loc,662						|| format!("slice {desc}"),663						|| <Option<T>>::from_untyped(evaluate(ctx.clone(), value)?),664					)?)665				} else {666					Ok(None)667				}668			}669670			let indexable = evaluate(ctx.clone(), value)?;671			let loc = CallLocation::new(&loc);672673			let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;674			let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;675			let step = parse_idx(loc, &ctx, desc.step.as_ref(), "step")?;676677			IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?678		}679		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {680			let Expr::Str(path) = &path.expr() else {681				bail!("computed imports are not supported")682			};683			let tmp = loc.clone().0;684			let s = ctx.state();685			let resolved_path = s.resolve_from(tmp.source_path(), path)?;686			match i {687				Import(_) => in_frame(688					CallLocation::new(&loc),689					|| format!("import {:?}", path.clone()),690					|| s.import_resolved(resolved_path),691				)?,692				ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),693				ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),694				_ => unreachable!(),695			}696		}697	})698}
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -2,7 +2,7 @@
 
 use jrsonnet_gcmodule::Trace;
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ArgsDesc, LocExpr};
+use jrsonnet_parser::{ArgsDesc, LocExpr, SourceFifo, SourcePath};
 
 use crate::{evaluate, typed::Typed, Context, Result, Thunk, Val};
 
@@ -41,22 +41,34 @@
 #[derive(Clone, Trace)]
 pub enum TlaArg {
 	String(IStr),
-	Code(LocExpr),
 	Val(Val),
 	Lazy(Thunk<Val>),
+	Import(String),
+	ImportStr(String),
+	InlineCode(String),
 }
 impl ArgLike for TlaArg {
-	fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
+	fn evaluate_arg(&self, ctx: Context, _tailstrict: bool) -> Result<Thunk<Val>> {
 		match self {
 			Self::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
-			Self::Code(code) => Ok(if tailstrict {
-				Thunk::evaluated(evaluate(ctx, code)?)
-			} else {
-				let code = code.clone();
-				Thunk!(move || evaluate(ctx, &code))
-			}),
 			Self::Val(val) => Ok(Thunk::evaluated(val.clone())),
 			Self::Lazy(lazy) => Ok(lazy.clone()),
+			Self::Import(p) => {
+				let resolved = ctx.state().resolve_from_default(&p.as_str())?;
+				Ok(Thunk!(move || ctx.state().import_resolved(resolved)))
+			}
+			Self::ImportStr(p) => {
+				let resolved = ctx.state().resolve_from_default(&p.as_str())?;
+				Ok(Thunk!(move || ctx
+					.state()
+					.import_resolved_str(resolved)
+					.map(Val::string)))
+			}
+			Self::InlineCode(p) => {
+				let resolved =
+					SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
+				Ok(Thunk!(move || ctx.state().import_resolved(resolved)))
+			}
 		}
 	}
 }
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>) {