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

difftreelog

Merge branch 'master' into gc-v2

Yaroslav Bolyukin2021-06-14parents: #a501dd9 #ff2926d.patch.diff
in: master

17 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -242,7 +242,6 @@
 dependencies = [
  "gc",
  "jrsonnet-evaluator",
- "jrsonnet-interner",
  "jrsonnet-parser",
 ]
 
modifiedbindings/jsonnet/Cargo.tomldiffbeforeafterboth
--- a/bindings/jsonnet/Cargo.toml
+++ b/bindings/jsonnet/Cargo.toml
@@ -8,7 +8,6 @@
 publish = false
 
 [dependencies]
-jrsonnet-interner = { path = "../../crates/jrsonnet-interner", version = "0.3.8" }
 jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.3.8" }
 jrsonnet-parser = { path = "../../crates/jrsonnet-parser", version = "0.3.8" }
 gc = { version = "0.4.1", features = ["derive"] }
modifiedbindings/jsonnet/src/import.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -2,9 +2,8 @@
 
 use jrsonnet_evaluator::{
 	error::{Error::*, Result},
-	throw, EvaluationState, ImportResolver,
+	throw, EvaluationState, IStr, ImportResolver,
 };
-use jrsonnet_interner::IStr;
 use std::{
 	any::Any,
 	cell::RefCell,
@@ -13,7 +12,7 @@
 	fs::File,
 	io::Read,
 	os::raw::{c_char, c_int},
-	path::PathBuf,
+	path::{Path, PathBuf},
 	ptr::null_mut,
 	rc::Rc,
 };
@@ -34,7 +33,7 @@
 	out: RefCell<HashMap<PathBuf, IStr>>,
 }
 impl ImportResolver for CallbackImportResolver {
-	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
+	fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
 		let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();
 		let rel = CString::new(path.to_str().unwrap()).unwrap().into_raw();
 		let found_here: *mut c_char = null_mut();
@@ -74,9 +73,9 @@
 			unsafe { CString::from_raw(result_ptr) };
 		}
 
-		Ok(Rc::new(found_here_buf))
+		Ok(found_here_buf.into())
 	}
-	fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr> {
+	fn load_file_contents(&self, resolved: &Path) -> Result<IStr> {
 		Ok(self.out.borrow().get(resolved).unwrap().clone())
 	}
 	unsafe fn as_any(&self) -> &dyn Any {
@@ -109,27 +108,27 @@
 	}
 }
 impl ImportResolver for NativeImportResolver {
-	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
-		let mut new_path = from.clone();
+	fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
+		let mut new_path = from.to_owned();
 		new_path.push(path);
 		if new_path.exists() {
-			Ok(Rc::new(new_path))
+			Ok(new_path.into())
 		} else {
 			for library_path in self.library_paths.borrow().iter() {
 				let mut cloned = library_path.clone();
 				cloned.push(path);
 				if cloned.exists() {
-					return Ok(Rc::new(cloned));
+					return Ok(cloned.into());
 				}
 			}
-			throw!(ImportFileNotFound(from.clone(), path.clone()))
+			throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
 		}
 	}
-	fn load_file_contents(&self, id: &PathBuf) -> Result<IStr> {
-		let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;
+	fn load_file_contents(&self, id: &Path) -> Result<IStr> {
+		let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;
 		let mut out = String::new();
 		file.read_to_string(&mut out)
-			.map_err(|_e| ImportBadFileUtf8(id.clone()))?;
+			.map_err(|_e| ImportBadFileUtf8(id.to_owned()))?;
 		Ok(out.into())
 	}
 	unsafe fn as_any(&self) -> &dyn Any {
modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -9,14 +9,12 @@
 pub mod vars_tlas;
 
 use import::NativeImportResolver;
-use jrsonnet_evaluator::{EvaluationState, ManifestFormat, Val};
-use jrsonnet_interner::IStr;
+use jrsonnet_evaluator::{EvaluationState, IStr, ManifestFormat, Val};
 use std::{
 	alloc::Layout,
 	ffi::{CStr, CString},
 	os::raw::{c_char, c_double, c_int, c_uint},
 	path::PathBuf,
-	rc::Rc,
 };
 
 /// WASM stub
@@ -145,7 +143,7 @@
 		let snippet = CStr::from_ptr(snippet);
 		match vm
 			.evaluate_snippet_raw(
-				Rc::new(PathBuf::from(filename.to_str().unwrap())),
+				PathBuf::from(filename.to_str().unwrap()).into(),
 				snippet.to_str().unwrap().into(),
 			)
 			.and_then(|v| vm.with_tla(v))
@@ -221,7 +219,7 @@
 		let snippet = CStr::from_ptr(snippet);
 		match vm
 			.evaluate_snippet_raw(
-				Rc::new(PathBuf::from(filename.to_str().unwrap())),
+				PathBuf::from(filename.to_str().unwrap()).into(),
 				snippet.to_str().unwrap().into(),
 			)
 			.and_then(|v| vm.with_tla(v))
@@ -295,7 +293,7 @@
 		let snippet = CStr::from_ptr(snippet);
 		match vm
 			.evaluate_snippet_raw(
-				Rc::new(PathBuf::from(filename.to_str().unwrap())),
+				PathBuf::from(filename.to_str().unwrap()).into(),
 				snippet.to_str().unwrap().into(),
 			)
 			.and_then(|v| vm.with_tla(v))
modifiedbindings/jsonnet/src/native.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -8,7 +8,7 @@
 use std::{
 	ffi::{c_void, CStr},
 	os::raw::{c_char, c_int},
-	path::PathBuf,
+	path::Path,
 	rc::Rc,
 };
 
@@ -27,7 +27,7 @@
 	unsafe_empty_trace!();
 }
 impl NativeCallbackHandler for JsonnetNativeCallbackHandler {
-	fn call(&self, _from: Option<Rc<PathBuf>>, args: &[Val]) -> Result<Val, LocError> {
+	fn call(&self, _from: Option<Rc<Path>>, args: &[Val]) -> Result<Val, LocError> {
 		let mut n_args = Vec::new();
 		for a in args {
 			n_args.push(Some(Box::new(a.clone())));
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -6,7 +6,6 @@
 	io::Read,
 	io::Write,
 	path::PathBuf,
-	rc::Rc,
 	str::FromStr,
 };
 
@@ -134,14 +133,14 @@
 	let val = if opts.input.exec {
 		state.set_manifest_format(ManifestFormat::ToString);
 		state.evaluate_snippet_raw(
-			Rc::new(PathBuf::from("args")),
+			PathBuf::from("args").into(),
 			(&opts.input.input as &str).into(),
 		)?
 	} else if opts.input.input == "-" {
 		let mut input = Vec::new();
 		std::io::stdin().read_to_end(&mut input)?;
 		let input_str = std::str::from_utf8(&input)?.into();
-		state.evaluate_snippet_raw(Rc::new(PathBuf::from("<stdin>")), input_str)?
+		state.evaluate_snippet_raw(PathBuf::from("<stdin>").into(), input_str)?
 	} else {
 		state.evaluate_file_raw(&PathBuf::from(opts.input.input))?
 	};
modifiedcrates/jrsonnet-evaluator/build.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/build.rs
+++ b/crates/jrsonnet-evaluator/build.rs
@@ -15,7 +15,7 @@
 	let parsed = parse(
 		STDLIB_STR,
 		&ParserSettings {
-			file_name: Rc::new(PathBuf::from("std.jsonnet")),
+			file_name: PathBuf::from("std.jsonnet").into(),
 			loc_data: true,
 		},
 	)
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -177,7 +177,7 @@
 		0, s: ty!(string) => Val::Str;
 	], {
 		let state = EvaluationState::default();
-		let path = Rc::new(PathBuf::from("std.parseJson"));
+		let path = PathBuf::from("std.parseJson").into();
 		state.evaluate_snippet_raw(path ,s)
 	})
 }
modifiedcrates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
@@ -1,5 +1,5 @@
 use jrsonnet_parser::{LocExpr, ParserSettings};
-use std::{path::PathBuf, rc::Rc};
+use std::path::PathBuf;
 
 thread_local! {
 	/// To avoid parsing again when issued from the same thread
@@ -25,7 +25,7 @@
 			jrsonnet_stdlib::STDLIB_STR,
 			&ParserSettings {
 				loc_data: true,
-				file_name: Rc::new(PathBuf::from("std.jsonnet")),
+				file_name: PathBuf::from("std.jsonnet").into(),
 			},
 		)
 		.unwrap()
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -6,7 +6,10 @@
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
 use jrsonnet_types::ValType;
-use std::{path::PathBuf, rc::Rc};
+use std::{
+	path::{Path, PathBuf},
+	rc::Rc,
+};
 use thiserror::Error;
 
 #[derive(Error, Debug, Clone, Trace, Finalize)]
@@ -87,7 +90,7 @@
 		.source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())
 	)]
 	ImportSyntaxError {
-		path: Rc<PathBuf>,
+		path: Rc<Path>,
 		source_code: IStr,
 		#[unsafe_ignore_trace]
 		error: Box<jrsonnet_parser::ParseError>,
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate.rs
1use crate::{2	equals, error::Error::*, push, throw, with_state, ArrValue, Bindable, Context, ContextCreator,3	FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue,4	ObjectAssertion, Result, Val,5};6use gc::{custom_trace, Finalize, Gc, Trace};7use jrsonnet_interner::IStr;8use jrsonnet_parser::{9	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,10	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,11	Visibility,12};13use jrsonnet_types::ValType;14use rustc_hash::{FxHashMap, FxHasher};15use std::{collections::HashMap, hash::BuildHasherDefault, rc::Rc};1617pub fn evaluate_binding_in_future(18	b: &BindSpec,19	context_creator: FutureWrapper<Context>,20) -> LazyVal {21	let b = b.clone();22	if let Some(params) = &b.params {23		let params = params.clone();2425		struct LazyMethodBinding {26			context_creator: FutureWrapper<Context>,27			name: IStr,28			params: ParamsDesc,29			value: LocExpr,30		}31		impl Finalize for LazyMethodBinding {}32		unsafe impl Trace for LazyMethodBinding {33			custom_trace!(this, {34				mark(&this.context_creator);35				mark(&this.name);36				mark(&this.params);37				mark(&this.value);38			});39		}40		impl LazyValValue for LazyMethodBinding {41			fn get(self: Box<Self>) -> Result<Val> {42				Ok(evaluate_method(43					self.context_creator.unwrap(),44					self.name,45					self.params,46					self.value,47				))48			}49		}5051		LazyVal::new(Box::new(LazyMethodBinding {52			context_creator,53			name: b.name.clone(),54			params,55			value: b.value.clone(),56		}))57	} else {58		struct LazyNamedBinding {59			context_creator: FutureWrapper<Context>,60			name: IStr,61			value: LocExpr,62		}63		impl Finalize for LazyNamedBinding {}64		unsafe impl Trace for LazyNamedBinding {65			custom_trace!(this, {66				mark(&this.context_creator);67				mark(&this.name);68				mark(&this.value);69			});70		}71		impl LazyValValue for LazyNamedBinding {72			fn get(self: Box<Self>) -> Result<Val> {73				evaluate_named(self.context_creator.unwrap(), &self.value, self.name)74			}75		}76		LazyVal::new(Box::new(LazyNamedBinding {77			context_creator,78			name: b.name.clone(),79			value: b.value,80		}))81	}82}8384pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {85	let b = b.clone();86	if let Some(params) = &b.params {87		let params = params.clone();8889		struct BindableMethodLazyVal {90			this: Option<ObjValue>,91			super_obj: Option<ObjValue>,9293			context_creator: ContextCreator,94			name: IStr,95			params: ParamsDesc,96			value: LocExpr,97		}98		impl Finalize for BindableMethodLazyVal {}99		unsafe impl Trace for BindableMethodLazyVal {100			custom_trace!(this, {101				mark(&this.this);102				mark(&this.super_obj);103				mark(&this.context_creator);104				mark(&this.name);105				mark(&this.params);106				mark(&this.value);107			});108		}109		impl LazyValValue for BindableMethodLazyVal {110			fn get(self: Box<Self>) -> Result<Val> {111				Ok(evaluate_method(112					self.context_creator.create(self.this, self.super_obj)?,113					self.name,114					self.params,115					self.value,116				))117			}118		}119120		#[derive(Trace, Finalize)]121		struct BindableMethod {122			context_creator: ContextCreator,123			name: IStr,124			params: ParamsDesc,125			value: LocExpr,126		}127		impl Bindable for BindableMethod {128			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {129				Ok(LazyVal::new(Box::new(BindableMethodLazyVal {130					this,131					super_obj,132133					context_creator: self.context_creator.clone(),134					name: self.name.clone(),135					params: self.params.clone(),136					value: self.value.clone(),137				})))138			}139		}140141		(142			b.name.clone(),143			LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {144				context_creator,145				name: b.name.clone(),146				params,147				value: b.value.clone(),148			}))),149		)150	} else {151		struct BindableNamedLazyVal {152			this: Option<ObjValue>,153			super_obj: Option<ObjValue>,154155			context_creator: ContextCreator,156			name: IStr,157			value: LocExpr,158		}159		impl Finalize for BindableNamedLazyVal {}160		unsafe impl Trace for BindableNamedLazyVal {161			custom_trace!(this, {162				mark(&this.this);163				mark(&this.super_obj);164				mark(&this.context_creator);165				mark(&this.name);166				mark(&this.value);167			});168		}169		impl LazyValValue for BindableNamedLazyVal {170			fn get(self: Box<Self>) -> Result<Val> {171				evaluate_named(172					self.context_creator.create(self.this, self.super_obj)?,173					&self.value,174					self.name,175				)176			}177		}178179		#[derive(Trace, Finalize)]180		struct BindableNamed {181			context_creator: ContextCreator,182			name: IStr,183			value: LocExpr,184		}185		impl Bindable for BindableNamed {186			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {187				Ok(LazyVal::new(Box::new(BindableNamedLazyVal {188					this,189					super_obj,190191					context_creator: self.context_creator.clone(),192					name: self.name.clone(),193					value: self.value.clone(),194				})))195			}196		}197198		(199			b.name.clone(),200			LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {201				context_creator,202				name: b.name.clone(),203				value: b.value.clone(),204			}))),205		)206	}207}208209pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {210	Val::Func(Gc::new(FuncVal::Normal(FuncDesc {211		name,212		ctx,213		params,214		body,215	})))216}217218pub fn evaluate_field_name(219	context: Context,220	field_name: &jrsonnet_parser::FieldName,221) -> Result<Option<IStr>> {222	Ok(match field_name {223		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),224		jrsonnet_parser::FieldName::Dyn(expr) => {225			let value = evaluate(context, expr)?;226			if matches!(value, Val::Null) {227				None228			} else {229				Some(value.try_cast_str("dynamic field name")?)230			}231		}232	})233}234235pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {236	Ok(match (op, b) {237		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),238		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),239		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),240		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),241	})242}243244pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {245	Ok(match (a, b) {246		(Val::DebugGcTraceValue(v1), Val::DebugGcTraceValue(v2)) => {247			evaluate_add_op(&v1.value, &v2.value)?248		}249		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),250251		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)252		(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),253		(Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),254255		(Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),256		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),257258		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),259		(Val::Arr(a), Val::Arr(b)) => {260			let mut out = Vec::with_capacity(a.len() + b.len());261			out.extend(a.iter_lazy());262			out.extend(b.iter_lazy());263			Val::Arr(out.into())264		}265		(Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,266		_ => throw!(BinaryOperatorDoesNotOperateOnValues(267			BinaryOpType::Add,268			a.value_type(),269			b.value_type(),270		)),271	})272}273274pub fn evaluate_binary_op_special(275	context: Context,276	a: &LocExpr,277	op: BinaryOpType,278	b: &LocExpr,279) -> Result<Val> {280	Ok(match (evaluate(context.clone(), a)?, op, b) {281		(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),282		(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),283		(a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,284	})285}286287pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {288	Ok(match (a, op, b) {289		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,290291		(a, BinaryOpType::Eq, b) => Val::Bool(equals(a, b)?),292		(a, BinaryOpType::Neq, b) => Val::Bool(!equals(a, b)?),293294		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),295296		// Bool X Bool297		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),298		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),299300		// Str X Str301		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),302		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),303		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),304		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),305306		// Num X Num307		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,308		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {309			if *v2 <= f64::EPSILON {310				throw!(DivisionByZero)311			}312			Val::new_checked_num(v1 / v2)?313		}314315		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,316317		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),318		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),319		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),320		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),321322		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {323			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)324		}325		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {326			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)327		}328		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {329			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)330		}331		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {332			if *v2 < 0.0 {333				throw!(RuntimeError("shift by negative exponent".into()))334			}335			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)336		}337		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {338			if *v2 < 0.0 {339				throw!(RuntimeError("shift by negative exponent".into()))340			}341			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)342		}343344		_ => throw!(BinaryOperatorDoesNotOperateOnValues(345			op,346			a.value_type(),347			b.value_type(),348		)),349	})350}351352pub fn evaluate_comp(353	context: Context,354	specs: &[CompSpec],355	callback: &mut impl FnMut(Context) -> Result<()>,356) -> Result<()> {357	match specs.get(0) {358		None => callback(context)?,359		Some(CompSpec::IfSpec(IfSpecData(cond))) => {360			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {361				evaluate_comp(context, &specs[1..], callback)?362			}363		}364		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {365			Val::Arr(list) => {366				for item in list.iter() {367					evaluate_comp(368						context.clone().with_var(var.clone(), item?.clone()),369						&specs[1..],370						callback,371					)?372				}373			}374			_ => throw!(InComprehensionCanOnlyIterateOverArray),375		},376	}377	Ok(())378}379380pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {381	let new_bindings = FutureWrapper::new();382	let future_this = FutureWrapper::new();383	let context_creator = ContextCreator(context.clone(), new_bindings.clone());384	{385		let mut bindings: FxHashMap<IStr, LazyBinding> =386			FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());387		for (n, b) in members388			.iter()389			.filter_map(|m| match m {390				Member::BindStmt(b) => Some(b.clone()),391				_ => None,392			})393			.map(|b| evaluate_binding(&b, context_creator.clone()))394		{395			bindings.insert(n, b);396		}397		new_bindings.fill(bindings);398	}399400	let mut new_members = FxHashMap::default();401	let mut assertions: Vec<Box<dyn ObjectAssertion>> = Vec::new();402	for member in members.iter() {403		match member {404			Member::Field(FieldMember {405				name,406				plus,407				params: None,408				visibility,409				value,410			}) => {411				let name = evaluate_field_name(context.clone(), name)?;412				if name.is_none() {413					continue;414				}415				let name = name.unwrap();416417				#[derive(Trace, Finalize)]418				struct ObjMemberBinding {419					context_creator: ContextCreator,420					value: LocExpr,421					name: IStr,422				}423				impl Bindable for ObjMemberBinding {424					fn bind(425						&self,426						this: Option<ObjValue>,427						super_obj: Option<ObjValue>,428					) -> Result<LazyVal> {429						Ok(LazyVal::new_resolved(evaluate_named(430							self.context_creator.create(this, super_obj)?,431							&self.value,432							self.name.clone(),433						)?))434					}435				}436				new_members.insert(437					name.clone(),438					ObjMember {439						add: *plus,440						visibility: *visibility,441						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {442							context_creator: context_creator.clone(),443							value: value.clone(),444							name,445						}))),446						location: value.1.clone(),447					},448				);449			}450			Member::Field(FieldMember {451				name,452				params: Some(params),453				value,454				..455			}) => {456				let name = evaluate_field_name(context.clone(), name)?;457				if name.is_none() {458					continue;459				}460				let name = name.unwrap();461				#[derive(Trace, Finalize)]462				struct ObjMemberBinding {463					context_creator: ContextCreator,464					value: LocExpr,465					params: ParamsDesc,466					name: IStr,467				}468				impl Bindable for ObjMemberBinding {469					fn bind(470						&self,471						this: Option<ObjValue>,472						super_obj: Option<ObjValue>,473					) -> Result<LazyVal> {474						Ok(LazyVal::new_resolved(evaluate_method(475							self.context_creator.create(this, super_obj)?,476							self.name.clone(),477							self.params.clone(),478							self.value.clone(),479						)))480					}481				}482				new_members.insert(483					name.clone(),484					ObjMember {485						add: false,486						visibility: Visibility::Hidden,487						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {488							context_creator: context_creator.clone(),489							value: value.clone(),490							params: params.clone(),491							name,492						}))),493						location: value.1.clone(),494					},495				);496			}497			Member::BindStmt(_) => {}498			Member::AssertStmt(stmt) => {499				struct ObjectAssert {500					context_creator: ContextCreator,501					assert: AssertStmt,502				}503				impl Finalize for ObjectAssert {}504				unsafe impl Trace for ObjectAssert {505					custom_trace!(this, {506						mark(&this.context_creator);507						mark(&this.assert);508					});509				}510				impl ObjectAssertion for ObjectAssert {511					fn run(512						&self,513						this: Option<ObjValue>,514						super_obj: Option<ObjValue>,515					) -> Result<()> {516						let ctx = self.context_creator.create(this, super_obj)?;517						evaluate_assert(ctx, &self.assert)518					}519				}520				assertions.push(Box::new(ObjectAssert {521					context_creator: context_creator.clone(),522					assert: stmt.clone(),523				}));524			}525		}526	}527	let this = ObjValue::new(None, Gc::new(new_members), Gc::new(assertions));528	future_this.fill(this.clone());529	Ok(this)530}531532pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {533	Ok(match object {534		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,535		ObjBody::ObjComp(obj) => {536			let future_this = FutureWrapper::new();537			let mut new_members = FxHashMap::default();538			evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {539				let new_bindings = FutureWrapper::new();540				let context_creator = ContextCreator(context.clone(), new_bindings.clone());541				let mut bindings: FxHashMap<IStr, LazyBinding> =542					FxHashMap::with_capacity_and_hasher(543						obj.pre_locals.len() + obj.post_locals.len(),544						BuildHasherDefault::default(),545					);546				for (n, b) in obj547					.pre_locals548					.iter()549					.chain(obj.post_locals.iter())550					.map(|b| evaluate_binding(b, context_creator.clone()))551				{552					bindings.insert(n, b);553				}554				new_bindings.fill(bindings.clone());555				let ctx = ctx.extend_unbound(bindings, None, None, None)?;556				let key = evaluate(ctx.clone(), &obj.key)?;557558				match key {559					Val::Null => {}560					Val::Str(n) => {561						#[derive(Trace, Finalize)]562						struct ObjCompBinding {563							context: Context,564							value: LocExpr,565						}566						impl Bindable for ObjCompBinding {567							fn bind(568								&self,569								this: Option<ObjValue>,570								_super_obj: Option<ObjValue>,571							) -> Result<LazyVal> {572								Ok(LazyVal::new_resolved(evaluate(573									self.context.clone().extend(574										FxHashMap::default(),575										None,576										this,577										None,578									),579									&self.value,580								)?))581							}582						}583						new_members.insert(584							n,585							ObjMember {586								add: false,587								visibility: Visibility::Normal,588								invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {589									context: ctx,590									value: obj.value.clone(),591								}))),592								location: obj.value.1.clone(),593							},594						);595					}596					v => throw!(FieldMustBeStringGot(v.value_type())),597				}598599				Ok(())600			})?;601602			let this = ObjValue::new(None, Gc::new(new_members), Gc::new(Vec::new()));603			future_this.fill(this.clone());604			this605		}606	})607}608609pub fn evaluate_apply(610	context: Context,611	value: &LocExpr,612	args: &ArgsDesc,613	loc: Option<&ExprLocation>,614	tailstrict: bool,615) -> Result<Val> {616	let value = evaluate(context.clone(), value)?;617	Ok(match value {618		Val::Func(f) => {619			let body = || f.evaluate(context, loc, args, tailstrict);620			if tailstrict {621				body()?622			} else {623				push(loc, || format!("function <{}> call", f.name()), body)?624			}625		}626		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),627	})628}629630pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {631	let value = &assertion.0;632	let msg = &assertion.1;633	let assertion_result = push(634		value.1.as_ref(),635		|| "assertion condition".to_owned(),636		|| {637			evaluate(context.clone(), value)?638				.try_cast_bool("assertion condition should be of type `boolean`")639		},640	)?;641	if !assertion_result {642		push(643			value.1.as_ref(),644			|| "assertion failure".to_owned(),645			|| {646				if let Some(msg) = msg {647					throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));648				} else {649					throw!(AssertionFailed(Val::Null.to_string()?));650				}651			},652		)?653	}654	Ok(())655}656657pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {658	use Expr::*;659	let LocExpr(expr, _loc) = lexpr;660	Ok(match &**expr {661		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),662		_ => evaluate(context, lexpr)?,663	})664}665666pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {667	use Expr::*;668	let LocExpr(expr, loc) = expr;669	Ok(match &**expr {670		Literal(LiteralType::This) => {671			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)672		}673		Literal(LiteralType::Super) => Val::Obj(674			context675				.super_obj()676				.clone()677				.ok_or(NoSuperFound)?678				.with_this(context.this().clone().unwrap()),679		),680		Literal(LiteralType::Dollar) => {681			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)682		}683		Literal(LiteralType::True) => Val::Bool(true),684		Literal(LiteralType::False) => Val::Bool(false),685		Literal(LiteralType::Null) => Val::Null,686		Parened(e) => evaluate(context, e)?,687		Str(v) => Val::Str(v.clone()),688		Num(v) => Val::new_checked_num(*v)?,689		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,690		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,691		Var(name) => push(692			loc.as_ref(),693			|| format!("variable <{}>", name),694			|| context.binding(name.clone())?.evaluate(),695		)?,696		Index(value, index) => {697			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {698				(Val::Obj(v), Val::Str(s)) => {699					let sn = s.clone();700					push(701						loc.as_ref(),702						|| format!("field <{}> access", sn),703						|| {704							if let Some(v) = v.get(s.clone())? {705								Ok(v)706							} else if v.get("__intrinsic_namespace__".into())?.is_some() {707								Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))708							} else {709								throw!(NoSuchField(s))710							}711						},712					)?713				}714				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(715					ValType::Obj,716					ValType::Str,717					n.value_type(),718				)),719720				(Val::Arr(v), Val::Num(n)) => {721					if n.fract() > f64::EPSILON {722						throw!(FractionalIndex)723					}724					v.get(n as usize)?725						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?726				}727				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),728				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(729					ValType::Arr,730					ValType::Num,731					n.value_type(),732				)),733734				(Val::Str(s), Val::Num(n)) => Val::Str(735					s.chars()736						.skip(n as usize)737						.take(1)738						.collect::<String>()739						.into(),740				),741				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(742					ValType::Str,743					ValType::Num,744					n.value_type(),745				)),746747				(v, _) => throw!(CantIndexInto(v.value_type())),748			}749		}750		LocalExpr(bindings, returned) => {751			let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(752				bindings.len(),753				BuildHasherDefault::<FxHasher>::default(),754			);755			let future_context = Context::new_future();756			for b in bindings {757				new_bindings.insert(758					b.name.clone(),759					evaluate_binding_in_future(b, future_context.clone()),760				);761			}762			let context = context763				.extend_bound(new_bindings)764				.into_future(future_context);765			evaluate(context, &returned.clone())?766		}767		Arr(items) => {768			let mut out = Vec::with_capacity(items.len());769			for item in items {770				// TODO: Implement ArrValue::Lazy with same context for every element?771				struct ArrayElement {772					context: Context,773					item: LocExpr,774				}775				impl Finalize for ArrayElement {}776				unsafe impl Trace for ArrayElement {777					custom_trace!(this, {778						mark(&this.context);779						mark(&this.item);780					});781				}782				impl LazyValValue for ArrayElement {783					fn get(self: Box<Self>) -> Result<Val> {784						evaluate(self.context, &self.item)785					}786				}787				out.push(LazyVal::new(Box::new(ArrayElement {788					context: context.clone(),789					item: item.clone(),790				})));791			}792			Val::Arr(out.into())793		}794		ArrComp(expr, comp_specs) => {795			let mut out = Vec::new();796			evaluate_comp(context, comp_specs, &mut |ctx| {797				out.push(evaluate(ctx, expr)?);798				Ok(())799			})?;800			Val::Arr(ArrValue::Eager(Gc::new(out)))801		}802		Obj(body) => Val::Obj(evaluate_object(context, body)?),803		ObjExtend(s, t) => evaluate_add_op(804			&evaluate(context.clone(), s)?,805			&Val::Obj(evaluate_object(context, t)?),806		)?,807		Apply(value, args, tailstrict) => {808			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?809		}810		Function(params, body) => {811			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())812		}813		Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),814		AssertExpr(assert, returned) => {815			evaluate_assert(context.clone(), assert)?;816			evaluate(context, returned)?817		}818		ErrorStmt(e) => push(819			loc.as_ref(),820			|| "error statement".to_owned(),821			|| {822				throw!(RuntimeError(823					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,824				))825			},826		)?,827		IfElse {828			cond,829			cond_then,830			cond_else,831		} => {832			if push(833				loc.as_ref(),834				|| "if condition".to_owned(),835				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),836			)? {837				evaluate(context, cond_then)?838			} else {839				match cond_else {840					Some(v) => evaluate(context, v)?,841					None => Val::Null,842				}843			}844		}845		Import(path) => {846			let mut tmp = loc847				.clone()848				.expect("imports cannot be used without loc_data")849				.0;850			let import_location = Rc::make_mut(&mut tmp);851			import_location.pop();852			push(853				loc.as_ref(),854				|| format!("import {:?}", path),855				|| with_state(|s| s.import_file(import_location, path)),856			)?857		}858		ImportStr(path) => {859			let mut tmp = loc860				.clone()861				.expect("imports cannot be used without loc_data")862				.0;863			let import_location = Rc::make_mut(&mut tmp);864			import_location.pop();865			Val::Str(with_state(|s| s.import_file_str(import_location, path))?)866		}867	})868}
after · crates/jrsonnet-evaluator/src/evaluate.rs
1use crate::{2	equals, error::Error::*, push, throw, with_state, ArrValue, Bindable, Context, ContextCreator,3	FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue,4	ObjectAssertion, Result, Val,5};6use gc::{custom_trace, Finalize, Gc, Trace};7use jrsonnet_interner::IStr;8use jrsonnet_parser::{9	ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,10	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,11	Visibility,12};13use jrsonnet_types::ValType;14use rustc_hash::{FxHashMap, FxHasher};15use std::{collections::HashMap, hash::BuildHasherDefault};1617pub fn evaluate_binding_in_future(18	b: &BindSpec,19	context_creator: FutureWrapper<Context>,20) -> LazyVal {21	let b = b.clone();22	if let Some(params) = &b.params {23		let params = params.clone();2425		struct LazyMethodBinding {26			context_creator: FutureWrapper<Context>,27			name: IStr,28			params: ParamsDesc,29			value: LocExpr,30		}31		impl Finalize for LazyMethodBinding {}32		unsafe impl Trace for LazyMethodBinding {33			custom_trace!(this, {34				mark(&this.context_creator);35				mark(&this.name);36				mark(&this.params);37				mark(&this.value);38			});39		}40		impl LazyValValue for LazyMethodBinding {41			fn get(self: Box<Self>) -> Result<Val> {42				Ok(evaluate_method(43					self.context_creator.unwrap(),44					self.name,45					self.params,46					self.value,47				))48			}49		}5051		LazyVal::new(Box::new(LazyMethodBinding {52			context_creator,53			name: b.name.clone(),54			params,55			value: b.value.clone(),56		}))57	} else {58		struct LazyNamedBinding {59			context_creator: FutureWrapper<Context>,60			name: IStr,61			value: LocExpr,62		}63		impl Finalize for LazyNamedBinding {}64		unsafe impl Trace for LazyNamedBinding {65			custom_trace!(this, {66				mark(&this.context_creator);67				mark(&this.name);68				mark(&this.value);69			});70		}71		impl LazyValValue for LazyNamedBinding {72			fn get(self: Box<Self>) -> Result<Val> {73				evaluate_named(self.context_creator.unwrap(), &self.value, self.name)74			}75		}76		LazyVal::new(Box::new(LazyNamedBinding {77			context_creator,78			name: b.name.clone(),79			value: b.value,80		}))81	}82}8384pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {85	let b = b.clone();86	if let Some(params) = &b.params {87		let params = params.clone();8889		struct BindableMethodLazyVal {90			this: Option<ObjValue>,91			super_obj: Option<ObjValue>,9293			context_creator: ContextCreator,94			name: IStr,95			params: ParamsDesc,96			value: LocExpr,97		}98		impl Finalize for BindableMethodLazyVal {}99		unsafe impl Trace for BindableMethodLazyVal {100			custom_trace!(this, {101				mark(&this.this);102				mark(&this.super_obj);103				mark(&this.context_creator);104				mark(&this.name);105				mark(&this.params);106				mark(&this.value);107			});108		}109		impl LazyValValue for BindableMethodLazyVal {110			fn get(self: Box<Self>) -> Result<Val> {111				Ok(evaluate_method(112					self.context_creator.create(self.this, self.super_obj)?,113					self.name,114					self.params,115					self.value,116				))117			}118		}119120		#[derive(Trace, Finalize)]121		struct BindableMethod {122			context_creator: ContextCreator,123			name: IStr,124			params: ParamsDesc,125			value: LocExpr,126		}127		impl Bindable for BindableMethod {128			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {129				Ok(LazyVal::new(Box::new(BindableMethodLazyVal {130					this,131					super_obj,132133					context_creator: self.context_creator.clone(),134					name: self.name.clone(),135					params: self.params.clone(),136					value: self.value.clone(),137				})))138			}139		}140141		(142			b.name.clone(),143			LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {144				context_creator,145				name: b.name.clone(),146				params,147				value: b.value.clone(),148			}))),149		)150	} else {151		struct BindableNamedLazyVal {152			this: Option<ObjValue>,153			super_obj: Option<ObjValue>,154155			context_creator: ContextCreator,156			name: IStr,157			value: LocExpr,158		}159		impl Finalize for BindableNamedLazyVal {}160		unsafe impl Trace for BindableNamedLazyVal {161			custom_trace!(this, {162				mark(&this.this);163				mark(&this.super_obj);164				mark(&this.context_creator);165				mark(&this.name);166				mark(&this.value);167			});168		}169		impl LazyValValue for BindableNamedLazyVal {170			fn get(self: Box<Self>) -> Result<Val> {171				evaluate_named(172					self.context_creator.create(self.this, self.super_obj)?,173					&self.value,174					self.name,175				)176			}177		}178179		#[derive(Trace, Finalize)]180		struct BindableNamed {181			context_creator: ContextCreator,182			name: IStr,183			value: LocExpr,184		}185		impl Bindable for BindableNamed {186			fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {187				Ok(LazyVal::new(Box::new(BindableNamedLazyVal {188					this,189					super_obj,190191					context_creator: self.context_creator.clone(),192					name: self.name.clone(),193					value: self.value.clone(),194				})))195			}196		}197198		(199			b.name.clone(),200			LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {201				context_creator,202				name: b.name.clone(),203				value: b.value.clone(),204			}))),205		)206	}207}208209pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {210	Val::Func(Gc::new(FuncVal::Normal(FuncDesc {211		name,212		ctx,213		params,214		body,215	})))216}217218pub fn evaluate_field_name(219	context: Context,220	field_name: &jrsonnet_parser::FieldName,221) -> Result<Option<IStr>> {222	Ok(match field_name {223		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),224		jrsonnet_parser::FieldName::Dyn(expr) => {225			let value = evaluate(context, expr)?;226			if matches!(value, Val::Null) {227				None228			} else {229				Some(value.try_cast_str("dynamic field name")?)230			}231		}232	})233}234235pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {236	Ok(match (op, b) {237		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),238		(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),239		(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),240		(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),241	})242}243244pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {245	Ok(match (a, b) {246		(Val::DebugGcTraceValue(v1), Val::DebugGcTraceValue(v2)) => {247			evaluate_add_op(&v1.value, &v2.value)?248		}249		(Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),250251		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)252		(Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),253		(Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),254255		(Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),256		(o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),257258		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),259		(Val::Arr(a), Val::Arr(b)) => {260			let mut out = Vec::with_capacity(a.len() + b.len());261			out.extend(a.iter_lazy());262			out.extend(b.iter_lazy());263			Val::Arr(out.into())264		}265		(Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,266		_ => throw!(BinaryOperatorDoesNotOperateOnValues(267			BinaryOpType::Add,268			a.value_type(),269			b.value_type(),270		)),271	})272}273274pub fn evaluate_binary_op_special(275	context: Context,276	a: &LocExpr,277	op: BinaryOpType,278	b: &LocExpr,279) -> Result<Val> {280	Ok(match (evaluate(context.clone(), a)?, op, b) {281		(Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),282		(Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),283		(a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,284	})285}286287pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {288	Ok(match (a, op, b) {289		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,290291		(a, BinaryOpType::Eq, b) => Val::Bool(equals(a, b)?),292		(a, BinaryOpType::Neq, b) => Val::Bool(!equals(a, b)?),293294		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),295296		// Bool X Bool297		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),298		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),299300		// Str X Str301		(Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),302		(Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),303		(Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),304		(Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),305306		// Num X Num307		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,308		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {309			if *v2 <= f64::EPSILON {310				throw!(DivisionByZero)311			}312			Val::new_checked_num(v1 / v2)?313		}314315		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,316317		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),318		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),319		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),320		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),321322		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {323			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)324		}325		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {326			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)327		}328		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {329			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)330		}331		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {332			if *v2 < 0.0 {333				throw!(RuntimeError("shift by negative exponent".into()))334			}335			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)336		}337		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {338			if *v2 < 0.0 {339				throw!(RuntimeError("shift by negative exponent".into()))340			}341			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)342		}343344		_ => throw!(BinaryOperatorDoesNotOperateOnValues(345			op,346			a.value_type(),347			b.value_type(),348		)),349	})350}351352pub fn evaluate_comp(353	context: Context,354	specs: &[CompSpec],355	callback: &mut impl FnMut(Context) -> Result<()>,356) -> Result<()> {357	match specs.get(0) {358		None => callback(context)?,359		Some(CompSpec::IfSpec(IfSpecData(cond))) => {360			if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {361				evaluate_comp(context, &specs[1..], callback)?362			}363		}364		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {365			Val::Arr(list) => {366				for item in list.iter() {367					evaluate_comp(368						context.clone().with_var(var.clone(), item?.clone()),369						&specs[1..],370						callback,371					)?372				}373			}374			_ => throw!(InComprehensionCanOnlyIterateOverArray),375		},376	}377	Ok(())378}379380pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {381	let new_bindings = FutureWrapper::new();382	let future_this = FutureWrapper::new();383	let context_creator = ContextCreator(context.clone(), new_bindings.clone());384	{385		let mut bindings: FxHashMap<IStr, LazyBinding> =386			FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());387		for (n, b) in members388			.iter()389			.filter_map(|m| match m {390				Member::BindStmt(b) => Some(b.clone()),391				_ => None,392			})393			.map(|b| evaluate_binding(&b, context_creator.clone()))394		{395			bindings.insert(n, b);396		}397		new_bindings.fill(bindings);398	}399400	let mut new_members = FxHashMap::default();401	let mut assertions: Vec<Box<dyn ObjectAssertion>> = Vec::new();402	for member in members.iter() {403		match member {404			Member::Field(FieldMember {405				name,406				plus,407				params: None,408				visibility,409				value,410			}) => {411				let name = evaluate_field_name(context.clone(), name)?;412				if name.is_none() {413					continue;414				}415				let name = name.unwrap();416417				#[derive(Trace, Finalize)]418				struct ObjMemberBinding {419					context_creator: ContextCreator,420					value: LocExpr,421					name: IStr,422				}423				impl Bindable for ObjMemberBinding {424					fn bind(425						&self,426						this: Option<ObjValue>,427						super_obj: Option<ObjValue>,428					) -> Result<LazyVal> {429						Ok(LazyVal::new_resolved(evaluate_named(430							self.context_creator.create(this, super_obj)?,431							&self.value,432							self.name.clone(),433						)?))434					}435				}436				new_members.insert(437					name.clone(),438					ObjMember {439						add: *plus,440						visibility: *visibility,441						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {442							context_creator: context_creator.clone(),443							value: value.clone(),444							name,445						}))),446						location: value.1.clone(),447					},448				);449			}450			Member::Field(FieldMember {451				name,452				params: Some(params),453				value,454				..455			}) => {456				let name = evaluate_field_name(context.clone(), name)?;457				if name.is_none() {458					continue;459				}460				let name = name.unwrap();461				#[derive(Trace, Finalize)]462				struct ObjMemberBinding {463					context_creator: ContextCreator,464					value: LocExpr,465					params: ParamsDesc,466					name: IStr,467				}468				impl Bindable for ObjMemberBinding {469					fn bind(470						&self,471						this: Option<ObjValue>,472						super_obj: Option<ObjValue>,473					) -> Result<LazyVal> {474						Ok(LazyVal::new_resolved(evaluate_method(475							self.context_creator.create(this, super_obj)?,476							self.name.clone(),477							self.params.clone(),478							self.value.clone(),479						)))480					}481				}482				new_members.insert(483					name.clone(),484					ObjMember {485						add: false,486						visibility: Visibility::Hidden,487						invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {488							context_creator: context_creator.clone(),489							value: value.clone(),490							params: params.clone(),491							name,492						}))),493						location: value.1.clone(),494					},495				);496			}497			Member::BindStmt(_) => {}498			Member::AssertStmt(stmt) => {499				struct ObjectAssert {500					context_creator: ContextCreator,501					assert: AssertStmt,502				}503				impl Finalize for ObjectAssert {}504				unsafe impl Trace for ObjectAssert {505					custom_trace!(this, {506						mark(&this.context_creator);507						mark(&this.assert);508					});509				}510				impl ObjectAssertion for ObjectAssert {511					fn run(512						&self,513						this: Option<ObjValue>,514						super_obj: Option<ObjValue>,515					) -> Result<()> {516						let ctx = self.context_creator.create(this, super_obj)?;517						evaluate_assert(ctx, &self.assert)518					}519				}520				assertions.push(Box::new(ObjectAssert {521					context_creator: context_creator.clone(),522					assert: stmt.clone(),523				}));524			}525		}526	}527	let this = ObjValue::new(None, Gc::new(new_members), Gc::new(assertions));528	future_this.fill(this.clone());529	Ok(this)530}531532pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {533	Ok(match object {534		ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,535		ObjBody::ObjComp(obj) => {536			let future_this = FutureWrapper::new();537			let mut new_members = FxHashMap::default();538			evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {539				let new_bindings = FutureWrapper::new();540				let context_creator = ContextCreator(context.clone(), new_bindings.clone());541				let mut bindings: FxHashMap<IStr, LazyBinding> =542					FxHashMap::with_capacity_and_hasher(543						obj.pre_locals.len() + obj.post_locals.len(),544						BuildHasherDefault::default(),545					);546				for (n, b) in obj547					.pre_locals548					.iter()549					.chain(obj.post_locals.iter())550					.map(|b| evaluate_binding(b, context_creator.clone()))551				{552					bindings.insert(n, b);553				}554				new_bindings.fill(bindings.clone());555				let ctx = ctx.extend_unbound(bindings, None, None, None)?;556				let key = evaluate(ctx.clone(), &obj.key)?;557558				match key {559					Val::Null => {}560					Val::Str(n) => {561						#[derive(Trace, Finalize)]562						struct ObjCompBinding {563							context: Context,564							value: LocExpr,565						}566						impl Bindable for ObjCompBinding {567							fn bind(568								&self,569								this: Option<ObjValue>,570								_super_obj: Option<ObjValue>,571							) -> Result<LazyVal> {572								Ok(LazyVal::new_resolved(evaluate(573									self.context.clone().extend(574										FxHashMap::default(),575										None,576										this,577										None,578									),579									&self.value,580								)?))581							}582						}583						new_members.insert(584							n,585							ObjMember {586								add: false,587								visibility: Visibility::Normal,588								invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {589									context: ctx,590									value: obj.value.clone(),591								}))),592								location: obj.value.1.clone(),593							},594						);595					}596					v => throw!(FieldMustBeStringGot(v.value_type())),597				}598599				Ok(())600			})?;601602			let this = ObjValue::new(None, Gc::new(new_members), Gc::new(Vec::new()));603			future_this.fill(this.clone());604			this605		}606	})607}608609pub fn evaluate_apply(610	context: Context,611	value: &LocExpr,612	args: &ArgsDesc,613	loc: Option<&ExprLocation>,614	tailstrict: bool,615) -> Result<Val> {616	let value = evaluate(context.clone(), value)?;617	Ok(match value {618		Val::Func(f) => {619			let body = || f.evaluate(context, loc, args, tailstrict);620			if tailstrict {621				body()?622			} else {623				push(loc, || format!("function <{}> call", f.name()), body)?624			}625		}626		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),627	})628}629630pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {631	let value = &assertion.0;632	let msg = &assertion.1;633	let assertion_result = push(634		value.1.as_ref(),635		|| "assertion condition".to_owned(),636		|| {637			evaluate(context.clone(), value)?638				.try_cast_bool("assertion condition should be of type `boolean`")639		},640	)?;641	if !assertion_result {642		push(643			value.1.as_ref(),644			|| "assertion failure".to_owned(),645			|| {646				if let Some(msg) = msg {647					throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));648				} else {649					throw!(AssertionFailed(Val::Null.to_string()?));650				}651			},652		)?653	}654	Ok(())655}656657pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {658	use Expr::*;659	let LocExpr(expr, _loc) = lexpr;660	Ok(match &**expr {661		Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),662		_ => evaluate(context, lexpr)?,663	})664}665666pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {667	use Expr::*;668	let LocExpr(expr, loc) = expr;669	Ok(match &**expr {670		Literal(LiteralType::This) => {671			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)672		}673		Literal(LiteralType::Super) => Val::Obj(674			context675				.super_obj()676				.clone()677				.ok_or(NoSuperFound)?678				.with_this(context.this().clone().unwrap()),679		),680		Literal(LiteralType::Dollar) => {681			Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)682		}683		Literal(LiteralType::True) => Val::Bool(true),684		Literal(LiteralType::False) => Val::Bool(false),685		Literal(LiteralType::Null) => Val::Null,686		Parened(e) => evaluate(context, e)?,687		Str(v) => Val::Str(v.clone()),688		Num(v) => Val::new_checked_num(*v)?,689		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,690		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,691		Var(name) => push(692			loc.as_ref(),693			|| format!("variable <{}>", name),694			|| context.binding(name.clone())?.evaluate(),695		)?,696		Index(value, index) => {697			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {698				(Val::Obj(v), Val::Str(s)) => {699					let sn = s.clone();700					push(701						loc.as_ref(),702						|| format!("field <{}> access", sn),703						|| {704							if let Some(v) = v.get(s.clone())? {705								Ok(v)706							} else if v.get("__intrinsic_namespace__".into())?.is_some() {707								Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))708							} else {709								throw!(NoSuchField(s))710							}711						},712					)?713				}714				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(715					ValType::Obj,716					ValType::Str,717					n.value_type(),718				)),719720				(Val::Arr(v), Val::Num(n)) => {721					if n.fract() > f64::EPSILON {722						throw!(FractionalIndex)723					}724					v.get(n as usize)?725						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?726				}727				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),728				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(729					ValType::Arr,730					ValType::Num,731					n.value_type(),732				)),733734				(Val::Str(s), Val::Num(n)) => Val::Str(735					s.chars()736						.skip(n as usize)737						.take(1)738						.collect::<String>()739						.into(),740				),741				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(742					ValType::Str,743					ValType::Num,744					n.value_type(),745				)),746747				(v, _) => throw!(CantIndexInto(v.value_type())),748			}749		}750		LocalExpr(bindings, returned) => {751			let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(752				bindings.len(),753				BuildHasherDefault::<FxHasher>::default(),754			);755			let future_context = Context::new_future();756			for b in bindings {757				new_bindings.insert(758					b.name.clone(),759					evaluate_binding_in_future(b, future_context.clone()),760				);761			}762			let context = context763				.extend_bound(new_bindings)764				.into_future(future_context);765			evaluate(context, &returned.clone())?766		}767		Arr(items) => {768			let mut out = Vec::with_capacity(items.len());769			for item in items {770				// TODO: Implement ArrValue::Lazy with same context for every element?771				struct ArrayElement {772					context: Context,773					item: LocExpr,774				}775				impl Finalize for ArrayElement {}776				unsafe impl Trace for ArrayElement {777					custom_trace!(this, {778						mark(&this.context);779						mark(&this.item);780					});781				}782				impl LazyValValue for ArrayElement {783					fn get(self: Box<Self>) -> Result<Val> {784						evaluate(self.context, &self.item)785					}786				}787				out.push(LazyVal::new(Box::new(ArrayElement {788					context: context.clone(),789					item: item.clone(),790				})));791			}792			Val::Arr(out.into())793		}794		ArrComp(expr, comp_specs) => {795			let mut out = Vec::new();796			evaluate_comp(context, comp_specs, &mut |ctx| {797				out.push(evaluate(ctx, expr)?);798				Ok(())799			})?;800			Val::Arr(ArrValue::Eager(Gc::new(out)))801		}802		Obj(body) => Val::Obj(evaluate_object(context, body)?),803		ObjExtend(s, t) => evaluate_add_op(804			&evaluate(context.clone(), s)?,805			&Val::Obj(evaluate_object(context, t)?),806		)?,807		Apply(value, args, tailstrict) => {808			evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?809		}810		Function(params, body) => {811			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())812		}813		Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),814		AssertExpr(assert, returned) => {815			evaluate_assert(context.clone(), assert)?;816			evaluate(context, returned)?817		}818		ErrorStmt(e) => push(819			loc.as_ref(),820			|| "error statement".to_owned(),821			|| {822				throw!(RuntimeError(823					evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,824				))825			},826		)?,827		IfElse {828			cond,829			cond_then,830			cond_else,831		} => {832			if push(833				loc.as_ref(),834				|| "if condition".to_owned(),835				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),836			)? {837				evaluate(context, cond_then)?838			} else {839				match cond_else {840					Some(v) => evaluate(context, v)?,841					None => Val::Null,842				}843			}844		}845		Import(path) => {846			let tmp = loc847				.clone()848				.expect("imports cannot be used without loc_data")849				.0;850			let mut import_location = tmp.to_path_buf();851			import_location.pop();852			push(853				loc.as_ref(),854				|| format!("import {:?}", path),855				|| with_state(|s| s.import_file(&import_location, path)),856			)?857		}858		ImportStr(path) => {859			let tmp = loc860				.clone()861				.expect("imports cannot be used without loc_data")862				.0;863			let mut import_location = tmp.to_path_buf();864			import_location.pop();865			Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)866		}867	})868}
modifiedcrates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -6,17 +6,23 @@
 use jrsonnet_interner::IStr;
 use std::fs;
 use std::io::Read;
-use std::{any::Any, cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc};
+use std::{
+	any::Any,
+	cell::RefCell,
+	collections::HashMap,
+	path::{Path, PathBuf},
+	rc::Rc,
+};
 
 /// Implements file resolution logic for `import` and `importStr`
 pub trait ImportResolver {
 	/// Resolves real file path, e.g. `(/home/user/manifests, b.libjsonnet)` can correspond
 	/// both to `/home/user/manifests/b.libjsonnet` and to `/home/user/${vendor}/b.libjsonnet`
 	/// where `${vendor}` is a library path.
-	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>>;
+	fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>>;
 
 	/// Reads file from filesystem, should be used only with path received from `resolve_file`
-	fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr>;
+	fn load_file_contents(&self, resolved: &Path) -> Result<IStr>;
 
 	/// # Safety
 	///
@@ -29,11 +35,11 @@
 /// Dummy resolver, can't resolve/load any file
 pub struct DummyImportResolver;
 impl ImportResolver for DummyImportResolver {
-	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
-		throw!(ImportNotSupported(from.clone(), path.clone()))
+	fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
+		throw!(ImportNotSupported(from.into(), path.into()))
 	}
 
-	fn load_file_contents(&self, _resolved: &PathBuf) -> Result<IStr> {
+	fn load_file_contents(&self, _resolved: &Path) -> Result<IStr> {
 		// Can be only caused by library direct consumer, not by supplied jsonnet
 		panic!("dummy resolver can't load any file")
 	}
@@ -57,27 +63,27 @@
 	pub library_paths: Vec<PathBuf>,
 }
 impl ImportResolver for FileImportResolver {
-	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
-		let mut new_path = from.clone();
-		new_path.push(path);
-		if new_path.exists() {
-			Ok(Rc::new(new_path))
+	fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
+		let mut direct = from.to_path_buf();
+		direct.push(path);
+		if direct.exists() {
+			Ok(direct.into())
 		} else {
 			for library_path in self.library_paths.iter() {
 				let mut cloned = library_path.clone();
 				cloned.push(path);
 				if cloned.exists() {
-					return Ok(Rc::new(cloned));
+					return Ok(cloned.into());
 				}
 			}
-			throw!(ImportFileNotFound(from.clone(), path.clone()))
+			throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
 		}
 	}
-	fn load_file_contents(&self, id: &PathBuf) -> Result<IStr> {
-		let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;
+	fn load_file_contents(&self, id: &Path) -> Result<IStr> {
+		let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;
 		let mut out = String::new();
 		file.read_to_string(&mut out)
-			.map_err(|_e| ImportBadFileUtf8(id.clone()))?;
+			.map_err(|_e| ImportBadFileUtf8(id.to_owned()))?;
 		Ok(out.into())
 	}
 	unsafe fn as_any(&self) -> &dyn Any {
@@ -89,23 +95,23 @@
 
 /// Caches results of the underlying resolver
 pub struct CachingImportResolver {
-	resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<PathBuf>>>>,
+	resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<Path>>>>,
 	loading_cache: RefCell<HashMap<PathBuf, Result<IStr>>>,
 	inner: Box<dyn ImportResolver>,
 }
 impl ImportResolver for CachingImportResolver {
-	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
+	fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
 		self.resolution_cache
 			.borrow_mut()
-			.entry((from.clone(), path.clone()))
+			.entry((from.to_owned(), path.to_owned()))
 			.or_insert_with(|| self.inner.resolve_file(from, path))
 			.clone()
 	}
 
-	fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr> {
+	fn load_file_contents(&self, resolved: &Path) -> Result<IStr> {
 		self.loading_cache
 			.borrow_mut()
-			.entry(resolved.clone())
+			.entry(resolved.to_owned())
 			.or_insert_with(|| self.inner.load_file_contents(resolved))
 			.clone()
 	}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -27,7 +27,7 @@
 pub use function::parse_function_call;
 use gc::{Finalize, Gc, Trace};
 pub use import::*;
-use jrsonnet_interner::IStr;
+pub use jrsonnet_interner::IStr;
 use jrsonnet_parser::*;
 use native::NativeCallback;
 pub use obj::*;
@@ -37,7 +37,7 @@
 	collections::HashMap,
 	fmt::Debug,
 	hash::BuildHasherDefault,
-	path::PathBuf,
+	path::{Path, PathBuf},
 	rc::Rc,
 };
 use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};
@@ -110,8 +110,8 @@
 	/// Used for stack overflow detection, stacktrace is populated on unwind
 	stack_depth: usize,
 	/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
-	files: HashMap<Rc<PathBuf>, FileData>,
-	str_files: HashMap<Rc<PathBuf>, IStr>,
+	files: HashMap<Rc<Path>, FileData>,
+	str_files: HashMap<Rc<Path>, IStr>,
 }
 
 pub struct FileData {
@@ -157,7 +157,7 @@
 
 impl EvaluationState {
 	/// Parses and adds file as loaded
-	pub fn add_file(&self, path: Rc<PathBuf>, source_code: IStr) -> Result<()> {
+	pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<()> {
 		self.add_parsed_file(
 			path.clone(),
 			source_code.clone(),
@@ -170,7 +170,7 @@
 			)
 			.map_err(|error| ImportSyntaxError {
 				error: Box::new(error),
-				path,
+				path: path.to_owned(),
 				source_code,
 			})?,
 		)?;
@@ -181,7 +181,7 @@
 	/// Adds file by source code and parsed expr
 	pub fn add_parsed_file(
 		&self,
-		name: Rc<PathBuf>,
+		name: Rc<Path>,
 		source_code: IStr,
 		parsed: LocExpr,
 	) -> Result<()> {
@@ -196,20 +196,20 @@
 
 		Ok(())
 	}
-	pub fn get_source(&self, name: &PathBuf) -> Option<IStr> {
+	pub fn get_source(&self, name: &Path) -> Option<IStr> {
 		let ro_map = &self.data().files;
 		ro_map.get(name).map(|value| value.source_code.clone())
 	}
-	pub fn map_source_locations(&self, file: &PathBuf, locs: &[usize]) -> Vec<CodeLocation> {
+	pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {
 		offset_to_location(&self.get_source(file).unwrap(), locs)
 	}
 
-	pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {
+	pub(crate) fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {
 		let file_path = self.resolve_file(from, path)?;
 		{
 			let data = self.data();
 			let files = &data.files;
-			if files.contains_key(&file_path) {
+			if files.contains_key(&file_path as &Path) {
 				drop(data);
 				return self.evaluate_loaded_file_raw(&file_path);
 			}
@@ -218,7 +218,7 @@
 		self.add_file(file_path.clone(), contents)?;
 		self.evaluate_loaded_file_raw(&file_path)
 	}
-	pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<IStr> {
+	pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {
 		let path = self.resolve_file(from, path)?;
 		if !self.data().str_files.contains_key(&path) {
 			let file_str = self.load_file_contents(&path)?;
@@ -227,7 +227,7 @@
 		Ok(self.data().str_files.get(&path).cloned().unwrap())
 	}
 
-	fn evaluate_loaded_file_raw(&self, name: &PathBuf) -> Result<Val> {
+	fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {
 		let expr: LocExpr = {
 			let ro_map = &self.data().files;
 			let value = ro_map
@@ -253,7 +253,7 @@
 	/// Adds standard library global variable (std) to this evaluator
 	pub fn with_stdlib(&self) -> &Self {
 		use jrsonnet_stdlib::STDLIB_STR;
-		let std_path = Rc::new(PathBuf::from("std.jsonnet"));
+		let std_path: Rc<Path> = PathBuf::from("std.jsonnet").into();
 		self.run_in_state(|| {
 			self.add_parsed_file(
 				std_path.clone(),
@@ -381,14 +381,14 @@
 
 /// Raw methods evaluate passed values but don't perform TLA execution
 impl EvaluationState {
-	pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {
+	pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {
 		self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))
 	}
-	pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {
+	pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {
 		self.run_in_state(|| self.import_file(&PathBuf::from("."), name))
 	}
 	/// Parses and evaluates the given snippet
-	pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: IStr) -> Result<Val> {
+	pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {
 		let parsed = parse(
 			&code,
 			&ParserSettings {
@@ -420,7 +420,7 @@
 	}
 	pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {
 		let value =
-			self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("ext_code {}", name))), code)?;
+			self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;
 		self.add_ext_var(name, value);
 		Ok(())
 	}
@@ -433,15 +433,15 @@
 	}
 	pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {
 		let value =
-			self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("tla_code {}", name))), code)?;
+			self.evaluate_snippet_raw(PathBuf::from(format!("tla_code {}", name)).into(), code)?;
 		self.add_tla(name, value);
 		Ok(())
 	}
 
-	pub fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
+	pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
 		self.settings().import_resolver.resolve_file(from, path)
 	}
-	pub fn load_file_contents(&self, path: &PathBuf) -> Result<IStr> {
+	pub fn load_file_contents(&self, path: &Path) -> Result<IStr> {
 		self.settings().import_resolver.load_file_contents(path)
 	}
 
@@ -494,7 +494,10 @@
 	use gc::Gc;
 	use jrsonnet_interner::IStr;
 	use jrsonnet_parser::*;
-	use std::{path::PathBuf, rc::Rc};
+	use std::{
+		path::{Path, PathBuf},
+		rc::Rc,
+	};
 
 	#[test]
 	#[should_panic]
@@ -503,19 +506,11 @@
 		state.run_in_state(|| {
 			state
 				.push(
-					Some(&ExprLocation(
-						Rc::new(PathBuf::from("test1.jsonnet")),
-						10,
-						20,
-					)),
+					Some(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),
 					|| "outer".to_owned(),
 					|| {
 						state.push(
-							Some(&ExprLocation(
-								Rc::new(PathBuf::from("test2.jsonnet")),
-								30,
-								40,
-							)),
+							Some(&ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40)),
 							|| "inner".to_owned(),
 							|| Err(RuntimeError("".into()).into()),
 						)?;
@@ -533,7 +528,7 @@
 		assert!(primitive_equals(
 			&state
 				.evaluate_snippet_raw(
-					Rc::new(PathBuf::from("raw.jsonnet")),
+					PathBuf::from("raw.jsonnet").into(),
 					r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()
 				)
 				.unwrap(),
@@ -546,7 +541,7 @@
 		($str: expr) => {
 			EvaluationState::default()
 				.with_stdlib()
-				.evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())
+				.evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())
 				.unwrap()
 		};
 	}
@@ -556,7 +551,7 @@
 			evaluator.with_stdlib();
 			evaluator.run_in_state(|| {
 				evaluator
-					.evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())
+					.evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())
 					.unwrap()
 					.to_json(0)
 					.unwrap()
@@ -913,7 +908,10 @@
 			"{:?}",
 			jrsonnet_parser::parse(
 				"{ x: 1, y: 2 } == { x: 1, y: 2 }",
-				&ParserSettings::default()
+				&ParserSettings {
+					file_name: PathBuf::from("equality").into(),
+					loc_data: true,
+				}
 			)
 		);
 		assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")
@@ -929,10 +927,10 @@
 		#[derive(gc::Trace, gc::Finalize)]
 		struct NativeAdd;
 		impl NativeCallbackHandler for NativeAdd {
-			fn call(&self, from: Option<Rc<PathBuf>>, args: &[Val]) -> crate::error::Result<Val> {
+			fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> crate::error::Result<Val> {
 				assert_eq!(
-					from.unwrap(),
-					Rc::new(PathBuf::from("native_caller.jsonnet"))
+					&from.unwrap() as &Path,
+					&PathBuf::from("native_caller.jsonnet")
 				);
 				match (&args[0], &args[1]) {
 					(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),
@@ -951,7 +949,7 @@
 			)),
 		);
 		evaluator.evaluate_snippet_raw(
-			Rc::new(PathBuf::from("native_caller.jsonnet")),
+			PathBuf::from("native_caller.jsonnet").into(),
 			"std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),
 		)?;
 		Ok(())
@@ -1003,11 +1001,11 @@
 
 	struct TestImportResolver(IStr);
 	impl crate::import::ImportResolver for TestImportResolver {
-		fn resolve_file(&self, _: &PathBuf, _: &PathBuf) -> crate::error::Result<Rc<PathBuf>> {
-			Ok(Rc::new(PathBuf::from("/test")))
+		fn resolve_file(&self, _: &Path, _: &Path) -> crate::error::Result<Rc<Path>> {
+			Ok(PathBuf::from("/test").into())
 		}
 
-		fn load_file_contents(&self, _: &PathBuf) -> crate::error::Result<IStr> {
+		fn load_file_contents(&self, _: &Path) -> crate::error::Result<IStr> {
 			Ok(self.0.clone())
 		}
 
@@ -1030,7 +1028,7 @@
 
 		let error = state
 			.evaluate_snippet_raw(
-				Rc::new(PathBuf::from("issue40.jsonnet")),
+				PathBuf::from("issue40.jsonnet").into(),
 				r#"
 				local conf = {
 					n: ""
modifiedcrates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -4,11 +4,11 @@
 use gc::{Finalize, Trace};
 use jrsonnet_parser::ParamsDesc;
 use std::fmt::Debug;
-use std::path::PathBuf;
+use std::path::Path;
 use std::rc::Rc;
 
 pub trait NativeCallbackHandler: Trace {
-	fn call(&self, from: Option<Rc<PathBuf>>, args: &[Val]) -> Result<Val>;
+	fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> Result<Val>;
 }
 
 #[derive(Trace, Finalize)]
@@ -20,7 +20,7 @@
 	pub fn new(params: ParamsDesc, handler: Box<dyn NativeCallbackHandler>) -> Self {
 		Self { params, handler }
 	}
-	pub fn call(&self, caller: Option<Rc<PathBuf>>, args: &[Val]) -> Result<Val> {
+	pub fn call(&self, caller: Option<Rc<Path>>, args: &[Val]) -> Result<Val> {
 		self.handler.call(caller, args)
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -2,7 +2,7 @@
 
 use crate::{error::Error, EvaluationState, LocError};
 pub use location::*;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
 
 /// The way paths should be displayed
 pub enum PathResolver {
@@ -15,7 +15,7 @@
 }
 
 impl PathResolver {
-	pub fn resolve(&self, from: &PathBuf) -> String {
+	pub fn resolve(&self, from: &Path) -> String {
 		match self {
 			Self::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),
 			Self::Absolute => from.to_string_lossy().into_owned(),
@@ -255,7 +255,7 @@
 		&self,
 		out: &mut dyn std::fmt::Write,
 		source: &str,
-		origin: &PathBuf,
+		origin: &Path,
 		start: &CodeLocation,
 		end: &CodeLocation,
 		desc: &str,
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -7,7 +7,7 @@
 use std::{
 	fmt::{Debug, Display},
 	ops::Deref,
-	path::PathBuf,
+	path::{Path, PathBuf},
 	rc::Rc,
 };
 
@@ -405,7 +405,7 @@
 #[cfg_attr(feature = "serialize", derive(Serialize))]
 #[cfg_attr(feature = "deserialize", derive(Deserialize))]
 #[derive(Clone, PartialEq)]
-pub struct ExprLocation(pub Rc<PathBuf>, pub usize, pub usize);
+pub struct ExprLocation(pub Rc<Path>, pub usize, pub usize);
 impl Finalize for ExprLocation {}
 unsafe impl Trace for ExprLocation {
 	unsafe_empty_trace!();
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -1,15 +1,17 @@
 #![allow(clippy::redundant_closure_call)]
 
 use peg::parser;
-use std::{path::PathBuf, rc::Rc};
+use std::{
+	path::{Path, PathBuf},
+	rc::Rc,
+};
 mod expr;
 pub use expr::*;
 pub use peg;
 
-#[derive(Default)]
 pub struct ParserSettings {
 	pub loc_data: bool,
-	pub file_name: Rc<PathBuf>,
+	pub file_name: Rc<Path>,
 }
 
 parser! {
@@ -304,7 +306,6 @@
 	use super::{expr::*, parse};
 	use crate::ParserSettings;
 	use std::path::PathBuf;
-	use std::rc::Rc;
 
 	macro_rules! parse {
 		($s:expr) => {
@@ -312,7 +313,7 @@
 				$s,
 				&ParserSettings {
 					loc_data: false,
-					file_name: Rc::new(PathBuf::from("/test.jsonnet")),
+					file_name: PathBuf::from("/test.jsonnet").into(),
 				},
 			)
 			.unwrap()