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

difftreelog

refactor receive Path in public api arguments

Yaroslav Bolyukin2021-06-14parent: #ad64d8a.patch.diff
in: master
Fixes #39
Fixes #47

14 files changed

modifiedbindings/jsonnet/src/import.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -12,7 +12,7 @@
 	fs::File,
 	io::Read,
 	os::raw::{c_char, c_int},
-	path::PathBuf,
+	path::{Path, PathBuf},
 	ptr::null_mut,
 	rc::Rc,
 };
@@ -33,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();
@@ -73,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 {
@@ -108,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
@@ -15,7 +15,6 @@
 	ffi::{CStr, CString},
 	os::raw::{c_char, c_double, c_int, c_uint},
 	path::PathBuf,
-	rc::Rc,
 };
 
 /// WASM stub
@@ -144,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))
@@ -220,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))
@@ -294,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))
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
@@ -174,7 +174,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
before · crates/jrsonnet-evaluator/src/error.rs
1use crate::{2	builtin::{format::FormatError, sort::SortError},3	typed::TypeLocError,4};5use jrsonnet_interner::IStr;6use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};7use jrsonnet_types::ValType;8use std::{path::PathBuf, rc::Rc};9use thiserror::Error;1011#[derive(Error, Debug, Clone)]12pub enum Error {13	#[error("intrinsic not found: {0}")]14	IntrinsicNotFound(IStr),15	#[error("argument reordering in intrisics not supported yet")]16	IntrinsicArgumentReorderingIsNotSupportedYet,1718	#[error("operator {0} does not operate on type {1}")]19	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),20	#[error("binary operation {1} {0} {2} is not implemented")]21	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2223	#[error("no top level object in this context")]24	NoTopLevelObjectFound,25	#[error("self is only usable inside objects")]26	CantUseSelfOutsideOfObject,27	#[error("no super found")]28	NoSuperFound,2930	#[error("for loop can only iterate over arrays")]31	InComprehensionCanOnlyIterateOverArray,3233	#[error("array out of bounds: {0} is not within [0,{1})")]34	ArrayBoundsError(usize, usize),3536	#[error("assert failed: {0}")]37	AssertionFailed(IStr),3839	#[error("variable is not defined: {0}")]40	VariableIsNotDefined(IStr),41	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]42	TypeMismatch(&'static str, Vec<ValType>, ValType),43	#[error("no such field: {0}")]44	NoSuchField(IStr),4546	#[error("only functions can be called, got {0}")]47	OnlyFunctionsCanBeCalledGot(ValType),48	#[error("parameter {0} is not defined")]49	UnknownFunctionParameter(String),50	#[error("argument {0} is already bound")]51	BindingParameterASecondTime(IStr),52	#[error("too many args, function has {0}")]53	TooManyArgsFunctionHas(usize),54	#[error("founction argument is not passed: {0}")]55	FunctionParameterNotBoundInCall(IStr),5657	#[error("external variable is not defined: {0}")]58	UndefinedExternalVariable(IStr),59	#[error("native is not defined: {0}")]60	UndefinedExternalFunction(IStr),6162	#[error("field name should be string, got {0}")]63	FieldMustBeStringGot(ValType),6465	#[error("attempted to index array with string {0}")]66	AttemptedIndexAnArrayWithString(IStr),67	#[error("{0} index type should be {1}, got {2}")]68	ValueIndexMustBeTypeGot(ValType, ValType, ValType),69	#[error("cant index into {0}")]70	CantIndexInto(ValType),7172	#[error("super can't be used standalone")]73	StandaloneSuper,7475	#[error("can't resolve {1} from {0}")]76	ImportFileNotFound(PathBuf, PathBuf),77	#[error("resolved file not found: {0}")]78	ResolvedFileNotFound(PathBuf),79	#[error("imported file is not valid utf-8: {0:?}")]80	ImportBadFileUtf8(PathBuf),81	#[error("tried to import {1} from {0}, but imports is not supported")]82	ImportNotSupported(PathBuf, PathBuf),83	#[error(84		"syntax error, expected one of {}, got {:?}",85		.error.expected,86		.source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())87	)]88	ImportSyntaxError {89		path: Rc<PathBuf>,90		source_code: IStr,91		error: Box<jrsonnet_parser::ParseError>,92	},9394	#[error("runtime error: {0}")]95	RuntimeError(IStr),96	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]97	StackOverflow,98	#[error("tried to index by fractional value")]99	FractionalIndex,100	#[error("attempted to divide by zero")]101	DivisionByZero,102103	#[error("string manifest output is not an string")]104	StringManifestOutputIsNotAString,105	#[error("stream manifest output is not an array")]106	StreamManifestOutputIsNotAArray,107	#[error("multi manifest output is not an object")]108	MultiManifestOutputIsNotAObject,109110	#[error("cant recurse stream manifest")]111	StreamManifestOutputCannotBeRecursed,112	#[error("stream manifest output cannot consist of raw strings")]113	StreamManifestCannotNestString,114115	#[error("{0}")]116	ImportCallbackError(String),117	#[error("invalid unicode codepoint: {0}")]118	InvalidUnicodeCodepointGot(u32),119120	#[error("format error: {0}")]121	Format(#[from] FormatError),122	#[error("type error: {0}")]123	TypeError(TypeLocError),124	#[error("sort error: {0}")]125	Sort(#[from] SortError),126127	#[cfg(feature = "anyhow-error")]128	#[error(transparent)]129	Other(Rc<anyhow::Error>),130}131132#[cfg(feature = "anyhow-error")]133impl From<anyhow::Error> for LocError {134	fn from(e: anyhow::Error) -> Self {135		Self::new(Error::Other(Rc::new(e)))136	}137}138139impl From<Error> for LocError {140	fn from(e: Error) -> Self {141		Self::new(e)142	}143}144145#[derive(Clone, Debug)]146pub struct StackTraceElement {147	pub location: Option<ExprLocation>,148	pub desc: String,149}150#[derive(Debug, Clone)]151pub struct StackTrace(pub Vec<StackTraceElement>);152153#[derive(Debug, Clone)]154pub struct LocError(Box<(Error, StackTrace)>);155impl LocError {156	pub fn new(e: Error) -> Self {157		Self(Box::new((e, StackTrace(vec![]))))158	}159160	pub const fn error(&self) -> &Error {161		&(self.0).0162	}163	pub fn error_mut(&mut self) -> &mut Error {164		&mut (self.0).0165	}166	pub const fn trace(&self) -> &StackTrace {167		&(self.0).1168	}169	pub fn trace_mut(&mut self) -> &mut StackTrace {170		&mut (self.0).1171	}172}173174pub type Result<V> = std::result::Result<V, LocError>;175176#[macro_export]177macro_rules! throw {178	($e: expr) => {179		return Err($e.into());180	};181}
after · crates/jrsonnet-evaluator/src/error.rs
1use crate::{2	builtin::{format::FormatError, sort::SortError},3	typed::TypeLocError,4};5use jrsonnet_interner::IStr;6use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};7use jrsonnet_types::ValType;8use std::{9	path::{Path, PathBuf},10	rc::Rc,11};12use thiserror::Error;1314#[derive(Error, Debug, Clone)]15pub enum Error {16	#[error("intrinsic not found: {0}")]17	IntrinsicNotFound(IStr),18	#[error("argument reordering in intrisics not supported yet")]19	IntrinsicArgumentReorderingIsNotSupportedYet,2021	#[error("operator {0} does not operate on type {1}")]22	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),23	#[error("binary operation {1} {0} {2} is not implemented")]24	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2526	#[error("no top level object in this context")]27	NoTopLevelObjectFound,28	#[error("self is only usable inside objects")]29	CantUseSelfOutsideOfObject,30	#[error("no super found")]31	NoSuperFound,3233	#[error("for loop can only iterate over arrays")]34	InComprehensionCanOnlyIterateOverArray,3536	#[error("array out of bounds: {0} is not within [0,{1})")]37	ArrayBoundsError(usize, usize),3839	#[error("assert failed: {0}")]40	AssertionFailed(IStr),4142	#[error("variable is not defined: {0}")]43	VariableIsNotDefined(IStr),44	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]45	TypeMismatch(&'static str, Vec<ValType>, ValType),46	#[error("no such field: {0}")]47	NoSuchField(IStr),4849	#[error("only functions can be called, got {0}")]50	OnlyFunctionsCanBeCalledGot(ValType),51	#[error("parameter {0} is not defined")]52	UnknownFunctionParameter(String),53	#[error("argument {0} is already bound")]54	BindingParameterASecondTime(IStr),55	#[error("too many args, function has {0}")]56	TooManyArgsFunctionHas(usize),57	#[error("founction argument is not passed: {0}")]58	FunctionParameterNotBoundInCall(IStr),5960	#[error("external variable is not defined: {0}")]61	UndefinedExternalVariable(IStr),62	#[error("native is not defined: {0}")]63	UndefinedExternalFunction(IStr),6465	#[error("field name should be string, got {0}")]66	FieldMustBeStringGot(ValType),6768	#[error("attempted to index array with string {0}")]69	AttemptedIndexAnArrayWithString(IStr),70	#[error("{0} index type should be {1}, got {2}")]71	ValueIndexMustBeTypeGot(ValType, ValType, ValType),72	#[error("cant index into {0}")]73	CantIndexInto(ValType),7475	#[error("super can't be used standalone")]76	StandaloneSuper,7778	#[error("can't resolve {1} from {0}")]79	ImportFileNotFound(PathBuf, PathBuf),80	#[error("resolved file not found: {0}")]81	ResolvedFileNotFound(PathBuf),82	#[error("imported file is not valid utf-8: {0:?}")]83	ImportBadFileUtf8(PathBuf),84	#[error("tried to import {1} from {0}, but imports is not supported")]85	ImportNotSupported(PathBuf, PathBuf),86	#[error(87		"syntax error, expected one of {}, got {:?}",88		.error.expected,89		.source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())90	)]91	ImportSyntaxError {92		path: Rc<Path>,93		source_code: IStr,94		error: Box<jrsonnet_parser::ParseError>,95	},9697	#[error("runtime error: {0}")]98	RuntimeError(IStr),99	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]100	StackOverflow,101	#[error("tried to index by fractional value")]102	FractionalIndex,103	#[error("attempted to divide by zero")]104	DivisionByZero,105106	#[error("string manifest output is not an string")]107	StringManifestOutputIsNotAString,108	#[error("stream manifest output is not an array")]109	StreamManifestOutputIsNotAArray,110	#[error("multi manifest output is not an object")]111	MultiManifestOutputIsNotAObject,112113	#[error("cant recurse stream manifest")]114	StreamManifestOutputCannotBeRecursed,115	#[error("stream manifest output cannot consist of raw strings")]116	StreamManifestCannotNestString,117118	#[error("{0}")]119	ImportCallbackError(String),120	#[error("invalid unicode codepoint: {0}")]121	InvalidUnicodeCodepointGot(u32),122123	#[error("format error: {0}")]124	Format(#[from] FormatError),125	#[error("type error: {0}")]126	TypeError(TypeLocError),127	#[error("sort error: {0}")]128	Sort(#[from] SortError),129130	#[cfg(feature = "anyhow-error")]131	#[error(transparent)]132	Other(Rc<anyhow::Error>),133}134135#[cfg(feature = "anyhow-error")]136impl From<anyhow::Error> for LocError {137	fn from(e: anyhow::Error) -> Self {138		Self::new(Error::Other(Rc::new(e)))139	}140}141142impl From<Error> for LocError {143	fn from(e: Error) -> Self {144		Self::new(e)145	}146}147148#[derive(Clone, Debug)]149pub struct StackTraceElement {150	pub location: Option<ExprLocation>,151	pub desc: String,152}153#[derive(Debug, Clone)]154pub struct StackTrace(pub Vec<StackTraceElement>);155156#[derive(Debug, Clone)]157pub struct LocError(Box<(Error, StackTrace)>);158impl LocError {159	pub fn new(e: Error) -> Self {160		Self(Box::new((e, StackTrace(vec![]))))161	}162163	pub const fn error(&self) -> &Error {164		&(self.0).0165	}166	pub fn error_mut(&mut self) -> &mut Error {167		&mut (self.0).0168	}169	pub const fn trace(&self) -> &StackTrace {170		&(self.0).1171	}172	pub fn trace_mut(&mut self) -> &mut StackTrace {173		&mut (self.0).1174	}175}176177pub type Result<V> = std::result::Result<V, LocError>;178179#[macro_export]180macro_rules! throw {181	($e: expr) => {182		return Err($e.into());183	};184}
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -609,26 +609,26 @@
 			}
 		}
 		Import(path) => {
-			let mut tmp = loc
+			let tmp = loc
 				.clone()
 				.expect("imports cannot be used without loc_data")
 				.0;
-			let import_location = Rc::make_mut(&mut tmp);
+			let mut import_location = tmp.to_path_buf();
 			import_location.pop();
 			push(
 				loc.as_ref(),
 				|| format!("import {:?}", path),
-				|| with_state(|s| s.import_file(import_location, path)),
+				|| with_state(|s| s.import_file(&import_location, path)),
 			)?
 		}
 		ImportStr(path) => {
-			let mut tmp = loc
+			let tmp = loc
 				.clone()
 				.expect("imports cannot be used without loc_data")
 				.0;
-			let import_location = Rc::make_mut(&mut tmp);
+			let mut import_location = tmp.to_path_buf();
 			import_location.pop();
-			Val::Str(with_state(|s| s.import_file_str(import_location, path))?)
+			Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)
 		}
 	})
 }
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
@@ -35,7 +35,7 @@
 	collections::HashMap,
 	fmt::Debug,
 	hash::BuildHasherDefault,
-	path::PathBuf,
+	path::{Path, PathBuf},
 	rc::Rc,
 };
 use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};
@@ -109,8 +109,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 {
@@ -156,7 +156,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(),
@@ -169,7 +169,7 @@
 			)
 			.map_err(|error| ImportSyntaxError {
 				error: Box::new(error),
-				path,
+				path: path.to_owned(),
 				source_code,
 			})?,
 		)?;
@@ -180,7 +180,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<()> {
@@ -195,20 +195,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);
 			}
@@ -217,7 +217,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)?;
@@ -226,7 +226,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
@@ -252,7 +252,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(),
@@ -380,14 +380,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 {
@@ -419,7 +419,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(())
 	}
@@ -432,15 +432,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)
 	}
 
@@ -490,7 +490,10 @@
 	use crate::{error::Error::*, primitive_equals, EvaluationState};
 	use jrsonnet_interner::IStr;
 	use jrsonnet_parser::*;
-	use std::{path::PathBuf, rc::Rc};
+	use std::{
+		path::{Path, PathBuf},
+		rc::Rc,
+	};
 
 	#[test]
 	#[should_panic]
@@ -499,19 +502,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()),
 						)?;
@@ -529,7 +524,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(),
@@ -542,7 +537,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()
 		};
 	}
@@ -552,7 +547,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()
@@ -909,7 +904,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 }")
@@ -930,8 +928,8 @@
 				])),
 				|caller, args| {
 					assert_eq!(
-						caller.unwrap(),
-						Rc::new(PathBuf::from("native_caller.jsonnet"))
+						&caller.unwrap() as &Path,
+						&PathBuf::from("native_caller.jsonnet")
 					);
 					match (&args[0], &args[1]) {
 						(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),
@@ -941,7 +939,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(())
@@ -993,11 +991,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())
 		}
 
@@ -1020,7 +1018,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
@@ -3,24 +3,24 @@
 use crate::{error::Result, Val};
 use jrsonnet_parser::ParamsDesc;
 use std::fmt::Debug;
-use std::path::PathBuf;
+use std::path::Path;
 use std::rc::Rc;
 
 pub struct NativeCallback {
 	pub params: ParamsDesc,
-	handler: Box<dyn Fn(Option<Rc<PathBuf>>, &[Val]) -> Result<Val>>,
+	handler: Box<dyn Fn(Option<Rc<Path>>, &[Val]) -> Result<Val>>,
 }
 impl NativeCallback {
 	pub fn new(
 		params: ParamsDesc,
-		handler: impl Fn(Option<Rc<PathBuf>>, &[Val]) -> Result<Val> + 'static,
+		handler: impl Fn(Option<Rc<Path>>, &[Val]) -> Result<Val> + 'static,
 	) -> Self {
 		Self {
 			params,
 			handler: Box::new(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)(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
@@ -6,7 +6,7 @@
 use std::{
 	fmt::{Debug, Display},
 	ops::Deref,
-	path::PathBuf,
+	path::{Path, PathBuf},
 	rc::Rc,
 };
 
@@ -320,7 +320,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 Debug for ExprLocation {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)
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()