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
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -5,7 +5,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)]
@@ -86,7 +89,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,
 		error: Box<jrsonnet_parser::ParseError>,
 	},
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
35 collections::HashMap,35 collections::HashMap,
36 fmt::Debug,36 fmt::Debug,
37 hash::BuildHasherDefault,37 hash::BuildHasherDefault,
38 path::PathBuf,38 path::{Path, PathBuf},
39 rc::Rc,39 rc::Rc,
40};40};
41use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};41use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};
109 /// Used for stack overflow detection, stacktrace is populated on unwind109 /// Used for stack overflow detection, stacktrace is populated on unwind
110 stack_depth: usize,110 stack_depth: usize,
111 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces111 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
112 files: HashMap<Rc<PathBuf>, FileData>,112 files: HashMap<Rc<Path>, FileData>,
113 str_files: HashMap<Rc<PathBuf>, IStr>,113 str_files: HashMap<Rc<Path>, IStr>,
114}114}
115115
116pub struct FileData {116pub struct FileData {
156156
157impl EvaluationState {157impl EvaluationState {
158 /// Parses and adds file as loaded158 /// Parses and adds file as loaded
159 pub fn add_file(&self, path: Rc<PathBuf>, source_code: IStr) -> Result<()> {159 pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<()> {
160 self.add_parsed_file(160 self.add_parsed_file(
161 path.clone(),161 path.clone(),
162 source_code.clone(),162 source_code.clone(),
169 )169 )
170 .map_err(|error| ImportSyntaxError {170 .map_err(|error| ImportSyntaxError {
171 error: Box::new(error),171 error: Box::new(error),
172 path,172 path: path.to_owned(),
173 source_code,173 source_code,
174 })?,174 })?,
175 )?;175 )?;
180 /// Adds file by source code and parsed expr180 /// Adds file by source code and parsed expr
181 pub fn add_parsed_file(181 pub fn add_parsed_file(
182 &self,182 &self,
183 name: Rc<PathBuf>,183 name: Rc<Path>,
184 source_code: IStr,184 source_code: IStr,
185 parsed: LocExpr,185 parsed: LocExpr,
186 ) -> Result<()> {186 ) -> Result<()> {
195195
196 Ok(())196 Ok(())
197 }197 }
198 pub fn get_source(&self, name: &PathBuf) -> Option<IStr> {198 pub fn get_source(&self, name: &Path) -> Option<IStr> {
199 let ro_map = &self.data().files;199 let ro_map = &self.data().files;
200 ro_map.get(name).map(|value| value.source_code.clone())200 ro_map.get(name).map(|value| value.source_code.clone())
201 }201 }
202 pub fn map_source_locations(&self, file: &PathBuf, locs: &[usize]) -> Vec<CodeLocation> {202 pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {
203 offset_to_location(&self.get_source(file).unwrap(), locs)203 offset_to_location(&self.get_source(file).unwrap(), locs)
204 }204 }
205205
206 pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {206 pub(crate) fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {
207 let file_path = self.resolve_file(from, path)?;207 let file_path = self.resolve_file(from, path)?;
208 {208 {
209 let data = self.data();209 let data = self.data();
210 let files = &data.files;210 let files = &data.files;
211 if files.contains_key(&file_path) {211 if files.contains_key(&file_path as &Path) {
212 drop(data);212 drop(data);
213 return self.evaluate_loaded_file_raw(&file_path);213 return self.evaluate_loaded_file_raw(&file_path);
214 }214 }
217 self.add_file(file_path.clone(), contents)?;217 self.add_file(file_path.clone(), contents)?;
218 self.evaluate_loaded_file_raw(&file_path)218 self.evaluate_loaded_file_raw(&file_path)
219 }219 }
220 pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<IStr> {220 pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {
221 let path = self.resolve_file(from, path)?;221 let path = self.resolve_file(from, path)?;
222 if !self.data().str_files.contains_key(&path) {222 if !self.data().str_files.contains_key(&path) {
223 let file_str = self.load_file_contents(&path)?;223 let file_str = self.load_file_contents(&path)?;
226 Ok(self.data().str_files.get(&path).cloned().unwrap())226 Ok(self.data().str_files.get(&path).cloned().unwrap())
227 }227 }
228228
229 fn evaluate_loaded_file_raw(&self, name: &PathBuf) -> Result<Val> {229 fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {
230 let expr: LocExpr = {230 let expr: LocExpr = {
231 let ro_map = &self.data().files;231 let ro_map = &self.data().files;
232 let value = ro_map232 let value = ro_map
252 /// Adds standard library global variable (std) to this evaluator252 /// Adds standard library global variable (std) to this evaluator
253 pub fn with_stdlib(&self) -> &Self {253 pub fn with_stdlib(&self) -> &Self {
254 use jrsonnet_stdlib::STDLIB_STR;254 use jrsonnet_stdlib::STDLIB_STR;
255 let std_path = Rc::new(PathBuf::from("std.jsonnet"));255 let std_path: Rc<Path> = PathBuf::from("std.jsonnet").into();
256 self.run_in_state(|| {256 self.run_in_state(|| {
257 self.add_parsed_file(257 self.add_parsed_file(
258 std_path.clone(),258 std_path.clone(),
380380
381/// Raw methods evaluate passed values but don't perform TLA execution381/// Raw methods evaluate passed values but don't perform TLA execution
382impl EvaluationState {382impl EvaluationState {
383 pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {383 pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {
384 self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))384 self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))
385 }385 }
386 pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {386 pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {
387 self.run_in_state(|| self.import_file(&PathBuf::from("."), name))387 self.run_in_state(|| self.import_file(&PathBuf::from("."), name))
388 }388 }
389 /// Parses and evaluates the given snippet389 /// Parses and evaluates the given snippet
390 pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: IStr) -> Result<Val> {390 pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {
391 let parsed = parse(391 let parsed = parse(
392 &code,392 &code,
393 &ParserSettings {393 &ParserSettings {
419 }419 }
420 pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {420 pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {
421 let value =421 let value =
422 self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("ext_code {}", name))), code)?;422 self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;
423 self.add_ext_var(name, value);423 self.add_ext_var(name, value);
424 Ok(())424 Ok(())
425 }425 }
432 }432 }
433 pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {433 pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {
434 let value =434 let value =
435 self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("tla_code {}", name))), code)?;435 self.evaluate_snippet_raw(PathBuf::from(format!("tla_code {}", name)).into(), code)?;
436 self.add_tla(name, value);436 self.add_tla(name, value);
437 Ok(())437 Ok(())
438 }438 }
439439
440 pub fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {440 pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
441 self.settings().import_resolver.resolve_file(from, path)441 self.settings().import_resolver.resolve_file(from, path)
442 }442 }
443 pub fn load_file_contents(&self, path: &PathBuf) -> Result<IStr> {443 pub fn load_file_contents(&self, path: &Path) -> Result<IStr> {
444 self.settings().import_resolver.load_file_contents(path)444 self.settings().import_resolver.load_file_contents(path)
445 }445 }
446446
491 use jrsonnet_interner::IStr;491 use jrsonnet_interner::IStr;
492 use jrsonnet_parser::*;492 use jrsonnet_parser::*;
493 use std::{path::PathBuf, rc::Rc};493 use std::{
494 path::{Path, PathBuf},
495 rc::Rc,
496 };
494497
495 #[test]498 #[test]
499 state.run_in_state(|| {502 state.run_in_state(|| {
500 state503 state
501 .push(504 .push(
502 Some(&ExprLocation(505 Some(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),
503 Rc::new(PathBuf::from("test1.jsonnet")),
504 10,
505 20,
506 )),
507 || "outer".to_owned(),506 || "outer".to_owned(),
508 || {507 || {
509 state.push(508 state.push(
510 Some(&ExprLocation(509 Some(&ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40)),
511 Rc::new(PathBuf::from("test2.jsonnet")),
512 30,
513 40,
514 )),
529 assert!(primitive_equals(524 assert!(primitive_equals(
530 &state525 &state
531 .evaluate_snippet_raw(526 .evaluate_snippet_raw(
532 Rc::new(PathBuf::from("raw.jsonnet")),527 PathBuf::from("raw.jsonnet").into(),
533 r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()528 r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()
534 )529 )
535 .unwrap(),530 .unwrap(),
542 ($str: expr) => {537 ($str: expr) => {
543 EvaluationState::default()538 EvaluationState::default()
544 .with_stdlib()539 .with_stdlib()
545 .evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())540 .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())
546 .unwrap()541 .unwrap()
547 };542 };
548 }543 }
552 evaluator.with_stdlib();547 evaluator.with_stdlib();
553 evaluator.run_in_state(|| {548 evaluator.run_in_state(|| {
554 evaluator549 evaluator
555 .evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())550 .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())
556 .unwrap()551 .unwrap()
557 .to_json(0)552 .to_json(0)
558 .unwrap()553 .unwrap()
909 "{:?}",904 "{:?}",
910 jrsonnet_parser::parse(905 jrsonnet_parser::parse(
911 "{ x: 1, y: 2 } == { x: 1, y: 2 }",906 "{ x: 1, y: 2 } == { x: 1, y: 2 }",
912 &ParserSettings::default()907 &ParserSettings {
908 file_name: PathBuf::from("equality").into(),
909 loc_data: true,
910 }
913 )911 )
914 );912 );
915 assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")913 assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")
930 ])),928 ])),
931 |caller, args| {929 |caller, args| {
932 assert_eq!(930 assert_eq!(
933 caller.unwrap(),931 &caller.unwrap() as &Path,
934 Rc::new(PathBuf::from("native_caller.jsonnet"))932 &PathBuf::from("native_caller.jsonnet")
935 );933 );
936 match (&args[0], &args[1]) {934 match (&args[0], &args[1]) {
937 (Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),935 (Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),
941 )),939 )),
942 );940 );
943 evaluator.evaluate_snippet_raw(941 evaluator.evaluate_snippet_raw(
944 Rc::new(PathBuf::from("native_caller.jsonnet")),942 PathBuf::from("native_caller.jsonnet").into(),
945 "std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),943 "std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),
946 )?;944 )?;
947 Ok(())945 Ok(())
993991
994 struct TestImportResolver(IStr);992 struct TestImportResolver(IStr);
995 impl crate::import::ImportResolver for TestImportResolver {993 impl crate::import::ImportResolver for TestImportResolver {
996 fn resolve_file(&self, _: &PathBuf, _: &PathBuf) -> crate::error::Result<Rc<PathBuf>> {994 fn resolve_file(&self, _: &Path, _: &Path) -> crate::error::Result<Rc<Path>> {
997 Ok(Rc::new(PathBuf::from("/test")))995 Ok(PathBuf::from("/test").into())
998 }996 }
999997
1000 fn load_file_contents(&self, _: &PathBuf) -> crate::error::Result<IStr> {998 fn load_file_contents(&self, _: &Path) -> crate::error::Result<IStr> {
1001 Ok(self.0.clone())999 Ok(self.0.clone())
1002 }1000 }
10031001
10201018
1021 let error = state1019 let error = state
1022 .evaluate_snippet_raw(1020 .evaluate_snippet_raw(
1023 Rc::new(PathBuf::from("issue40.jsonnet")),1021 PathBuf::from("issue40.jsonnet").into(),
1024 r#"1022 r#"
1025 local conf = {1023 local conf = {
1026 n: ""1024 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()