difftreelog
style fix clippy warnings
in: master
20 files changed
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 trace::PathResolver, FileImportResolver, IStr, ManifestFormat, State, Val,21};2223/// WASM stub24#[cfg(target_arch = "wasm32")]25#[no_mangle]26pub extern "C" fn _start() {}2728/// Return the version string of the Jsonnet interpreter.29/// Conforms to [semantic versioning](http://semver.org/).30/// If this does not match `LIB_JSONNET_VERSION`31/// then there is a mismatch between header and compiled library.32#[no_mangle]33pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {34 b"v0.16.0\0"35}3637unsafe fn parse_path(input: &CStr) -> Cow<Path> {38 #[cfg(target_family = "unix")]39 {40 use std::os::unix::ffi::OsStrExt;41 let str = OsStr::from_bytes(input.to_bytes());42 Cow::Borrowed(Path::new(str))43 }44 #[cfg(target_family = "windows")]45 {46 use std::os::windows::ffi::OsStringExt;47 let str = input.to_str().expect("input is not utf8");48 let wide = str.encode_utf16().collect::<Vec<_>>();49 let wide = OsString::from_wide(&wide);50 Cow::Owned(PathBuf::new(wide))51 }52 #[cfg(not(any(target_family = "unix", target_family = "windows")))]53 {54 compile_error!("unsupported os")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(any(target_family = "unix", target_family = "windows")))]66 {67 compile_error!("unsupported os")68 }69}7071/// Creates a new Jsonnet virtual machine.72#[no_mangle]73pub extern "C" fn jsonnet_make() -> *mut State {74 let state = State::default();75 state.settings_mut().import_resolver = Box::new(FileImportResolver::default());76 state.settings_mut().context_initializer = Box::new(jrsonnet_stdlib::ContextInitializer::new(77 state.clone(),78 PathResolver::new_cwd_fallback(),79 ));80 Box::into_raw(Box::new(state))81}8283/// Complement of [`jsonnet_vm_make`].84#[no_mangle]85#[allow(clippy::boxed_local)]86pub extern "C" fn jsonnet_destroy(vm: Box<State>) {87 drop(vm);88}8990/// Set the maximum stack depth.91#[no_mangle]92pub extern "C" fn jsonnet_max_stack(vm: &State, v: c_uint) {93 vm.settings_mut().max_stack = v as usize;94}9596/// Set the number of objects required before a garbage collection cycle is allowed.97///98/// No-op for now99#[no_mangle]100pub extern "C" fn jsonnet_gc_min_objects(_vm: &State, _v: c_uint) {}101102/// Run the garbage collector after this amount of growth in the number of objects103///104/// No-op for now105#[no_mangle]106pub extern "C" fn jsonnet_gc_growth_trigger(_vm: &State, _v: c_double) {}107108/// Expect a string as output and don't JSON encode it.109#[no_mangle]110pub extern "C" fn jsonnet_string_output(vm: &State, v: c_int) {111 match v {112 1 => vm.set_manifest_format(ManifestFormat::String),113 0 => vm.set_manifest_format(ManifestFormat::Json {114 padding: 4,115 #[cfg(feature = "exp-preserve-order")]116 preserve_order: false,117 }),118 _ => panic!("incorrect output format"),119 }120}121122/// Allocate, resize, or free a buffer. This will abort if the memory cannot be allocated. It will123/// only return NULL if sz was zero.124///125/// # Safety126///127/// `buf` should be either previosly allocated by this library, or NULL128///129/// This function is most definitely broken, but it works somehow, see TODO inside130#[no_mangle]131pub unsafe extern "C" fn jsonnet_realloc(_vm: &State, buf: *mut u8, sz: usize) -> *mut u8 {132 if buf.is_null() {133 if sz == 0 {134 return std::ptr::null_mut();135 }136 return std::alloc::alloc(Layout::from_size_align(sz, std::mem::align_of::<u8>()).unwrap());137 }138 // TODO: Somehow store size of allocation, because its real size is probally not 16 :D139 // OR (Alternative way of fixing this TODO)140 // TODO: Standard allocator uses malloc, and it doesn't uses allocation size,141 // TODO: so it should work in normal cases. Maybe force allocator for this library?142 let old_layout = Layout::from_size_align(16, std::mem::align_of::<u8>()).unwrap();143 if sz == 0 {144 std::alloc::dealloc(buf, old_layout);145 return std::ptr::null_mut();146 }147 std::alloc::realloc(buf, old_layout, sz)148}149150/// Clean up a JSON subtree.151///152/// This is useful if you want to abort with an error mid-way through building a complex value.153#[no_mangle]154#[allow(clippy::boxed_local)]155pub extern "C" fn jsonnet_json_destroy(_vm: &State, v: Box<Val>) {156 drop(v);157}158159/// Set the number of lines of stack trace to display (0 for all of them).160#[no_mangle]161pub extern "C" fn jsonnet_max_trace(vm: &State, v: c_uint) {162 vm.set_max_trace(v as usize)163}164165/// Evaluate a file containing Jsonnet code, return a JSON string.166///167/// The returned string should be cleaned up with jsonnet_realloc.168///169/// # Safety170///171/// `filename` should be a \0-terminated string172#[no_mangle]173pub unsafe extern "C" fn jsonnet_evaluate_file(174 vm: &State,175 filename: *const c_char,176 error: &mut c_int,177) -> *const c_char {178 let filename = parse_path(CStr::from_ptr(filename));179 match vm180 .import(&filename)181 .and_then(|v| vm.with_tla(v))182 .and_then(|v| vm.manifest(v))183 {184 Ok(v) => {185 *error = 0;186 CString::new(&*v as &str).unwrap().into_raw()187 }188 Err(e) => {189 *error = 1;190 let out = vm.stringify_err(&e);191 CString::new(&out as &str).unwrap().into_raw()192 }193 }194}195196/// Evaluate a string containing Jsonnet code, return a JSON string.197///198/// The returned string should be cleaned up with jsonnet_realloc.199///200/// # Safety201///202/// `filename`, `snippet` should be a \0-terminated strings203#[no_mangle]204pub unsafe extern "C" fn jsonnet_evaluate_snippet(205 vm: &State,206 filename: *const c_char,207 snippet: *const c_char,208 error: &mut c_int,209) -> *const c_char {210 let filename = CStr::from_ptr(filename);211 let snippet = CStr::from_ptr(snippet);212 match vm213 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())214 .and_then(|v| vm.with_tla(v))215 .and_then(|v| vm.manifest(v))216 {217 Ok(v) => {218 *error = 0;219 CString::new(&*v as &str).unwrap().into_raw()220 }221 Err(e) => {222 *error = 1;223 let out = vm.stringify_err(&e);224 CString::new(&out as &str).unwrap().into_raw()225 }226 }227}228229fn multi_to_raw(multi: Vec<(IStr, IStr)>) -> *const c_char {230 let mut out = Vec::new();231 for (i, (k, v)) in multi.iter().enumerate() {232 if i != 0 {233 out.push(0);234 }235 out.extend_from_slice(k.as_bytes());236 out.push(0);237 out.extend_from_slice(v.as_bytes());238 }239 out.push(0);240 out.push(0);241 let v = out.as_ptr();242 std::mem::forget(out);243 v as *const c_char244}245246/// # Safety247#[no_mangle]248pub unsafe extern "C" fn jsonnet_evaluate_file_multi(249 vm: &State,250 filename: *const c_char,251 error: &mut c_int,252) -> *const c_char {253 let filename = parse_path(CStr::from_ptr(filename));254 match vm255 .import(&filename)256 .and_then(|v| vm.with_tla(v))257 .and_then(|v| vm.manifest_multi(v))258 {259 Ok(v) => {260 *error = 0;261 multi_to_raw(v)262 }263 Err(e) => {264 *error = 1;265 let out = vm.stringify_err(&e);266 CString::new(&out as &str).unwrap().into_raw()267 }268 }269}270271/// # Safety272#[no_mangle]273pub unsafe extern "C" fn jsonnet_evaluate_snippet_multi(274 vm: &State,275 filename: *const c_char,276 snippet: *const c_char,277 error: &mut c_int,278) -> *const c_char {279 let filename = CStr::from_ptr(filename);280 let snippet = CStr::from_ptr(snippet);281 match vm282 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())283 .and_then(|v| vm.with_tla(v))284 .and_then(|v| vm.manifest_multi(v))285 {286 Ok(v) => {287 *error = 0;288 multi_to_raw(v)289 }290 Err(e) => {291 *error = 1;292 let out = vm.stringify_err(&e);293 CString::new(&out as &str).unwrap().into_raw()294 }295 }296}297298fn stream_to_raw(multi: Vec<IStr>) -> *const c_char {299 let mut out = Vec::new();300 for (i, v) in multi.iter().enumerate() {301 if i != 0 {302 out.push(0);303 }304 out.extend_from_slice(v.as_bytes());305 }306 out.push(0);307 out.push(0);308 let v = out.as_ptr();309 std::mem::forget(out);310 v as *const c_char311}312313/// # Safety314#[no_mangle]315pub unsafe extern "C" fn jsonnet_evaluate_file_stream(316 vm: &State,317 filename: *const c_char,318 error: &mut c_int,319) -> *const c_char {320 let filename = parse_path(CStr::from_ptr(filename));321 match vm322 .import(&filename)323 .and_then(|v| vm.with_tla(v))324 .and_then(|v| vm.manifest_stream(v))325 {326 Ok(v) => {327 *error = 0;328 stream_to_raw(v)329 }330 Err(e) => {331 *error = 1;332 let out = vm.stringify_err(&e);333 CString::new(&out as &str)334 .expect("there should be no \\0 in the error string")335 .into_raw()336 }337 }338}339340/// # Safety341#[no_mangle]342pub unsafe extern "C" fn jsonnet_evaluate_snippet_stream(343 vm: &State,344 filename: *const c_char,345 snippet: *const c_char,346 error: &mut c_int,347) -> *const c_char {348 let filename = CStr::from_ptr(filename);349 let snippet = CStr::from_ptr(snippet);350 match vm351 .evaluate_snippet(352 filename.to_str().expect("filename is not utf-8"),353 snippet.to_str().expect("snippet is not utf-8"),354 )355 .and_then(|v| vm.with_tla(v))356 .and_then(|v| vm.manifest_stream(v))357 {358 Ok(v) => {359 *error = 0;360 stream_to_raw(v)361 }362 Err(e) => {363 *error = 1;364 let out = vm.stringify_err(&e);365 CString::new(&out as &str)366 .expect("there should be no \\0 in the error string")367 .into_raw()368 }369 }370}1#[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 trace::PathResolver, FileImportResolver, IStr, ManifestFormat, State, Val,21};2223/// WASM stub24#[cfg(target_arch = "wasm32")]25#[no_mangle]26pub extern "C" fn _start() {}2728/// Return the version string of the Jsonnet interpreter.29/// Conforms to [semantic versioning](http://semver.org/).30/// If this does not match `LIB_JSONNET_VERSION`31/// then there is a mismatch between header and compiled library.32#[no_mangle]33pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {34 b"v0.16.0\0"35}3637unsafe fn parse_path(input: &CStr) -> Cow<Path> {38 #[cfg(target_family = "unix")]39 {40 use std::os::unix::ffi::OsStrExt;41 let str = OsStr::from_bytes(input.to_bytes());42 Cow::Borrowed(Path::new(str))43 }44 #[cfg(target_family = "windows")]45 {46 use std::os::windows::ffi::OsStringExt;47 let str = input.to_str().expect("input is not utf8");48 let wide = str.encode_utf16().collect::<Vec<_>>();49 let wide = OsString::from_wide(&wide);50 Cow::Owned(PathBuf::new(wide))51 }52 #[cfg(not(any(target_family = "unix", target_family = "windows")))]53 {54 compile_error!("unsupported os")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(any(target_family = "unix", target_family = "windows")))]66 {67 compile_error!("unsupported os")68 }69}7071/// Creates a new Jsonnet virtual machine.72#[no_mangle]73#[allow(clippy::box_default)]74pub extern "C" fn jsonnet_make() -> *mut State {75 let state = State::default();76 state.settings_mut().import_resolver = Box::new(FileImportResolver::default());77 state.settings_mut().context_initializer = Box::new(jrsonnet_stdlib::ContextInitializer::new(78 state.clone(),79 PathResolver::new_cwd_fallback(),80 ));81 Box::into_raw(Box::new(state))82}8384/// Complement of [`jsonnet_vm_make`].85#[no_mangle]86#[allow(clippy::boxed_local)]87pub extern "C" fn jsonnet_destroy(vm: Box<State>) {88 drop(vm);89}9091/// Set the maximum stack depth.92#[no_mangle]93pub extern "C" fn jsonnet_max_stack(vm: &State, v: c_uint) {94 vm.settings_mut().max_stack = v as usize;95}9697/// Set the number of objects required before a garbage collection cycle is allowed.98///99/// No-op for now100#[no_mangle]101pub extern "C" fn jsonnet_gc_min_objects(_vm: &State, _v: c_uint) {}102103/// Run the garbage collector after this amount of growth in the number of objects104///105/// No-op for now106#[no_mangle]107pub extern "C" fn jsonnet_gc_growth_trigger(_vm: &State, _v: c_double) {}108109/// Expect a string as output and don't JSON encode it.110#[no_mangle]111pub extern "C" fn jsonnet_string_output(vm: &State, v: c_int) {112 match v {113 1 => vm.set_manifest_format(ManifestFormat::String),114 0 => vm.set_manifest_format(ManifestFormat::Json {115 padding: 4,116 #[cfg(feature = "exp-preserve-order")]117 preserve_order: false,118 }),119 _ => panic!("incorrect output format"),120 }121}122123/// Allocate, resize, or free a buffer. This will abort if the memory cannot be allocated. It will124/// only return NULL if sz was zero.125///126/// # Safety127///128/// `buf` should be either previosly allocated by this library, or NULL129///130/// This function is most definitely broken, but it works somehow, see TODO inside131#[no_mangle]132pub unsafe extern "C" fn jsonnet_realloc(_vm: &State, buf: *mut u8, sz: usize) -> *mut u8 {133 if buf.is_null() {134 if sz == 0 {135 return std::ptr::null_mut();136 }137 return std::alloc::alloc(Layout::from_size_align(sz, std::mem::align_of::<u8>()).unwrap());138 }139 // TODO: Somehow store size of allocation, because its real size is probally not 16 :D140 // OR (Alternative way of fixing this TODO)141 // TODO: Standard allocator uses malloc, and it doesn't uses allocation size,142 // TODO: so it should work in normal cases. Maybe force allocator for this library?143 let old_layout = Layout::from_size_align(16, std::mem::align_of::<u8>()).unwrap();144 if sz == 0 {145 std::alloc::dealloc(buf, old_layout);146 return std::ptr::null_mut();147 }148 std::alloc::realloc(buf, old_layout, sz)149}150151/// Clean up a JSON subtree.152///153/// This is useful if you want to abort with an error mid-way through building a complex value.154#[no_mangle]155#[allow(clippy::boxed_local)]156pub extern "C" fn jsonnet_json_destroy(_vm: &State, v: Box<Val>) {157 drop(v);158}159160/// Set the number of lines of stack trace to display (0 for all of them).161#[no_mangle]162pub extern "C" fn jsonnet_max_trace(vm: &State, v: c_uint) {163 vm.set_max_trace(v as usize)164}165166/// Evaluate a file containing Jsonnet code, return a JSON string.167///168/// The returned string should be cleaned up with jsonnet_realloc.169///170/// # Safety171///172/// `filename` should be a \0-terminated string173#[no_mangle]174pub unsafe extern "C" fn jsonnet_evaluate_file(175 vm: &State,176 filename: *const c_char,177 error: &mut c_int,178) -> *const c_char {179 let filename = parse_path(CStr::from_ptr(filename));180 match vm181 .import(&filename)182 .and_then(|v| vm.with_tla(v))183 .and_then(|v| vm.manifest(v))184 {185 Ok(v) => {186 *error = 0;187 CString::new(&*v as &str).unwrap().into_raw()188 }189 Err(e) => {190 *error = 1;191 let out = vm.stringify_err(&e);192 CString::new(&out as &str).unwrap().into_raw()193 }194 }195}196197/// Evaluate a string containing Jsonnet code, return a JSON string.198///199/// The returned string should be cleaned up with jsonnet_realloc.200///201/// # Safety202///203/// `filename`, `snippet` should be a \0-terminated strings204#[no_mangle]205pub unsafe extern "C" fn jsonnet_evaluate_snippet(206 vm: &State,207 filename: *const c_char,208 snippet: *const c_char,209 error: &mut c_int,210) -> *const c_char {211 let filename = CStr::from_ptr(filename);212 let snippet = CStr::from_ptr(snippet);213 match vm214 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())215 .and_then(|v| vm.with_tla(v))216 .and_then(|v| vm.manifest(v))217 {218 Ok(v) => {219 *error = 0;220 CString::new(&*v as &str).unwrap().into_raw()221 }222 Err(e) => {223 *error = 1;224 let out = vm.stringify_err(&e);225 CString::new(&out as &str).unwrap().into_raw()226 }227 }228}229230fn multi_to_raw(multi: Vec<(IStr, IStr)>) -> *const c_char {231 let mut out = Vec::new();232 for (i, (k, v)) in multi.iter().enumerate() {233 if i != 0 {234 out.push(0);235 }236 out.extend_from_slice(k.as_bytes());237 out.push(0);238 out.extend_from_slice(v.as_bytes());239 }240 out.push(0);241 out.push(0);242 let v = out.as_ptr();243 std::mem::forget(out);244 v as *const c_char245}246247/// # Safety248#[no_mangle]249pub unsafe extern "C" fn jsonnet_evaluate_file_multi(250 vm: &State,251 filename: *const c_char,252 error: &mut c_int,253) -> *const c_char {254 let filename = parse_path(CStr::from_ptr(filename));255 match vm256 .import(&filename)257 .and_then(|v| vm.with_tla(v))258 .and_then(|v| vm.manifest_multi(v))259 {260 Ok(v) => {261 *error = 0;262 multi_to_raw(v)263 }264 Err(e) => {265 *error = 1;266 let out = vm.stringify_err(&e);267 CString::new(&out as &str).unwrap().into_raw()268 }269 }270}271272/// # Safety273#[no_mangle]274pub unsafe extern "C" fn jsonnet_evaluate_snippet_multi(275 vm: &State,276 filename: *const c_char,277 snippet: *const c_char,278 error: &mut c_int,279) -> *const c_char {280 let filename = CStr::from_ptr(filename);281 let snippet = CStr::from_ptr(snippet);282 match vm283 .evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())284 .and_then(|v| vm.with_tla(v))285 .and_then(|v| vm.manifest_multi(v))286 {287 Ok(v) => {288 *error = 0;289 multi_to_raw(v)290 }291 Err(e) => {292 *error = 1;293 let out = vm.stringify_err(&e);294 CString::new(&out as &str).unwrap().into_raw()295 }296 }297}298299fn stream_to_raw(multi: Vec<IStr>) -> *const c_char {300 let mut out = Vec::new();301 for (i, v) in multi.iter().enumerate() {302 if i != 0 {303 out.push(0);304 }305 out.extend_from_slice(v.as_bytes());306 }307 out.push(0);308 out.push(0);309 let v = out.as_ptr();310 std::mem::forget(out);311 v as *const c_char312}313314/// # Safety315#[no_mangle]316pub unsafe extern "C" fn jsonnet_evaluate_file_stream(317 vm: &State,318 filename: *const c_char,319 error: &mut c_int,320) -> *const c_char {321 let filename = parse_path(CStr::from_ptr(filename));322 match vm323 .import(&filename)324 .and_then(|v| vm.with_tla(v))325 .and_then(|v| vm.manifest_stream(v))326 {327 Ok(v) => {328 *error = 0;329 stream_to_raw(v)330 }331 Err(e) => {332 *error = 1;333 let out = vm.stringify_err(&e);334 CString::new(&out as &str)335 .expect("there should be no \\0 in the error string")336 .into_raw()337 }338 }339}340341/// # Safety342#[no_mangle]343pub unsafe extern "C" fn jsonnet_evaluate_snippet_stream(344 vm: &State,345 filename: *const c_char,346 snippet: *const c_char,347 error: &mut c_int,348) -> *const c_char {349 let filename = CStr::from_ptr(filename);350 let snippet = CStr::from_ptr(snippet);351 match vm352 .evaluate_snippet(353 filename.to_str().expect("filename is not utf-8"),354 snippet.to_str().expect("snippet is not utf-8"),355 )356 .and_then(|v| vm.with_tla(v))357 .and_then(|v| vm.manifest_stream(v))358 {359 Ok(v) => {360 *error = 0;361 stream_to_raw(v)362 }363 Err(e) => {364 *error = 1;365 let out = vm.stringify_err(&e);366 CString::new(&out as &str)367 .expect("there should be no \\0 in the error string")368 .into_raw()369 }370 }371}crates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -44,7 +44,7 @@
if out.len() != 2 {
return Err("bad ext-file syntax".to_owned());
}
- let file = read_to_string(&out[1]);
+ let file = read_to_string(out[1]);
match file {
Ok(content) => Ok(Self {
name: out[0].into(),
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -100,7 +100,7 @@
#[error("duplicate local var: {0}")]
DuplicateLocalVar(IStr),
- #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]
+ #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]
TypeMismatch(&'static str, Vec<ValType>, ValType),
#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]
NoSuchField(IStr, Vec<IStr>),
@@ -113,7 +113,7 @@
BindingParameterASecondTime(IStr),
#[error("too many args, function has {0}{}", format_signature(.1))]
TooManyArgsFunctionHas(usize, FunctionSignature),
- #[error("function argument is not passed: {}{}", .0.as_ref().map(|n| n.as_str()).unwrap_or("<unnamed>"), format_signature(.1))]
+ #[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]
FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),
#[error("external variable is not defined: {0}")]
@@ -249,7 +249,7 @@
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.0 .0)?;
for el in &self.0 .1 .0 {
- writeln!(f, "\t{:?}", el)?;
+ writeln!(f, "\t{el:?}")?;
}
Ok(())
}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -436,7 +436,7 @@
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,
Var(name) => s.push(
CallLocation::new(loc),
- || format!("variable <{}> access", name),
+ || format!("variable <{name}> access"),
|| ctx.binding(name.clone())?.evaluate(s.clone()),
)?,
Index(value, index) => {
@@ -446,7 +446,7 @@
) {
(Val::Obj(v), Val::Str(key)) => s.push(
CallLocation::new(loc),
- || format!("field <{}> access", key),
+ || format!("field <{key}> access"),
|| match v.get(s.clone(), key.clone()) {
Ok(Some(v)) => Ok(v),
#[cfg(not(feature = "friendly-errors"))]
@@ -611,7 +611,7 @@
if let Some(value) = expr {
Ok(Some(s.push(
loc,
- || format!("slice {}", desc),
+ || format!("slice {desc}"),
|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),
)?))
} else {
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -30,8 +30,8 @@
(Str(a), Num(b)) => Str(format!("{a}{b}").into()),
(Str(a), o) | (o, Str(a)) if a.is_empty() => Val::Str(o.clone().to_string(s)?),
- (Str(a), o) => Str(format!("{}{}", a, o.clone().to_string(s)?).into()),
- (o, Str(a)) => Str(format!("{}{}", o.clone().to_string(s)?, a).into()),
+ (Str(a), o) => Str(format!("{a}{}", o.clone().to_string(s)?).into()),
+ (o, Str(a)) => Str(format!("{}{a}", o.clone().to_string(s)?).into()),
(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
(Arr(a), Arr(b)) => {
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -108,7 +108,7 @@
handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
) -> Result<()> {
for (idx, el) in self.iter().enumerate() {
- handler(idx, Thunk::evaluated(el.clone()))?
+ handler(idx, Thunk::evaluated(el.clone()))?;
}
Ok(())
}
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -179,12 +179,7 @@
// FIXME: O(n) for arg existence check
let id = params
.iter()
- .position(|p| {
- p.name
- .as_ref()
- .map(|v| &v as &str == name as &str)
- .unwrap_or(false)
- })
+ .position(|p| p.name.as_ref().map_or(false, |v| v as &str == name as &str))
.ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;
if replace(&mut passed_args[id], Some(arg)).is_some() {
throw!(BindingParameterASecondTime(name.clone()));
@@ -209,8 +204,7 @@
if param
.name
.as_ref()
- .map(|v| &v as &str == name as &str)
- .unwrap_or(false)
+ .map_or(false, |v| v as &str == name as &str)
{
found = true;
}
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -123,15 +123,11 @@
};
if meta.is_file() {
Ok(SourcePath::new(SourceFile::new(
- path.canonicalize()
- .map_err(|e| ImportIo(e.to_string()))?
- .to_owned(),
+ path.canonicalize().map_err(|e| ImportIo(e.to_string()))?,
)))
} else if meta.is_dir() {
Ok(SourcePath::new(SourceDirectory::new(
- path.canonicalize()
- .map_err(|e| ImportIo(e.to_string()))?
- .to_owned(),
+ path.canonicalize().map_err(|e| ImportIo(e.to_string()))?,
)))
} else {
unreachable!("this can't be a symlink")
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -16,7 +16,7 @@
Self::Null => Val::Null,
Self::Bool(v) => Val::Bool(v),
Self::Number(n) => Val::Num(n.as_f64().ok_or_else(|| {
- RuntimeError(format!("json number can't be represented as jsonnet: {}", n).into())
+ RuntimeError(format!("json number can't be represented as jsonnet: {n}").into())
})?),
Self::String(s) => Val::Str((&s as &str).into()),
Self::Array(a) => {
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -594,7 +594,7 @@
.insert(name, TlaArg::String(value));
}
pub fn add_tla_code(&self, name: IStr, code: &str) -> Result<()> {
- let source_name = format!("<top-level-arg:{}>", name);
+ let source_name = format!("<top-level-arg:{name}>");
let source = Source::new_virtual(source_name.into(), code.into());
let parsed = jrsonnet_parser::parse(
code,
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -156,9 +156,9 @@
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(super_obj) = self.0.sup.as_ref() {
if f.alternate() {
- write!(f, "{:#?}", super_obj)?;
+ write!(f, "{super_obj:#?}")?;
} else {
- write!(f, "{:?}", super_obj)?;
+ write!(f, "{super_obj:?}")?;
}
write!(f, " + ")?;
}
@@ -395,10 +395,9 @@
})?;
self.0.value_cache.borrow_mut().insert(
key,
- match &value {
- Some(v) => CacheValue::Cached(v.clone()),
- None => CacheValue::NotFound,
- },
+ value
+ .as_ref()
+ .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),
);
Ok(value)
}
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -45,7 +45,7 @@
let mut i = 1;
while i < bytes.len() {
if bytes[i] == b')' {
- return Ok((&str[1..i as usize], &str[i as usize + 1..]));
+ return Ok((&str[1..i], &str[i + 1..]));
}
i += 1;
}
@@ -310,6 +310,7 @@
nums
};
let neg = iv < 0.0;
+ #[allow(clippy::bool_to_int_with_if)]
let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });
let zp2 = zp
.max(precision)
@@ -406,6 +407,7 @@
ensure_pt: bool,
trailing: bool,
) {
+ #[allow(clippy::bool_to_int_with_if)]
let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };
padding = padding.saturating_sub(dot_size + precision);
render_decimal(out, n.floor(), padding, 0, blank, sign);
@@ -478,10 +480,7 @@
precision: Option<usize>,
) -> Result<()> {
let clfags = &code.cflags;
- let (fpprec, iprec) = match precision {
- Some(v) => (v, v),
- None => (6, 0),
- };
+ let (fpprec, iprec) = precision.map_or((6, 0), |v| (v, v));
let padding = if clfags.zero && !clfags.left {
width
} else {
@@ -586,8 +585,10 @@
}
}
ConvTypeV::Char => match value.clone() {
- Val::Num(n) => tmp_out
- .push(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?),
+ Val::Num(n) => tmp_out.push(
+ std::char::from_u32(n as u32)
+ .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
+ ),
Val::Str(s) => {
if s.chars().count() != 1 {
throw!(RuntimeError(
crates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -49,7 +49,7 @@
}
Val::Null => buf.push_str("null"),
Val::Str(s) => escape_string_json_buf(s, buf),
- Val::Num(n) => write!(buf, "{}", n).unwrap(),
+ Val::Num(n) => write!(buf, "{n}").unwrap(),
Val::Arr(items) => {
buf.push('[');
if !items.is_empty() {
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -12,7 +12,7 @@
pub fn std_format(s: State, str: IStr, vals: Val) -> Result<String> {
s.push(
CallLocation::native(),
- || format!("std.format of {}", str),
+ || format!("std.format of {str}"),
|| {
Ok(match vals {
Val::Arr(vals) => format_arr(s.clone(), &str, &vals.evaluated(s.clone())?)?,
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -16,12 +16,9 @@
}
impl PathResolver {
- /// Will return Self::Relative(cwd), or Self::Absolute on cwd failure
+ /// Will return `Self::Relative(cwd)`, or `Self::Absolute` on cwd failure
pub fn new_cwd_fallback() -> Self {
- match std::env::current_dir() {
- Ok(v) => Self::Relative(v),
- Err(_) => Self::Absolute,
- }
+ std::env::current_dir().map_or(Self::Absolute, Self::Relative)
}
pub fn resolve(&self, from: &Path) -> String {
match self {
@@ -97,10 +94,10 @@
use std::fmt::Write;
writeln!(out)?;
- let mut n = match path.source_path().path() {
- Some(r) => self.resolver.resolve(r),
- None => path.source_path().to_string(),
- };
+ let mut n = path.source_path().path().map_or_else(
+ || path.source_path().to_string(),
+ |r| self.resolver.resolve(r),
+ );
let mut offset = error.location.offset;
let is_eof = if offset >= path.code().len() {
offset = path.code().len().saturating_sub(1);
@@ -119,7 +116,7 @@
write!(n, ":").unwrap();
print_code_location(&mut n, &location, &location).unwrap();
- write!(out, "{:<p$}{}", "", n, p = self.padding,)?;
+ write!(out, "{:<p$}{n}", "", p = self.padding)?;
}
let file_names = error
.trace()
@@ -185,10 +182,10 @@
let desc = &item.desc;
if let Some(source) = &item.location {
let start_end = source.0.map_source_locations(&[source.1, source.2]);
- let resolved_path = match source.0.source_path().path() {
- Some(r) => r.display().to_string(),
- None => source.0.source_path().to_string(),
- };
+ let resolved_path = source.0.source_path().path().map_or_else(
+ || source.0.source_path().to_string(),
+ |r| r.display().to_string(),
+ );
write!(
out,
@@ -196,7 +193,7 @@
desc, resolved_path, start_end[0].line, start_end[0].column,
)?;
} else {
- write!(out, " during {}", desc)?;
+ write!(out, " during {desc}")?;
}
}
Ok(())
@@ -252,7 +249,7 @@
desc,
)?;
} else {
- write!(out, "{}", desc)?;
+ write!(out, "{desc}")?;
}
}
Ok(())
@@ -280,10 +277,10 @@
.take(end.line_end_offset - end.line_start_offset)
.collect();
- let origin = match origin.source_path().path() {
- Some(r) => self.resolver.resolve(r),
- None => origin.source_path().to_string(),
- };
+ let origin = origin.source_path().path().map_or_else(
+ || origin.source_path().to_string(),
+ |r| self.resolver.resolve(r),
+ );
let snippet = Snippet {
opt: FormatOptions {
color: true,
@@ -308,7 +305,7 @@
};
let dl = DisplayList::from(snippet);
- write!(out, "{}", dl)?;
+ write!(out, "{dl}")?;
Ok(())
}
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -21,8 +21,8 @@
UnionFailed(ComplexValType, TypeLocErrorList),
#[error(
"number out of bounds: {0} not in {}..{}",
- .1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
- .2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
+ .1.map(|v|v.to_string()).unwrap_or_default(),
+ .2.map(|v|v.to_string()).unwrap_or_default(),
)]
BoundsFailed(f64, Option<f64>, Option<f64>),
}
@@ -65,7 +65,7 @@
writeln!(f)?;
}
out.clear();
- write!(out, "{}", err)?;
+ write!(out, "{err}")?;
for (i, line) in out.lines().enumerate() {
if line.trim().is_empty() {
@@ -77,7 +77,7 @@
writeln!(f)?;
write!(f, " ")?;
}
- write!(f, "{}", line)?;
+ write!(f, "{line}")?;
}
}
Ok(())
@@ -125,8 +125,8 @@
impl Display for ValuePathItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
- Self::Field(name) => write!(f, ".{:?}", name)?,
- Self::Index(idx) => write!(f, "[{}]", idx)?,
+ Self::Field(name) => write!(f, ".{name:?}")?,
+ Self::Index(idx) => write!(f, "[{idx}]")?,
}
Ok(())
}
@@ -138,7 +138,7 @@
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "self")?;
for elem in self.0.iter().rev() {
- write!(f, "{}", elem)?;
+ write!(f, "{elem}")?;
}
Ok(())
}
@@ -171,7 +171,7 @@
for (i, item) in a.iter(s.clone()).enumerate() {
push_type_description(
s.clone(),
- || format!("array index {}", i),
+ || format!("array index {i}"),
|| ValuePathItem::Index(i as u64),
|| elem_type.check(s.clone(), &item.clone()?),
)?;
@@ -185,7 +185,7 @@
for (i, item) in a.iter(s.clone()).enumerate() {
push_type_description(
s.clone(),
- || format!("array index {}", i),
+ || format!("array index {i}"),
|| ValuePathItem::Index(i as u64),
|| elem_type.check(s.clone(), &item.clone()?),
)?;
@@ -200,7 +200,7 @@
if let Some(got_v) = obj.get(s.clone(), (*k).into())? {
push_type_description(
s.clone(),
- || format!("property {}", k),
+ || format!("property {k}"),
|| ValuePathItem::Field((*k).into()),
|| v.check(s.clone(), &got_v),
)?;
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -292,7 +292,7 @@
if index >= v.to() {
return Ok(None);
}
- v.inner.get(s, index as usize)
+ v.inner.get(s, index)
}
}
}
@@ -332,7 +332,7 @@
if index >= s.to() {
return None;
}
- s.inner.get_lazy(index as usize)
+ s.inner.get_lazy(index)
}
}
}
@@ -531,8 +531,9 @@
}
}
-#[cfg(target_pointer_width = "64")]
-static_assertions::assert_eq_size!(Val, [u8; 32]);
+// Broken between stable and nightly, as there is new layout size optimization
+// #[cfg(target_pointer_width = "64")]
+// static_assertions::assert_eq_size!(Val, [u8; 24]);
impl Val {
pub const fn as_bool(&self) -> Option<bool> {
crates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -28,7 +28,7 @@
#[builtin]
pub fn builtin_base64_decode_bytes(input: IStr) -> Result<IBytes> {
- Ok(base64::decode(&input.as_bytes())
+ Ok(base64::decode(input.as_bytes())
.map_err(|_| RuntimeError("bad base64".into()))?
.as_slice()
.into())
@@ -36,6 +36,6 @@
#[builtin]
pub fn builtin_base64_decode(input: IStr) -> Result<String> {
- let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
+ let bytes = base64::decode(input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)
}
crates/jrsonnet-stdlib/src/hash.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/hash.rs
+++ b/crates/jrsonnet-stdlib/src/hash.rs
@@ -2,5 +2,5 @@
#[builtin]
pub fn builtin_md5(str: IStr) -> Result<String> {
- Ok(format!("{:x}", md5::compute(&str.as_bytes())))
+ Ok(format!("{:x}", md5::compute(str.as_bytes())))
}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -366,7 +366,7 @@
#[builtin]
fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {
- Ok(str.chars().skip(from as usize).take(len as usize).collect())
+ Ok(str.chars().skip(from).take(len).collect())
}
#[builtin(fields(
@@ -380,7 +380,7 @@
.ext_vars
.get(&x)
.cloned()
- .ok_or(UndefinedExternalVariable(x))?
+ .ok_or_else(|| UndefinedExternalVariable(x))?
.evaluate_arg(s.clone(), ctx, true)?
.evaluate(s)?))
}
@@ -402,7 +402,7 @@
#[builtin]
fn builtin_char(n: u32) -> Result<char> {
- Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)
+ Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)
}
#[builtin(fields(