difftreelog
style fix clippy warnings
in: master
35 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -68,6 +68,15 @@
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
+name = "block-buffer"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
name = "cc"
version = "1.0.73"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -141,6 +150,45 @@
]
[[package]]
+name = "cpufeatures"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adfbc57365a37acbd2ebf2b64d7e69bb766e2fea813521ed536f5d0520dcf86c"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
name = "getrandom"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -304,6 +352,7 @@
"serde",
"serde_json",
"serde_yaml_with_quirks",
+ "sha2",
"structdump",
]
@@ -550,6 +599,17 @@
]
[[package]]
+name = "sha2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"
+dependencies = [
+ "cfg-if 1.0.0",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
name = "smallvec"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -640,6 +700,12 @@
]
[[package]]
+name = "typenum"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
+
+[[package]]
name = "unicode-ident"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -12,7 +12,7 @@
};
use jrsonnet_evaluator::{
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
throw, FileImportResolver, ImportResolver,
};
use jrsonnet_gcmodule::Trace;
bindings/jsonnet/src/lib.rsdiffbeforeafterboth1#[cfg(feature = "interop")]2pub mod interop;34pub mod import;5pub mod native;6pub mod val_extract;7pub mod val_make;8pub mod val_modify;9pub mod vars_tlas;1011use std::{12 alloc::Layout,13 borrow::Cow,14 ffi::{CStr, CString, OsStr},15 os::raw::{c_char, c_double, c_int, c_uint},16 path::Path,17};1819use jrsonnet_evaluator::{20 apply_tla,21 function::TlaArg,22 gc::GcHashMap,23 stack::set_stack_depth_limit,24 stdlib::manifest::{JsonFormat, ToStringFormat},25 tb, throw,26 trace::{CompactFormat, PathResolver, TraceFormat},27 FileImportResolver, IStr, ManifestFormat, Result, State, Val,28};2930/// WASM stub31#[cfg(target_arch = "wasm32")]32#[no_mangle]33pub extern "C" fn _start() {}3435/// Return the version string of the Jsonnet interpreter.36/// Conforms to [semantic versioning](http://semver.org/).37/// If this does not match `LIB_JSONNET_VERSION`38/// then there is a mismatch between header and compiled library.39#[no_mangle]40pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {41 b"v0.16.0\0"42}4344unsafe fn parse_path(input: &CStr) -> Cow<Path> {45 #[cfg(target_family = "unix")]46 {47 use std::os::unix::ffi::OsStrExt;48 let str = OsStr::from_bytes(input.to_bytes());49 Cow::Borrowed(Path::new(str))50 }51 #[cfg(not(target_family = "unix"))]52 {53 let string = input.to_str().expect("bad utf-8");54 Cow::Borrowed(string.as_ref())55 }56}5758unsafe fn unparse_path(input: &Path) -> Cow<CStr> {59 #[cfg(target_family = "unix")]60 {61 use std::os::unix::ffi::OsStrExt;62 let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");63 Cow::Owned(str)64 }65 #[cfg(not(target_family = "unix"))]66 {67 let str = input.as_os_str().to_str().expect("bad utf-8");68 let cstr = CString::new(str).expect("input has NUL inside");69 Cow::Owned(cstr)70 }71}7273pub struct VM {74 state: State,75 manifest_format: Box<dyn ManifestFormat>,76 trace_format: Box<dyn TraceFormat>,77 tla_args: GcHashMap<IStr, TlaArg>,78}7980/// Creates a new Jsonnet virtual machine.81#[no_mangle]82#[allow(clippy::box_default)]83pub extern "C" fn jsonnet_make() -> *mut VM {84 let state = State::default();85 state.settings_mut().import_resolver = tb!(FileImportResolver::default());86 state.settings_mut().context_initializer = tb!(jrsonnet_stdlib::ContextInitializer::new(87 state.clone(),88 PathResolver::new_cwd_fallback(),89 ));90 Box::into_raw(Box::new(VM {91 state,92 manifest_format: Box::new(JsonFormat::default()),93 trace_format: Box::new(CompactFormat::default()),94 tla_args: GcHashMap::new(),95 }))96}9798/// Complement of [`jsonnet_vm_make`].99#[no_mangle]100#[allow(clippy::boxed_local)]101pub extern "C" fn jsonnet_destroy(vm: Box<VM>) {102 drop(vm);103}104105/// Set the maximum stack depth.106#[no_mangle]107pub extern "C" fn jsonnet_max_stack(_vm: &VM, v: c_uint) {108 set_stack_depth_limit(v as usize)109}110111/// Set the number of objects required before a garbage collection cycle is allowed.112///113/// No-op for now114#[no_mangle]115pub extern "C" fn jsonnet_gc_min_objects(_vm: &VM, _v: c_uint) {}116117/// Run the garbage collector after this amount of growth in the number of objects118///119/// No-op for now120#[no_mangle]121pub extern "C" fn jsonnet_gc_growth_trigger(_vm: &VM, _v: c_double) {}122123/// Expect a string as output and don't JSON encode it.124#[no_mangle]125pub extern "C" fn jsonnet_string_output(vm: &mut VM, v: c_int) {126 vm.manifest_format = match v {127 0 => Box::new(JsonFormat::default()),128 1 => Box::new(ToStringFormat),129 _ => panic!("incorrect output format"),130 };131}132133/// Allocate, resize, or free a buffer. This will abort if the memory cannot be allocated. It will134/// only return NULL if sz was zero.135///136/// # Safety137///138/// `buf` should be either previosly allocated by this library, or NULL139///140/// This function is most definitely broken, but it works somehow, see TODO inside141#[no_mangle]142pub unsafe extern "C" fn jsonnet_realloc(_vm: &VM, buf: *mut u8, sz: usize) -> *mut u8 {143 if buf.is_null() {144 if sz == 0 {145 return std::ptr::null_mut();146 }147 return std::alloc::alloc(Layout::from_size_align(sz, std::mem::align_of::<u8>()).unwrap());148 }149 // TODO: Somehow store size of allocation, because its real size is probally not 16 :D150 // OR (Alternative way of fixing this TODO)151 // TODO: Standard allocator uses malloc, and it doesn't uses allocation size,152 // TODO: so it should work in normal cases. Maybe force allocator for this library?153 let old_layout = Layout::from_size_align(16, std::mem::align_of::<u8>()).unwrap();154 if sz == 0 {155 std::alloc::dealloc(buf, old_layout);156 return std::ptr::null_mut();157 }158 std::alloc::realloc(buf, old_layout, sz)159}160161/// Clean up a JSON subtree.162///163/// This is useful if you want to abort with an error mid-way through building a complex value.164#[no_mangle]165#[allow(clippy::boxed_local)]166pub extern "C" fn jsonnet_json_destroy(_vm: &VM, v: Box<Val>) {167 drop(v);168}169170/// Set the number of lines of stack trace to display (0 for all of them).171#[no_mangle]172pub extern "C" fn jsonnet_max_trace(vm: &mut VM, v: c_uint) {173 if let Some(format) = vm.trace_format.as_any_mut().downcast_mut::<CompactFormat>() {174 format.max_trace = v as usize175 } else {176 panic!("max_trace is not supported by current tracing format")177 }178}179180/// Evaluate a file containing Jsonnet code, return a JSON string.181///182/// The returned string should be cleaned up with jsonnet_realloc.183///184/// # Safety185///186/// `filename` should be a NUL-terminated string187#[no_mangle]188pub unsafe extern "C" fn jsonnet_evaluate_file(189 vm: &VM,190 filename: *const c_char,191 error: &mut c_int,192) -> *const c_char {193 let filename = parse_path(CStr::from_ptr(filename));194 match vm195 .state196 .import(&filename)197 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))198 .and_then(|val| val.manifest(&vm.manifest_format))199 {200 Ok(v) => {201 *error = 0;202 CString::new(&*v as &str).unwrap().into_raw()203 }204 Err(e) => {205 *error = 1;206 let mut out = String::new();207 vm.trace_format.write_trace(&mut out, &e).unwrap();208 CString::new(&out as &str).unwrap().into_raw()209 }210 }211}212213/// Evaluate a string containing Jsonnet code, return a JSON string.214///215/// The returned string should be cleaned up with jsonnet_realloc.216///217/// # Safety218///219/// `filename`, `snippet` should be a NUL-terminated strings220#[no_mangle]221pub unsafe extern "C" fn jsonnet_evaluate_snippet(222 vm: &VM,223 filename: *const c_char,224 snippet: *const c_char,225 error: &mut c_int,226) -> *const c_char {227 let filename = CStr::from_ptr(filename);228 let snippet = CStr::from_ptr(snippet);229 match vm230 .state231 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())232 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))233 .and_then(|val| val.manifest(&vm.manifest_format))234 {235 Ok(v) => {236 *error = 0;237 CString::new(&*v as &str).unwrap().into_raw()238 }239 Err(e) => {240 *error = 1;241 let mut out = String::new();242 vm.trace_format.write_trace(&mut out, &e).unwrap();243 CString::new(&out as &str).unwrap().into_raw()244 }245 }246}247248fn val_to_multi(val: Val, format: &dyn ManifestFormat) -> Result<Vec<(IStr, IStr)>> {249 let Val::Obj(val) = val else {250 throw!("expected object as multi output")251 };252 let mut out = Vec::new();253 for (k, v) in val.iter(254 #[cfg(feature = "exp-preserve-order")]255 false,256 ) {257 out.push((k, v?.manifest(format)?.into()));258 }259 Ok(out)260}261262fn multi_to_raw(multi: Vec<(IStr, IStr)>) -> *const c_char {263 let mut out = Vec::new();264 for (i, (k, v)) in multi.iter().enumerate() {265 if i != 0 {266 out.push(0);267 }268 out.extend_from_slice(k.as_bytes());269 out.push(0);270 out.extend_from_slice(v.as_bytes());271 }272 out.push(0);273 out.push(0);274 let v = out.as_ptr();275 std::mem::forget(out);276 v as *const c_char277}278279/// # Safety280#[no_mangle]281pub unsafe extern "C" fn jsonnet_evaluate_file_multi(282 vm: &VM,283 filename: *const c_char,284 error: &mut c_int,285) -> *const c_char {286 let filename = parse_path(CStr::from_ptr(filename));287 match vm288 .state289 .import(&filename)290 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))291 .and_then(|val| val_to_multi(val, &vm.manifest_format))292 {293 Ok(v) => {294 *error = 0;295 multi_to_raw(v)296 }297 Err(e) => {298 *error = 1;299 let mut out = String::new();300 vm.trace_format.write_trace(&mut out, &e).unwrap();301 CString::new(&out as &str).unwrap().into_raw()302 }303 }304}305306/// # Safety307#[no_mangle]308pub unsafe extern "C" fn jsonnet_evaluate_snippet_multi(309 vm: &VM,310 filename: *const c_char,311 snippet: *const c_char,312 error: &mut c_int,313) -> *const c_char {314 let filename = CStr::from_ptr(filename);315 let snippet = CStr::from_ptr(snippet);316 match vm317 .state318 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())319 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))320 .and_then(|val| val_to_multi(val, &vm.manifest_format))321 {322 Ok(v) => {323 *error = 0;324 multi_to_raw(v)325 }326 Err(e) => {327 *error = 1;328 let mut out = String::new();329 vm.trace_format.write_trace(&mut out, &e).unwrap();330 CString::new(&out as &str).unwrap().into_raw()331 }332 }333}334335fn val_to_stream(val: Val, format: &dyn ManifestFormat) -> Result<Vec<IStr>> {336 let Val::Arr(val) = val else {337 throw!("expected array as stream output")338 };339 let mut out = Vec::new();340 for item in val.iter() {341 out.push(item?.manifest(format)?.into());342 }343 Ok(out)344}345346fn stream_to_raw(multi: Vec<IStr>) -> *const c_char {347 let mut out = Vec::new();348 for (i, v) in multi.iter().enumerate() {349 if i != 0 {350 out.push(0);351 }352 out.extend_from_slice(v.as_bytes());353 }354 out.push(0);355 out.push(0);356 let v = out.as_ptr();357 std::mem::forget(out);358 v as *const c_char359}360361/// # Safety362#[no_mangle]363pub unsafe extern "C" fn jsonnet_evaluate_file_stream(364 vm: &VM,365 filename: *const c_char,366 error: &mut c_int,367) -> *const c_char {368 let filename = parse_path(CStr::from_ptr(filename));369 match vm370 .state371 .import(filename)372 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))373 .and_then(|val| val_to_stream(val, &vm.manifest_format))374 {375 Ok(v) => {376 *error = 0;377 stream_to_raw(v)378 }379 Err(e) => {380 *error = 1;381 let mut out = String::new();382 vm.trace_format.write_trace(&mut out, &e).unwrap();383 CString::new(&out as &str).unwrap().into_raw()384 }385 }386}387388/// # Safety389#[no_mangle]390pub unsafe extern "C" fn jsonnet_evaluate_snippet_stream(391 vm: &VM,392 filename: *const c_char,393 snippet: *const c_char,394 error: &mut c_int,395) -> *const c_char {396 let filename = CStr::from_ptr(filename);397 let snippet = CStr::from_ptr(snippet);398 match vm399 .state400 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())401 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))402 .and_then(|val| val_to_stream(val, &vm.manifest_format))403 {404 Ok(v) => {405 *error = 0;406 stream_to_raw(v)407 }408 Err(e) => {409 *error = 1;410 let mut out = String::new();411 vm.trace_format.write_trace(&mut out, &e).unwrap();412 CString::new(&out as &str).unwrap().into_raw()413 }414 }415}1#![allow(clippy::box_default)]23#[cfg(feature = "interop")]4pub mod interop;56pub mod import;7pub mod native;8pub mod val_extract;9pub mod val_make;10pub mod val_modify;11pub mod vars_tlas;1213use std::{14 alloc::Layout,15 borrow::Cow,16 ffi::{CStr, CString, OsStr},17 os::raw::{c_char, c_double, c_int, c_uint},18 path::Path,19};2021use jrsonnet_evaluator::{22 apply_tla,23 function::TlaArg,24 gc::GcHashMap,25 manifest::{JsonFormat, ManifestFormat, ToStringFormat},26 stack::set_stack_depth_limit,27 tb, throw,28 trace::{CompactFormat, PathResolver, TraceFormat},29 FileImportResolver, IStr, Result, State, Val,30};3132/// WASM stub33#[cfg(target_arch = "wasm32")]34#[no_mangle]35pub extern "C" fn _start() {}3637/// Return the version string of the Jsonnet interpreter.38/// Conforms to [semantic versioning](http://semver.org/).39/// If this does not match `LIB_JSONNET_VERSION`40/// then there is a mismatch between header and compiled library.41#[no_mangle]42pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {43 b"v0.16.0\0"44}4546unsafe fn parse_path(input: &CStr) -> Cow<Path> {47 #[cfg(target_family = "unix")]48 {49 use std::os::unix::ffi::OsStrExt;50 let str = OsStr::from_bytes(input.to_bytes());51 Cow::Borrowed(Path::new(str))52 }53 #[cfg(not(target_family = "unix"))]54 {55 let string = input.to_str().expect("bad utf-8");56 Cow::Borrowed(string.as_ref())57 }58}5960unsafe fn unparse_path(input: &Path) -> Cow<CStr> {61 #[cfg(target_family = "unix")]62 {63 use std::os::unix::ffi::OsStrExt;64 let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");65 Cow::Owned(str)66 }67 #[cfg(not(target_family = "unix"))]68 {69 let str = input.as_os_str().to_str().expect("bad utf-8");70 let cstr = CString::new(str).expect("input has NUL inside");71 Cow::Owned(cstr)72 }73}7475pub struct VM {76 state: State,77 manifest_format: Box<dyn ManifestFormat>,78 trace_format: Box<dyn TraceFormat>,79 tla_args: GcHashMap<IStr, TlaArg>,80}8182/// Creates a new Jsonnet virtual machine.83#[no_mangle]84#[allow(clippy::box_default)]85pub extern "C" fn jsonnet_make() -> *mut VM {86 let state = State::default();87 state.settings_mut().import_resolver = tb!(FileImportResolver::default());88 state.settings_mut().context_initializer = tb!(jrsonnet_stdlib::ContextInitializer::new(89 state.clone(),90 PathResolver::new_cwd_fallback(),91 ));92 Box::into_raw(Box::new(VM {93 state,94 manifest_format: Box::new(JsonFormat::default()),95 trace_format: Box::new(CompactFormat::default()),96 tla_args: GcHashMap::new(),97 }))98}99100/// Complement of [`jsonnet_vm_make`].101#[no_mangle]102#[allow(clippy::boxed_local)]103pub extern "C" fn jsonnet_destroy(vm: Box<VM>) {104 drop(vm);105}106107/// Set the maximum stack depth.108#[no_mangle]109pub extern "C" fn jsonnet_max_stack(_vm: &VM, v: c_uint) {110 set_stack_depth_limit(v as usize)111}112113/// Set the number of objects required before a garbage collection cycle is allowed.114///115/// No-op for now116#[no_mangle]117pub extern "C" fn jsonnet_gc_min_objects(_vm: &VM, _v: c_uint) {}118119/// Run the garbage collector after this amount of growth in the number of objects120///121/// No-op for now122#[no_mangle]123pub extern "C" fn jsonnet_gc_growth_trigger(_vm: &VM, _v: c_double) {}124125/// Expect a string as output and don't JSON encode it.126#[no_mangle]127pub extern "C" fn jsonnet_string_output(vm: &mut VM, v: c_int) {128 vm.manifest_format = match v {129 0 => Box::new(JsonFormat::default()),130 1 => Box::new(ToStringFormat),131 _ => panic!("incorrect output format"),132 };133}134135/// Allocate, resize, or free a buffer. This will abort if the memory cannot be allocated. It will136/// only return NULL if sz was zero.137///138/// # Safety139///140/// `buf` should be either previosly allocated by this library, or NULL141///142/// This function is most definitely broken, but it works somehow, see TODO inside143#[no_mangle]144pub unsafe extern "C" fn jsonnet_realloc(_vm: &VM, buf: *mut u8, sz: usize) -> *mut u8 {145 if buf.is_null() {146 if sz == 0 {147 return std::ptr::null_mut();148 }149 return std::alloc::alloc(Layout::from_size_align(sz, std::mem::align_of::<u8>()).unwrap());150 }151 // TODO: Somehow store size of allocation, because its real size is probally not 16 :D152 // OR (Alternative way of fixing this TODO)153 // TODO: Standard allocator uses malloc, and it doesn't uses allocation size,154 // TODO: so it should work in normal cases. Maybe force allocator for this library?155 let old_layout = Layout::from_size_align(16, std::mem::align_of::<u8>()).unwrap();156 if sz == 0 {157 std::alloc::dealloc(buf, old_layout);158 return std::ptr::null_mut();159 }160 std::alloc::realloc(buf, old_layout, sz)161}162163/// Clean up a JSON subtree.164///165/// This is useful if you want to abort with an error mid-way through building a complex value.166#[no_mangle]167#[allow(clippy::boxed_local)]168pub extern "C" fn jsonnet_json_destroy(_vm: &VM, v: Box<Val>) {169 drop(v);170}171172/// Set the number of lines of stack trace to display (0 for all of them).173#[no_mangle]174pub extern "C" fn jsonnet_max_trace(vm: &mut VM, v: c_uint) {175 if let Some(format) = vm.trace_format.as_any_mut().downcast_mut::<CompactFormat>() {176 format.max_trace = v as usize177 } else {178 panic!("max_trace is not supported by current tracing format")179 }180}181182/// Evaluate a file containing Jsonnet code, return a JSON string.183///184/// The returned string should be cleaned up with jsonnet_realloc.185///186/// # Safety187///188/// `filename` should be a NUL-terminated string189#[no_mangle]190pub unsafe extern "C" fn jsonnet_evaluate_file(191 vm: &VM,192 filename: *const c_char,193 error: &mut c_int,194) -> *const c_char {195 let filename = parse_path(CStr::from_ptr(filename));196 match vm197 .state198 .import(filename)199 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))200 .and_then(|val| val.manifest(&vm.manifest_format))201 {202 Ok(v) => {203 *error = 0;204 CString::new(&*v as &str).unwrap().into_raw()205 }206 Err(e) => {207 *error = 1;208 let mut out = String::new();209 vm.trace_format.write_trace(&mut out, &e).unwrap();210 CString::new(&out as &str).unwrap().into_raw()211 }212 }213}214215/// Evaluate a string containing Jsonnet code, return a JSON string.216///217/// The returned string should be cleaned up with jsonnet_realloc.218///219/// # Safety220///221/// `filename`, `snippet` should be a NUL-terminated strings222#[no_mangle]223pub unsafe extern "C" fn jsonnet_evaluate_snippet(224 vm: &VM,225 filename: *const c_char,226 snippet: *const c_char,227 error: &mut c_int,228) -> *const c_char {229 let filename = CStr::from_ptr(filename);230 let snippet = CStr::from_ptr(snippet);231 match vm232 .state233 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())234 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))235 .and_then(|val| val.manifest(&vm.manifest_format))236 {237 Ok(v) => {238 *error = 0;239 CString::new(&*v as &str).unwrap().into_raw()240 }241 Err(e) => {242 *error = 1;243 let mut out = String::new();244 vm.trace_format.write_trace(&mut out, &e).unwrap();245 CString::new(&out as &str).unwrap().into_raw()246 }247 }248}249250fn val_to_multi(val: Val, format: &dyn ManifestFormat) -> Result<Vec<(IStr, IStr)>> {251 let Val::Obj(val) = val else {252 throw!("expected object as multi output")253 };254 let mut out = Vec::new();255 for (k, v) in val.iter(256 #[cfg(feature = "exp-preserve-order")]257 false,258 ) {259 out.push((k, v?.manifest(format)?.into()));260 }261 Ok(out)262}263264fn multi_to_raw(multi: Vec<(IStr, IStr)>) -> *const c_char {265 let mut out = Vec::new();266 for (i, (k, v)) in multi.iter().enumerate() {267 if i != 0 {268 out.push(0);269 }270 out.extend_from_slice(k.as_bytes());271 out.push(0);272 out.extend_from_slice(v.as_bytes());273 }274 out.push(0);275 out.push(0);276 let v = out.as_ptr();277 std::mem::forget(out);278 v as *const c_char279}280281/// # Safety282#[no_mangle]283pub unsafe extern "C" fn jsonnet_evaluate_file_multi(284 vm: &VM,285 filename: *const c_char,286 error: &mut c_int,287) -> *const c_char {288 let filename = parse_path(CStr::from_ptr(filename));289 match vm290 .state291 .import(filename)292 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))293 .and_then(|val| val_to_multi(val, &vm.manifest_format))294 {295 Ok(v) => {296 *error = 0;297 multi_to_raw(v)298 }299 Err(e) => {300 *error = 1;301 let mut out = String::new();302 vm.trace_format.write_trace(&mut out, &e).unwrap();303 CString::new(&out as &str).unwrap().into_raw()304 }305 }306}307308/// # Safety309#[no_mangle]310pub unsafe extern "C" fn jsonnet_evaluate_snippet_multi(311 vm: &VM,312 filename: *const c_char,313 snippet: *const c_char,314 error: &mut c_int,315) -> *const c_char {316 let filename = CStr::from_ptr(filename);317 let snippet = CStr::from_ptr(snippet);318 match vm319 .state320 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())321 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))322 .and_then(|val| val_to_multi(val, &vm.manifest_format))323 {324 Ok(v) => {325 *error = 0;326 multi_to_raw(v)327 }328 Err(e) => {329 *error = 1;330 let mut out = String::new();331 vm.trace_format.write_trace(&mut out, &e).unwrap();332 CString::new(&out as &str).unwrap().into_raw()333 }334 }335}336337fn val_to_stream(val: Val, format: &dyn ManifestFormat) -> Result<Vec<IStr>> {338 let Val::Arr(val) = val else {339 throw!("expected array as stream output")340 };341 let mut out = Vec::new();342 for item in val.iter() {343 out.push(item?.manifest(format)?.into());344 }345 Ok(out)346}347348fn stream_to_raw(multi: Vec<IStr>) -> *const c_char {349 let mut out = Vec::new();350 for (i, v) in multi.iter().enumerate() {351 if i != 0 {352 out.push(0);353 }354 out.extend_from_slice(v.as_bytes());355 }356 out.push(0);357 out.push(0);358 let v = out.as_ptr();359 std::mem::forget(out);360 v as *const c_char361}362363/// # Safety364#[no_mangle]365pub unsafe extern "C" fn jsonnet_evaluate_file_stream(366 vm: &VM,367 filename: *const c_char,368 error: &mut c_int,369) -> *const c_char {370 let filename = parse_path(CStr::from_ptr(filename));371 match vm372 .state373 .import(filename)374 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))375 .and_then(|val| val_to_stream(val, &vm.manifest_format))376 {377 Ok(v) => {378 *error = 0;379 stream_to_raw(v)380 }381 Err(e) => {382 *error = 1;383 let mut out = String::new();384 vm.trace_format.write_trace(&mut out, &e).unwrap();385 CString::new(&out as &str).unwrap().into_raw()386 }387 }388}389390/// # Safety391#[no_mangle]392pub unsafe extern "C" fn jsonnet_evaluate_snippet_stream(393 vm: &VM,394 filename: *const c_char,395 snippet: *const c_char,396 error: &mut c_int,397) -> *const c_char {398 let filename = CStr::from_ptr(filename);399 let snippet = CStr::from_ptr(snippet);400 match vm401 .state402 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())403 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))404 .and_then(|val| val_to_stream(val, &vm.manifest_format))405 {406 Ok(v) => {407 *error = 0;408 stream_to_raw(v)409 }410 Err(e) => {411 *error = 1;412 let mut out = String::new();413 vm.trace_format.write_trace(&mut out, &e).unwrap();414 CString::new(&out as &str).unwrap().into_raw()415 }416 }417}bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -5,7 +5,7 @@
};
use jrsonnet_evaluator::{
- error::{Error, LocError},
+ error::{Error, ErrorKind},
function::builtin::{NativeCallback, NativeCallbackHandler},
tb,
typed::Typed,
@@ -38,7 +38,7 @@
cb: JsonnetNativeCallback,
}
impl NativeCallbackHandler for JsonnetNativeCallbackHandler {
- fn call(&self, args: &[Val]) -> Result<Val, LocError> {
+ fn call(&self, args: &[Val]) -> Result<Val, Error> {
let mut n_args = Vec::new();
for a in args {
n_args.push(Some(Box::new(a.clone())));
@@ -57,7 +57,7 @@
Ok(v)
} else {
let e = IStr::from_untyped(v).expect("error msg should be a string");
- Err(Error::RuntimeError(e).into())
+ Err(ErrorKind::RuntimeError(e).into())
}
}
}
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -6,7 +6,11 @@
use clap::{CommandFactory, Parser};
use clap_complete::Shell;
use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts, TraceOpts};
-use jrsonnet_evaluator::{apply_tla, error::LocError, throw, ResultExt, State, Val};
+use jrsonnet_evaluator::{
+ apply_tla,
+ error::{Error as JrError, ErrorKind},
+ throw, ResultExt, State, Val,
+};
#[cfg(feature = "mimalloc")]
#[global_allocator]
@@ -96,7 +100,7 @@
enum Error {
// Handled differently
#[error("evaluation error")]
- Evaluation(LocError),
+ Evaluation(JrError),
#[error("io error")]
Io(#[from] std::io::Error),
#[error("input is not utf8 encoded")]
@@ -104,14 +108,14 @@
#[error("missing input argument")]
MissingInputArgument,
}
-impl From<LocError> for Error {
- fn from(e: LocError) -> Self {
+impl From<JrError> for Error {
+ fn from(e: JrError) -> Self {
Self::Evaluation(e)
}
}
-impl From<jrsonnet_evaluator::error::Error> for Error {
- fn from(e: jrsonnet_evaluator::error::Error) -> Self {
- Self::from(LocError::from(e))
+impl From<ErrorKind> for Error {
+ fn from(e: ErrorKind) -> Self {
+ Self::from(JrError::from(e))
}
}
crates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -3,9 +3,10 @@
use clap::{Parser, ValueEnum};
use jrsonnet_evaluator::{
error::Result,
- stdlib::manifest::{JsonFormat, StringFormat, ToStringFormat, YamlFormat, YamlStreamFormat},
- ManifestFormat, State,
+ manifest::{JsonFormat, ManifestFormat, StringFormat, ToStringFormat, YamlStreamFormat},
+ State,
};
+use jrsonnet_stdlib::YamlFormat;
use crate::ConfigureState;
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,6 +1,6 @@
use clap::Parser;
use jrsonnet_evaluator::{
- error::{Error, Result},
+ error::{ErrorKind, Result},
function::TlaArg,
gc::GcHashMap,
IStr, State,
@@ -51,15 +51,15 @@
{
let source = Source::new_virtual(format!("<top-level-arg:{name}>").into(), code.into());
out.insert(
- (&name as &str).into(),
+ (name as &str).into(),
TlaArg::Code(
jrsonnet_parser::parse(
- &code,
+ code,
&ParserSettings {
source: source.clone(),
},
)
- .map_err(|e| Error::ImportSyntaxError {
+ .map_err(|e| ErrorKind::ImportSyntaxError {
path: source,
error: Box::new(e),
})?,
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -4,8 +4,8 @@
use jrsonnet_interner::IStr;
use crate::{
- error::Error::*, gc::GcHashMap, map::LayeredHashMap, ObjValue, Pending, Result, State, Thunk,
- Val,
+ error::ErrorKind::*, gc::GcHashMap, map::LayeredHashMap, ObjValue, Pending, Result, State,
+ Thunk, Val,
};
#[derive(Trace)]
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -74,7 +74,7 @@
#[allow(missing_docs)]
#[derive(Error, Debug, Clone, Trace)]
#[non_exhaustive]
-pub enum Error {
+pub enum ErrorKind {
#[error("intrinsic not found: {0}")]
IntrinsicNotFound(IStr),
@@ -211,14 +211,14 @@
}
#[cfg(feature = "anyhow-error")]
-impl From<anyhow::Error> for LocError {
+impl From<anyhow::Error> for Error {
fn from(e: anyhow::Error) -> Self {
- Self::new(Error::Other(Rc::new(e)))
+ Self::new(ErrorKind::Other(Rc::new(e)))
}
}
-impl From<Error> for LocError {
- fn from(e: Error) -> Self {
+impl From<ErrorKind> for Error {
+ fn from(e: ErrorKind) -> Self {
Self::new(e)
}
}
@@ -236,16 +236,16 @@
pub struct StackTrace(pub Vec<StackTraceElement>);
#[derive(Clone, Trace)]
-pub struct LocError(Box<(Error, StackTrace)>);
-impl LocError {
- pub fn new(e: Error) -> Self {
+pub struct Error(Box<(ErrorKind, StackTrace)>);
+impl Error {
+ pub fn new(e: ErrorKind) -> Self {
Self(Box::new((e, StackTrace(vec![]))))
}
- pub const fn error(&self) -> &Error {
+ pub const fn error(&self) -> &ErrorKind {
&(self.0).0
}
- pub fn error_mut(&mut self) -> &mut Error {
+ pub fn error_mut(&mut self) -> &mut ErrorKind {
&mut (self.0).0
}
pub const fn trace(&self) -> &StackTrace {
@@ -255,7 +255,7 @@
&mut (self.0).1
}
}
-impl Display for LocError {
+impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.0 .0)?;
for el in &self.0 .1 .0 {
@@ -269,7 +269,7 @@
Ok(())
}
}
-impl Debug for LocError {
+impl Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("LocError").field(&self.0).finish()
}
@@ -294,7 +294,7 @@
}
}
-pub type Result<V, E = LocError> = std::result::Result<V, E>;
+pub type Result<V, E = Error> = std::result::Result<V, E>;
pub trait ResultExt: Sized {
#[must_use]
fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;
@@ -314,7 +314,7 @@
self.with_description_src(src, || msg)
}
}
-impl<T> ResultExt for Result<T, LocError> {
+impl<T> ResultExt for Result<T, Error> {
fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {
if let Err(e) = &mut self {
let trace = e.trace_mut();
@@ -348,9 +348,9 @@
return Err($w$(::$i)*$(($($tt)*))?.into())
};
($l:literal) => {
- return Err($crate::error::Error::RuntimeError($l.into()).into())
+ return Err($crate::error::ErrorKind::RuntimeError($l.into()).into())
};
($l:literal, $($tt:tt)*) => {
- return Err($crate::error::Error::RuntimeError(format!($l, $($tt)*).into()).into())
+ return Err($crate::error::ErrorKind::RuntimeError(format!($l, $($tt)*).into()).into())
};
}
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -3,7 +3,7 @@
use jrsonnet_parser::{BindSpec, Destruct, LocExpr, ParamsDesc};
use crate::{
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
evaluate, evaluate_method, evaluate_named,
gc::GcHashMap,
tb, throw,
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -11,14 +11,14 @@
use self::destructure::destruct;
use crate::{
destructure::evaluate_dest,
- error::Error::*,
+ error::ErrorKind::*,
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
function::{CallLocation, FuncDesc, FuncVal},
tb, throw,
typed::Typed,
val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},
- Context, GcHashMap, LocError, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
- ResultExt, State, Unbound, Val,
+ Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,
+ Unbound, Val,
};
pub mod destructure;
pub mod operator;
@@ -165,7 +165,7 @@
uctx: B,
field: &FieldMember,
) -> Result<()> {
- let name = evaluate_field_name(ctx.clone(), &field.name)?;
+ let name = evaluate_field_name(ctx, &field.name)?;
let Some(name) = name else {
return Ok(());
};
@@ -187,11 +187,7 @@
impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {
type Bound = Val;
fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {
- Ok(evaluate_named(
- self.uctx.bind(sup, this)?,
- &self.value,
- self.name.clone(),
- )?)
+ evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())
}
}
@@ -201,9 +197,9 @@
.with_visibility(*visibility)
.with_location(value.1.clone())
.bindable(tb!(UnboundValue {
- uctx: uctx.clone(),
+ uctx,
value: value.clone(),
- name: name.clone()
+ name,
}))?;
}
FieldMember {
@@ -236,10 +232,10 @@
.with_visibility(*visibility)
.with_location(value.1.clone())
.bindable(tb!(UnboundMethod {
- uctx: uctx.clone(),
+ uctx,
value: value.clone(),
params: params.clone(),
- name: name.clone()
+ name,
}))?;
}
}
@@ -267,7 +263,7 @@
for member in members.iter() {
match member {
Member::Field(field) => {
- evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), &field)?
+ evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;
}
Member::AssertStmt(stmt) => {
#[derive(Trace)]
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -3,7 +3,7 @@
use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
use crate::{
- error::Error::*, evaluate, stdlib::std_format, throw, typed::Typed, val::equals, Context,
+ error::ErrorKind::*, evaluate, stdlib::std_format, throw, typed::Typed, val::equals, Context,
Result, Val,
};
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -180,8 +180,8 @@
}
}
-impl<A: ArgLike, S> sealed::Named for HashMap<IStr, A, S> {}
-impl<A: ArgLike, S> ArgsLike for HashMap<IStr, A, S> {
+impl<V: ArgLike, S> sealed::Named for HashMap<IStr, V, S> {}
+impl<V: ArgLike, S> ArgsLike for HashMap<IStr, V, S> {
fn unnamed_len(&self) -> usize {
0
}
@@ -213,7 +213,7 @@
}
}
}
-impl<A, S> OptionalContext for HashMap<IStr, A, S> where A: ArgLike + OptionalContext {}
+impl<V, S> OptionalContext for HashMap<IStr, V, S> where V: ArgLike + OptionalContext {}
impl<A: ArgLike> ArgsLike for GcHashMap<IStr, A> {
fn unnamed_len(&self) -> usize {
@@ -239,7 +239,7 @@
}
fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
- self.0.named_names(handler)
+ self.0.named_names(handler);
}
}
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -7,7 +7,7 @@
use super::{arglike::ArgsLike, builtin::BuiltinParam};
use crate::{
destructure::destruct,
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
evaluate_named,
gc::GcHashMap,
tb, throw,
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -12,10 +12,7 @@
use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
use crate::{
- error::{
- Error::{self, *},
- Result,
- },
+ error::{ErrorKind::*, Result},
throw,
};
@@ -94,7 +91,7 @@
} else if let Some(d) = from.downcast_ref::<SourceDirectory>() {
d.path().to_owned()
} else if from.is_default() {
- current_dir().map_err(|e| Error::ImportIo(e.to_string()))?
+ current_dir().map_err(|e| ImportIo(e.to_string()))?
} else {
unreachable!("resolver can't return this path")
};
@@ -122,7 +119,7 @@
Err(e) if e.kind() == ErrorKind::NotFound => {
throw!(AbsoluteImportFileNotFound(path.to_owned()))
}
- Err(e) => throw!(Error::ImportIo(e.to_string())),
+ Err(e) => throw!(ImportIo(e.to_string())),
};
if meta.is_file() {
Ok(SourcePath::new(SourceFile::new(
@@ -141,7 +138,7 @@
let path = if let Some(f) = id.downcast_ref::<SourceFile>() {
f.path()
} else if id.downcast_ref::<SourceDirectory>().is_some() || id.is_default() {
- throw!(Error::ImportIsADirectory(id.clone()))
+ throw!(ImportIsADirectory(id.clone()))
} else {
unreachable!("other types are not supported in resolve");
};
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -51,6 +51,7 @@
pub mod gc;
mod import;
mod integrations;
+pub mod manifest;
mod map;
mod obj;
pub mod stack;
@@ -69,7 +70,7 @@
pub use ctx::*;
pub use dynamic::*;
-pub use error::{Error::*, LocError, Result, ResultExt};
+pub use error::{Error, ErrorKind::*, Result, ResultExt};
pub use evaluate::*;
use function::CallLocation;
use gc::{GcHashMap, TraceBox};
@@ -82,7 +83,7 @@
pub use obj::*;
use stack::check_depth;
pub use tla::apply_tla;
-pub use val::{ManifestFormat, Thunk, Val};
+pub use val::{Thunk, Val};
/// Thunk without bound `super`/`this`
/// object inheritance may be overriden multiple times, and will be fixed only on field read
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -11,7 +11,7 @@
use rustc_hash::FxHashMap;
use crate::{
- error::{Error::*, LocError},
+ error::{Error, ErrorKind::*},
function::CallLocation,
gc::{GcHashMap, GcHashSet, TraceBox},
operator::evaluate_add_op,
@@ -115,7 +115,7 @@
Cached(Val),
NotFound,
Pending,
- Errored(LocError),
+ Errored(Error),
}
#[allow(clippy::module_name_repetitions)]
crates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stack.rs
+++ b/crates/jrsonnet-evaluator/src/stack.rs
@@ -1,6 +1,6 @@
use std::{cell::Cell, marker::PhantomData};
-use crate::error::{Error, LocError};
+use crate::error::{Error, ErrorKind};
struct StackLimit {
max_stack_size: Cell<usize>,
@@ -22,14 +22,14 @@
}
pub struct StackOverflowError;
-impl From<StackOverflowError> for Error {
+impl From<StackOverflowError> for ErrorKind {
fn from(_: StackOverflowError) -> Self {
- Error::StackOverflow
+ ErrorKind::StackOverflow
}
}
-impl From<StackOverflowError> for LocError {
+impl From<StackOverflowError> for Error {
fn from(_: StackOverflowError) -> Self {
- Error::StackOverflow.into()
+ ErrorKind::StackOverflow.into()
}
}
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -6,7 +6,7 @@
use jrsonnet_types::ValType;
use thiserror::Error;
-use crate::{error::Error::*, throw, typed::Typed, LocError, ObjValue, Result, Val};
+use crate::{error::ErrorKind::*, throw, typed::Typed, Error, ObjValue, Result, Val};
#[derive(Debug, Clone, Error, Trace)]
pub enum FormatError {
@@ -26,7 +26,7 @@
NoSuchFormatField(IStr),
}
-impl From<FormatError> for LocError {
+impl From<FormatError> for Error {
fn from(e: FormatError) -> Self {
Self::new(Format(e))
}
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -7,7 +7,6 @@
use crate::{error::Result, function::CallLocation, State, Val};
pub mod format;
-pub mod manifest;
pub fn std_format(str: IStr, vals: Val) -> Result<String> {
State::push(
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -6,7 +6,7 @@
use jrsonnet_gcmodule::Trace;
use jrsonnet_parser::{CodeLocation, Source};
-use crate::{error::Error, LocError};
+use crate::{error::ErrorKind, Error};
/// The way paths should be displayed
#[derive(Clone, Trace)]
@@ -51,9 +51,9 @@
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- error: &LocError,
+ error: &Error,
) -> Result<(), std::fmt::Error>;
- fn format(&self, error: &LocError) -> Result<String, std::fmt::Error> {
+ fn format(&self, error: &Error) -> Result<String, std::fmt::Error> {
let mut out = String::new();
self.write_trace(&mut out, error)?;
Ok(out)
@@ -107,10 +107,10 @@
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- error: &LocError,
+ error: &Error,
) -> Result<(), std::fmt::Error> {
write!(out, "{}", error.error())?;
- if let Error::ImportSyntaxError { path, error } = error.error() {
+ if let ErrorKind::ImportSyntaxError { path, error } = error.error() {
use std::fmt::Write;
writeln!(out)?;
@@ -204,7 +204,7 @@
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- error: &LocError,
+ error: &Error,
) -> Result<(), std::fmt::Error> {
write!(out, "{}", error.error())?;
for item in &error.trace().0 {
@@ -250,10 +250,10 @@
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- error: &LocError,
+ error: &Error,
) -> Result<(), std::fmt::Error> {
write!(out, "{}", error.error())?;
- if let Error::ImportSyntaxError { path, error } = error.error() {
+ if let ErrorKind::ImportSyntaxError { path, error } = error.error() {
writeln!(out)?;
let offset = error.location.offset;
let location = path
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -7,7 +7,7 @@
use thiserror::Error;
use crate::{
- error::{Error, LocError, Result},
+ error::{Error, ErrorKind, Result},
State, Val,
};
@@ -26,9 +26,9 @@
)]
BoundsFailed(f64, Option<f64>, Option<f64>),
}
-impl From<TypeError> for LocError {
+impl From<TypeError> for Error {
fn from(e: TypeError) -> Self {
- Error::TypeError(e.into()).into()
+ ErrorKind::TypeError(e.into()).into()
}
}
@@ -39,9 +39,9 @@
Self(Box::new(e), ValuePathStack(Vec::new()))
}
}
-impl From<TypeLocError> for LocError {
+impl From<TypeLocError> for Error {
fn from(e: TypeLocError) -> Self {
- Error::TypeError(e).into()
+ ErrorKind::TypeError(e).into()
}
}
impl Display for TypeLocError {
@@ -92,7 +92,7 @@
State::push_description(error_reason, || match item() {
Ok(_) => Ok(()),
Err(mut e) => {
- if let Error::TypeError(e) = &mut e.error_mut() {
+ if let ErrorKind::TypeError(e) = &mut e.error_mut() {
(e.1).0.push(path());
}
Err(e)
@@ -218,7 +218,7 @@
return Ok(());
}
Err(e) => match e.error() {
- Error::TypeError(e) => errors.push(e.clone()),
+ ErrorKind::TypeError(e) => errors.push(e.clone()),
_ => return Err(e),
},
}
@@ -233,7 +233,7 @@
return Ok(());
}
Err(e) => match e.error() {
- Error::TypeError(e) => errors.push(e.clone()),
+ ErrorKind::TypeError(e) => errors.push(e.clone()),
_ => return Err(e),
},
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -5,9 +5,10 @@
use jrsonnet_types::ValType;
use crate::{
- error::{Error::*, LocError},
+ error::{Error, ErrorKind::*},
function::FuncVal,
gc::{GcHashMap, TraceBox},
+ manifest::{ManifestFormat, ToStringFormat},
throw,
typed::BoundedUsize,
ObjValue, Result, Unbound, WeakObjValue,
@@ -21,7 +22,7 @@
#[derive(Trace)]
enum ThunkInner<T: Trace> {
Computed(T),
- Errored(LocError),
+ Errored(Error),
Waiting(TraceBox<dyn ThunkValue<Output = T>>),
Pending,
}
@@ -116,33 +117,6 @@
impl<T: Trace> PartialEq for Thunk<T> {
fn eq(&self, other: &Self) -> bool {
Cc::ptr_eq(&self.0, &other.0)
- }
-}
-
-pub trait ManifestFormat {
- fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
- fn manifest(&self, val: Val) -> Result<String> {
- let mut out = String::new();
- self.manifest_buf(val, &mut out)?;
- Ok(out)
- }
-}
-impl<T> ManifestFormat for Box<T>
-where
- T: ManifestFormat + ?Sized,
-{
- fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
- let inner = &**self;
- inner.manifest_buf(val, buf)
- }
-}
-impl<T> ManifestFormat for &'_ T
-where
- T: ManifestFormat + ?Sized,
-{
- fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
- let inner = &**self;
- inner.manifest_buf(val, buf)
}
}
@@ -649,9 +623,7 @@
Self::Bool(false) => "false".into(),
Self::Null => "null".into(),
Self::Str(s) => s.clone(),
- _ => self
- .manifest(crate::stdlib::manifest::ToStringFormat)
- .map(IStr::from)?,
+ _ => self.manifest(ToStringFormat).map(IStr::from)?,
})
}
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -540,7 +540,7 @@
}
} else {
quote! {
- <#ty>::from_untyped(obj.get(#name.into())?.ok_or_else(|| Error::NoSuchField(#name.into(), vec![]))?)?
+ <#ty>::from_untyped(obj.get(#name.into())?.ok_or_else(|| ErrorKind::NoSuchField(#name.into(), vec![]))?)?
}
};
@@ -638,19 +638,19 @@
use ::jrsonnet_evaluator::{
typed::{ComplexValType, Typed, TypedObj, CheckType},
Val, State,
- error::{LocError, Error, Result},
+ error::{ErrorKind, Result as JrResult},
ObjValueBuilder, ObjValue,
};
#typed
impl TypedObj for #ident {
- fn serialize(self, out: &mut ObjValueBuilder) -> Result<(), LocError> {
+ fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {
#(#fields_serialize)*
Ok(())
}
- fn parse(obj: &ObjValue) -> Result<Self, LocError> {
+ fn parse(obj: &ObjValue) -> JrResult<Self> {
Ok(Self {
#(#fields_parse)*
})
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -450,15 +450,23 @@
fn imports() {
assert_eq!(
parse!("import \"hello\""),
- el!(Expr::Import("hello".into()), 0, 14),
+ el!(Expr::Import(el!(Expr::Str("hello".into()), 7, 14)), 0, 14),
);
assert_eq!(
parse!("importstr \"garnish.txt\""),
- el!(Expr::ImportStr("garnish.txt".into()), 0, 23)
+ el!(
+ Expr::ImportStr(el!(Expr::Str("garnish.txt".into()), 10, 23)),
+ 0,
+ 23
+ )
);
assert_eq!(
parse!("importbin \"garnish.bin\""),
- el!(Expr::ImportBin("garnish.bin".into()), 0, 23)
+ el!(
+ Expr::ImportBin(el!(Expr::Str("garnish.bin".into()), 10, 23)),
+ 0,
+ 23
+ )
);
}
crates/jrsonnet-stdlib/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-stdlib/Cargo.toml
+++ b/crates/jrsonnet-stdlib/Cargo.toml
@@ -7,7 +7,7 @@
edition = "2021"
[features]
-default = ["codegenerated-stdlib"]
+default = ["codegenerated-stdlib", "exp-more-hashes"]
# Speed-up initialization by generating code for parsed stdlib, instead
# of invoking parser for it
codegenerated-stdlib = ["jrsonnet-parser/structdump"]
@@ -15,6 +15,7 @@
legacy-this-file = []
# Add order preservation flag to some functions
exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
+exp-more-hashes = ["sha2"]
[dependencies]
jrsonnet-evaluator.workspace = true
@@ -36,6 +37,8 @@
# std.parseYaml, custom library fork is used for C++/golang compatibility
serde_yaml_with_quirks = "0.8.24"
+sha2 = { version = "0.10.6", optional = true }
+
[build-dependencies]
jrsonnet-parser.workspace = true
structdump = { version = "0.2.0", features = ["derive"] }
crates/jrsonnet-stdlib/build.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/build.rs
+++ b/crates/jrsonnet-stdlib/build.rs
@@ -19,7 +19,7 @@
{
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("stdlib.rs");
- let mut f = File::create(&dest_path).unwrap();
+ let mut f = File::create(dest_path).unwrap();
f.write_all(
("#[allow(clippy::redundant_clone)]".to_owned() + &v.to_string())
.replace(';', ";\n")
crates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -1,5 +1,5 @@
use jrsonnet_evaluator::{
- error::{Error::RuntimeError, Result},
+ error::{ErrorKind::RuntimeError, Result},
function::builtin,
typed::{Either, Either2},
IBytes, IStr,
crates/jrsonnet-stdlib/src/hash.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/hash.rs
+++ b/crates/jrsonnet-stdlib/src/hash.rs
@@ -4,3 +4,10 @@
pub fn builtin_md5(str: IStr) -> Result<String> {
Ok(format!("{:x}", md5::compute(str.as_bytes())))
}
+
+#[cfg(feature = "exp-more-hashes")]
+#[builtin]
+pub fn builtin_sha256(str: IStr) -> Result<String> {
+ use sha2::digest::Digest;
+ Ok(format!("{:?}", sha2::Sha256::digest(str.as_bytes())))
+}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -5,7 +5,7 @@
};
use jrsonnet_evaluator::{
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
function::{builtin::Builtin, CallLocation, FuncVal, TlaArg},
gc::{GcHashMap, TraceBox},
tb,
@@ -101,6 +101,8 @@
("sort", builtin_sort::INST),
// Hash
("md5", builtin_md5::INST),
+ #[cfg(feature = "exp-more-hashes")]
+ ("sha256", builtin_sha256::INST),
// Encoding
("encodeUTF8", builtin_encode_utf8::INST),
("decodeUTF8", builtin_decode_utf8::INST),
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -1,7 +1,7 @@
use std::{cell::RefCell, rc::Rc};
use jrsonnet_evaluator::{
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
function::{builtin, ArgLike, CallLocation, FuncVal},
throw,
typed::{Any, Either2, Either4},
crates/jrsonnet-stdlib/src/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/parse.rs
+++ b/crates/jrsonnet-stdlib/src/parse.rs
@@ -1,5 +1,5 @@
use jrsonnet_evaluator::{
- error::{Error::RuntimeError, Result},
+ error::{ErrorKind::RuntimeError, Result},
function::builtin,
typed::Any,
IStr, Val,
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -1,5 +1,5 @@
use jrsonnet_evaluator::{
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
function::builtin,
typed::{Either2, VecVal, M1},
val::ArrValue,
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -29,7 +29,7 @@
macro_rules! ensure_val_eq {
($a:expr, $b:expr) => {{
if !::jrsonnet_evaluator::val::equals(&$a.clone(), &$b.clone())? {
- use ::jrsonnet_evaluator::stdlib::manifest::JsonFormat;
+ use ::jrsonnet_evaluator::manifest::JsonFormat;
::jrsonnet_evaluator::throw!(
"assertion failed: a != b\na={:#?}\nb={:#?}",
$a.manifest(JsonFormat::default())?,
tests/tests/golden.rsdiffbeforeafterboth--- a/tests/tests/golden.rs
+++ b/tests/tests/golden.rs
@@ -4,7 +4,7 @@
};
use jrsonnet_evaluator::{
- stdlib::manifest::JsonFormat,
+ manifest::JsonFormat,
trace::{CompactFormat, PathResolver, TraceFormat},
FileImportResolver, State,
};