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
12 fs::File,12 fs::File,
13 io::Read,13 io::Read,
14 os::raw::{c_char, c_int},14 os::raw::{c_char, c_int},
15 path::PathBuf,15 path::{Path, PathBuf},
16 ptr::null_mut,16 ptr::null_mut,
17 rc::Rc,17 rc::Rc,
18};18};
33 out: RefCell<HashMap<PathBuf, IStr>>,33 out: RefCell<HashMap<PathBuf, IStr>>,
34}34}
35impl ImportResolver for CallbackImportResolver {35impl ImportResolver for CallbackImportResolver {
36 fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {36 fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
37 let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();37 let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();
38 let rel = CString::new(path.to_str().unwrap()).unwrap().into_raw();38 let rel = CString::new(path.to_str().unwrap()).unwrap().into_raw();
39 let found_here: *mut c_char = null_mut();39 let found_here: *mut c_char = null_mut();
73 unsafe { CString::from_raw(result_ptr) };73 unsafe { CString::from_raw(result_ptr) };
74 }74 }
7575
76 Ok(Rc::new(found_here_buf))76 Ok(found_here_buf.into())
77 }77 }
78 fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr> {78 fn load_file_contents(&self, resolved: &Path) -> Result<IStr> {
79 Ok(self.out.borrow().get(resolved).unwrap().clone())79 Ok(self.out.borrow().get(resolved).unwrap().clone())
80 }80 }
81 unsafe fn as_any(&self) -> &dyn Any {81 unsafe fn as_any(&self) -> &dyn Any {
108 }108 }
109}109}
110impl ImportResolver for NativeImportResolver {110impl ImportResolver for NativeImportResolver {
111 fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {111 fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
112 let mut new_path = from.clone();112 let mut new_path = from.to_owned();
113 new_path.push(path);113 new_path.push(path);
114 if new_path.exists() {114 if new_path.exists() {
115 Ok(Rc::new(new_path))115 Ok(new_path.into())
116 } else {116 } else {
117 for library_path in self.library_paths.borrow().iter() {117 for library_path in self.library_paths.borrow().iter() {
118 let mut cloned = library_path.clone();118 let mut cloned = library_path.clone();
119 cloned.push(path);119 cloned.push(path);
120 if cloned.exists() {120 if cloned.exists() {
121 return Ok(Rc::new(cloned));121 return Ok(cloned.into());
122 }122 }
123 }123 }
124 throw!(ImportFileNotFound(from.clone(), path.clone()))124 throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
125 }125 }
126 }126 }
127 fn load_file_contents(&self, id: &PathBuf) -> Result<IStr> {127 fn load_file_contents(&self, id: &Path) -> Result<IStr> {
128 let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;128 let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;
129 let mut out = String::new();129 let mut out = String::new();
130 file.read_to_string(&mut out)130 file.read_to_string(&mut out)
131 .map_err(|_e| ImportBadFileUtf8(id.clone()))?;131 .map_err(|_e| ImportBadFileUtf8(id.to_owned()))?;
132 Ok(out.into())132 Ok(out.into())
133 }133 }
134 unsafe fn as_any(&self) -> &dyn Any {134 unsafe fn as_any(&self) -> &dyn Any {
modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
15 ffi::{CStr, CString},15 ffi::{CStr, CString},
16 os::raw::{c_char, c_double, c_int, c_uint},16 os::raw::{c_char, c_double, c_int, c_uint},
17 path::PathBuf,17 path::PathBuf,
18 rc::Rc,
19};18};
2019
21/// WASM stub20/// WASM stub
144 let snippet = CStr::from_ptr(snippet);143 let snippet = CStr::from_ptr(snippet);
145 match vm144 match vm
146 .evaluate_snippet_raw(145 .evaluate_snippet_raw(
147 Rc::new(PathBuf::from(filename.to_str().unwrap())),146 PathBuf::from(filename.to_str().unwrap()).into(),
148 snippet.to_str().unwrap().into(),147 snippet.to_str().unwrap().into(),
149 )148 )
150 .and_then(|v| vm.with_tla(v))149 .and_then(|v| vm.with_tla(v))
220 let snippet = CStr::from_ptr(snippet);219 let snippet = CStr::from_ptr(snippet);
221 match vm220 match vm
222 .evaluate_snippet_raw(221 .evaluate_snippet_raw(
223 Rc::new(PathBuf::from(filename.to_str().unwrap())),222 PathBuf::from(filename.to_str().unwrap()).into(),
224 snippet.to_str().unwrap().into(),223 snippet.to_str().unwrap().into(),
225 )224 )
226 .and_then(|v| vm.with_tla(v))225 .and_then(|v| vm.with_tla(v))
294 let snippet = CStr::from_ptr(snippet);293 let snippet = CStr::from_ptr(snippet);
295 match vm294 match vm
296 .evaluate_snippet_raw(295 .evaluate_snippet_raw(
297 Rc::new(PathBuf::from(filename.to_str().unwrap())),296 PathBuf::from(filename.to_str().unwrap()).into(),
298 snippet.to_str().unwrap().into(),297 snippet.to_str().unwrap().into(),
299 )298 )
300 .and_then(|v| vm.with_tla(v))299 .and_then(|v| vm.with_tla(v))
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
6 io::Read,6 io::Read,
7 io::Write,7 io::Write,
8 path::PathBuf,8 path::PathBuf,
9 rc::Rc,
10 str::FromStr,9 str::FromStr,
11};10};
1211
134 let val = if opts.input.exec {133 let val = if opts.input.exec {
135 state.set_manifest_format(ManifestFormat::ToString);134 state.set_manifest_format(ManifestFormat::ToString);
136 state.evaluate_snippet_raw(135 state.evaluate_snippet_raw(
137 Rc::new(PathBuf::from("args")),136 PathBuf::from("args").into(),
138 (&opts.input.input as &str).into(),137 (&opts.input.input as &str).into(),
139 )?138 )?
140 } else if opts.input.input == "-" {139 } else if opts.input.input == "-" {
141 let mut input = Vec::new();140 let mut input = Vec::new();
142 std::io::stdin().read_to_end(&mut input)?;141 std::io::stdin().read_to_end(&mut input)?;
143 let input_str = std::str::from_utf8(&input)?.into();142 let input_str = std::str::from_utf8(&input)?.into();
144 state.evaluate_snippet_raw(Rc::new(PathBuf::from("<stdin>")), input_str)?143 state.evaluate_snippet_raw(PathBuf::from("<stdin>").into(), input_str)?
145 } else {144 } else {
146 state.evaluate_file_raw(&PathBuf::from(opts.input.input))?145 state.evaluate_file_raw(&PathBuf::from(opts.input.input))?
147 };146 };
modifiedcrates/jrsonnet-evaluator/build.rsdiffbeforeafterboth
15 let parsed = parse(15 let parsed = parse(
16 STDLIB_STR,16 STDLIB_STR,
17 &ParserSettings {17 &ParserSettings {
18 file_name: Rc::new(PathBuf::from("std.jsonnet")),18 file_name: PathBuf::from("std.jsonnet").into(),
19 loc_data: true,19 loc_data: true,
20 },20 },
21 )21 )
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
174 0, s: ty!(string) => Val::Str;174 0, s: ty!(string) => Val::Str;
175 ], {175 ], {
176 let state = EvaluationState::default();176 let state = EvaluationState::default();
177 let path = Rc::new(PathBuf::from("std.parseJson"));177 let path = PathBuf::from("std.parseJson").into();
178 state.evaluate_snippet_raw(path ,s)178 state.evaluate_snippet_raw(path ,s)
179 })179 })
180}180}
modifiedcrates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth
1use jrsonnet_parser::{LocExpr, ParserSettings};1use jrsonnet_parser::{LocExpr, ParserSettings};
2use std::{path::PathBuf, rc::Rc};2use std::path::PathBuf;
33
4thread_local! {4thread_local! {
5 /// To avoid parsing again when issued from the same thread5 /// To avoid parsing again when issued from the same thread
25 jrsonnet_stdlib::STDLIB_STR,25 jrsonnet_stdlib::STDLIB_STR,
26 &ParserSettings {26 &ParserSettings {
27 loc_data: true,27 loc_data: true,
28 file_name: Rc::new(PathBuf::from("std.jsonnet")),28 file_name: PathBuf::from("std.jsonnet").into(),
29 },29 },
30 )30 )
31 .unwrap()31 .unwrap()
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
6use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};6use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
7use jrsonnet_types::ValType;7use jrsonnet_types::ValType;
8use std::{path::PathBuf, rc::Rc};8use std::{
9 path::{Path, PathBuf},
10 rc::Rc,
11};
9use thiserror::Error;12use thiserror::Error;
1013
86 .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())89 .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())
87 )]90 )]
88 ImportSyntaxError {91 ImportSyntaxError {
89 path: Rc<PathBuf>,92 path: Rc<Path>,
90 source_code: IStr,93 source_code: IStr,
91 error: Box<jrsonnet_parser::ParseError>,94 error: Box<jrsonnet_parser::ParseError>,
92 },95 },
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
609 }609 }
610 }610 }
611 Import(path) => {611 Import(path) => {
612 let mut tmp = loc612 let tmp = loc
613 .clone()613 .clone()
614 .expect("imports cannot be used without loc_data")614 .expect("imports cannot be used without loc_data")
615 .0;615 .0;
616 let import_location = Rc::make_mut(&mut tmp);616 let mut import_location = tmp.to_path_buf();
617 import_location.pop();617 import_location.pop();
618 push(618 push(
619 loc.as_ref(),619 loc.as_ref(),
620 || format!("import {:?}", path),620 || format!("import {:?}", path),
621 || with_state(|s| s.import_file(import_location, path)),621 || with_state(|s| s.import_file(&import_location, path)),
622 )?622 )?
623 }623 }
624 ImportStr(path) => {624 ImportStr(path) => {
625 let mut tmp = loc625 let tmp = loc
626 .clone()626 .clone()
627 .expect("imports cannot be used without loc_data")627 .expect("imports cannot be used without loc_data")
628 .0;628 .0;
629 let import_location = Rc::make_mut(&mut tmp);629 let mut import_location = tmp.to_path_buf();
630 import_location.pop();630 import_location.pop();
631 Val::Str(with_state(|s| s.import_file_str(import_location, path))?)631 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)
632 }632 }
633 })633 })
634}634}
modifiedcrates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth
10 any::Any,
11 cell::RefCell,
12 collections::HashMap,
13 path::{Path, PathBuf},
14 rc::Rc,
15};
1016
11/// Implements file resolution logic for `import` and `importStr`17/// Implements file resolution logic for `import` and `importStr`
12pub trait ImportResolver {18pub trait ImportResolver {
13 /// Resolves real file path, e.g. `(/home/user/manifests, b.libjsonnet)` can correspond19 /// Resolves real file path, e.g. `(/home/user/manifests, b.libjsonnet)` can correspond
14 /// both to `/home/user/manifests/b.libjsonnet` and to `/home/user/${vendor}/b.libjsonnet`20 /// both to `/home/user/manifests/b.libjsonnet` and to `/home/user/${vendor}/b.libjsonnet`
15 /// where `${vendor}` is a library path.21 /// where `${vendor}` is a library path.
16 fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>>;22 fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>>;
1723
18 /// Reads file from filesystem, should be used only with path received from `resolve_file`24 /// Reads file from filesystem, should be used only with path received from `resolve_file`
19 fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr>;25 fn load_file_contents(&self, resolved: &Path) -> Result<IStr>;
2026
21 /// # Safety27 /// # Safety
22 ///28 ///
29/// Dummy resolver, can't resolve/load any file35/// Dummy resolver, can't resolve/load any file
30pub struct DummyImportResolver;36pub struct DummyImportResolver;
31impl ImportResolver for DummyImportResolver {37impl ImportResolver for DummyImportResolver {
32 fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {38 fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
33 throw!(ImportNotSupported(from.clone(), path.clone()))39 throw!(ImportNotSupported(from.into(), path.into()))
34 }40 }
3541
36 fn load_file_contents(&self, _resolved: &PathBuf) -> Result<IStr> {42 fn load_file_contents(&self, _resolved: &Path) -> Result<IStr> {
37 // Can be only caused by library direct consumer, not by supplied jsonnet43 // Can be only caused by library direct consumer, not by supplied jsonnet
38 panic!("dummy resolver can't load any file")44 panic!("dummy resolver can't load any file")
39 }45 }
57 pub library_paths: Vec<PathBuf>,63 pub library_paths: Vec<PathBuf>,
58}64}
59impl ImportResolver for FileImportResolver {65impl ImportResolver for FileImportResolver {
60 fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {66 fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
61 let mut new_path = from.clone();67 let mut direct = from.to_path_buf();
62 new_path.push(path);68 direct.push(path);
63 if new_path.exists() {69 if direct.exists() {
64 Ok(Rc::new(new_path))70 Ok(direct.into())
65 } else {71 } else {
66 for library_path in self.library_paths.iter() {72 for library_path in self.library_paths.iter() {
67 let mut cloned = library_path.clone();73 let mut cloned = library_path.clone();
68 cloned.push(path);74 cloned.push(path);
69 if cloned.exists() {75 if cloned.exists() {
70 return Ok(Rc::new(cloned));76 return Ok(cloned.into());
71 }77 }
72 }78 }
73 throw!(ImportFileNotFound(from.clone(), path.clone()))79 throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
74 }80 }
75 }81 }
76 fn load_file_contents(&self, id: &PathBuf) -> Result<IStr> {82 fn load_file_contents(&self, id: &Path) -> Result<IStr> {
77 let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;83 let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;
78 let mut out = String::new();84 let mut out = String::new();
79 file.read_to_string(&mut out)85 file.read_to_string(&mut out)
80 .map_err(|_e| ImportBadFileUtf8(id.clone()))?;86 .map_err(|_e| ImportBadFileUtf8(id.to_owned()))?;
81 Ok(out.into())87 Ok(out.into())
82 }88 }
83 unsafe fn as_any(&self) -> &dyn Any {89 unsafe fn as_any(&self) -> &dyn Any {
8995
90/// Caches results of the underlying resolver96/// Caches results of the underlying resolver
91pub struct CachingImportResolver {97pub struct CachingImportResolver {
92 resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<PathBuf>>>>,98 resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<Path>>>>,
93 loading_cache: RefCell<HashMap<PathBuf, Result<IStr>>>,99 loading_cache: RefCell<HashMap<PathBuf, Result<IStr>>>,
94 inner: Box<dyn ImportResolver>,100 inner: Box<dyn ImportResolver>,
95}101}
96impl ImportResolver for CachingImportResolver {102impl ImportResolver for CachingImportResolver {
97 fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {103 fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
98 self.resolution_cache104 self.resolution_cache
99 .borrow_mut()105 .borrow_mut()
100 .entry((from.clone(), path.clone()))106 .entry((from.to_owned(), path.to_owned()))
101 .or_insert_with(|| self.inner.resolve_file(from, path))107 .or_insert_with(|| self.inner.resolve_file(from, path))
102 .clone()108 .clone()
103 }109 }
104110
105 fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr> {111 fn load_file_contents(&self, resolved: &Path) -> Result<IStr> {
106 self.loading_cache112 self.loading_cache
107 .borrow_mut()113 .borrow_mut()
108 .entry(resolved.clone())114 .entry(resolved.to_owned())
109 .or_insert_with(|| self.inner.load_file_contents(resolved))115 .or_insert_with(|| self.inner.load_file_contents(resolved))
110 .clone()116 .clone()
111 }117 }
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
3use crate::{error::Result, Val};3use crate::{error::Result, Val};
4use jrsonnet_parser::ParamsDesc;4use jrsonnet_parser::ParamsDesc;
5use std::fmt::Debug;5use std::fmt::Debug;
6use std::path::PathBuf;6use std::path::Path;
7use std::rc::Rc;7use std::rc::Rc;
88
9pub struct NativeCallback {9pub struct NativeCallback {
10 pub params: ParamsDesc,10 pub params: ParamsDesc,
11 handler: Box<dyn Fn(Option<Rc<PathBuf>>, &[Val]) -> Result<Val>>,11 handler: Box<dyn Fn(Option<Rc<Path>>, &[Val]) -> Result<Val>>,
12}12}
13impl NativeCallback {13impl NativeCallback {
14 pub fn new(14 pub fn new(
15 params: ParamsDesc,15 params: ParamsDesc,
16 handler: impl Fn(Option<Rc<PathBuf>>, &[Val]) -> Result<Val> + 'static,16 handler: impl Fn(Option<Rc<Path>>, &[Val]) -> Result<Val> + 'static,
17 ) -> Self {17 ) -> Self {
18 Self {18 Self {
19 params,19 params,
20 handler: Box::new(handler),20 handler: Box::new(handler),
21 }21 }
22 }22 }
23 pub fn call(&self, caller: Option<Rc<PathBuf>>, args: &[Val]) -> Result<Val> {23 pub fn call(&self, caller: Option<Rc<Path>>, args: &[Val]) -> Result<Val> {
24 (self.handler)(caller, args)24 (self.handler)(caller, args)
25 }25 }
26}26}
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
22
3use crate::{error::Error, EvaluationState, LocError};3use crate::{error::Error, EvaluationState, LocError};
4pub use location::*;4pub use location::*;
5use std::path::PathBuf;5use std::path::{Path, PathBuf};
66
7/// The way paths should be displayed7/// The way paths should be displayed
8pub enum PathResolver {8pub enum PathResolver {
15}15}
1616
17impl PathResolver {17impl PathResolver {
18 pub fn resolve(&self, from: &PathBuf) -> String {18 pub fn resolve(&self, from: &Path) -> String {
19 match self {19 match self {
20 Self::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),20 Self::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),
21 Self::Absolute => from.to_string_lossy().into_owned(),21 Self::Absolute => from.to_string_lossy().into_owned(),
255 &self,255 &self,
256 out: &mut dyn std::fmt::Write,256 out: &mut dyn std::fmt::Write,
257 source: &str,257 source: &str,
258 origin: &PathBuf,258 origin: &Path,
259 start: &CodeLocation,259 start: &CodeLocation,
260 end: &CodeLocation,260 end: &CodeLocation,
261 desc: &str,261 desc: &str,
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
6use std::{6use std::{
7 fmt::{Debug, Display},7 fmt::{Debug, Display},
8 ops::Deref,8 ops::Deref,
9 path::PathBuf,9 path::{Path, PathBuf},
10 rc::Rc,10 rc::Rc,
11};11};
1212
320#[cfg_attr(feature = "serialize", derive(Serialize))]320#[cfg_attr(feature = "serialize", derive(Serialize))]
321#[cfg_attr(feature = "deserialize", derive(Deserialize))]321#[cfg_attr(feature = "deserialize", derive(Deserialize))]
322#[derive(Clone, PartialEq)]322#[derive(Clone, PartialEq)]
323pub struct ExprLocation(pub Rc<PathBuf>, pub usize, pub usize);323pub struct ExprLocation(pub Rc<Path>, pub usize, pub usize);
324impl Debug for ExprLocation {324impl Debug for ExprLocation {
325 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {325 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
326 write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)326 write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
22
3use peg::parser;3use peg::parser;
4use std::{path::PathBuf, rc::Rc};4use std::{
5 path::{Path, PathBuf},
6 rc::Rc,
7};
5mod expr;8mod expr;
6pub use expr::*;9pub use expr::*;
7pub use peg;10pub use peg;
811
9#[derive(Default)]
10pub struct ParserSettings {12pub struct ParserSettings {
11 pub loc_data: bool,13 pub loc_data: bool,
12 pub file_name: Rc<PathBuf>,14 pub file_name: Rc<Path>,
13}15}
1416
15parser! {17parser! {
304 use super::{expr::*, parse};306 use super::{expr::*, parse};
305 use crate::ParserSettings;307 use crate::ParserSettings;
306 use std::path::PathBuf;308 use std::path::PathBuf;
307 use std::rc::Rc;
308309
309 macro_rules! parse {310 macro_rules! parse {
310 ($s:expr) => {311 ($s:expr) => {
311 parse(312 parse(
312 $s,313 $s,
313 &ParserSettings {314 &ParserSettings {
314 loc_data: false,315 loc_data: false,
315 file_name: Rc::new(PathBuf::from("/test.jsonnet")),316 file_name: PathBuf::from("/test.jsonnet").into(),
316 },317 },
317 )318 )
318 .unwrap()319 .unwrap()