From a05afd32cebcebdc7b236c243df29f9470acf2b4 Mon Sep 17 00:00:00 2001 From: Yaroslav Bolyukin Date: Fri, 20 Jan 2023 00:09:16 +0000 Subject: [PATCH] style: fix clippy warnings --- --- a/cmds/jrsonnet/src/main.rs +++ b/cmds/jrsonnet/src/main.rs @@ -5,7 +5,7 @@ use clap::{CommandFactory, Parser}; use clap_complete::Shell; -use jrsonnet_cli::{ManifestOpts, OutputOpts, TraceOpts, MiscOpts, TlaOpts, StdOpts, GcOpts}; +use jrsonnet_cli::{GcOpts, ManifestOpts, MiscOpts, OutputOpts, StdOpts, TlaOpts, TraceOpts}; use jrsonnet_evaluator::{ apply_tla, error::{Error as JrError, ErrorKind}, @@ -133,16 +133,14 @@ fn main_catch(opts: Opts) -> bool { let s = State::default(); - let trace = opts - .trace - .trace_format(); + let trace = opts.trace.trace_format(); if let Err(e) = main_real(&s, opts) { if let Error::Evaluation(e) = e { let mut out = String::new(); trace.write_trace(&mut out, &e).expect("format error"); eprintln!("{out}") } else { - eprintln!("{}", e); + eprintln!("{e}"); } return false; } @@ -150,7 +148,7 @@ } fn main_real(s: &State, opts: Opts) -> Result<(), Error> { - let _gc_leak_guard= opts.gc.leak_on_exit(); + let _gc_leak_guard = opts.gc.leak_on_exit(); let _gc_print_stats = opts.gc.stats_printer(); let _stack_depth_override = opts.misc.stack_size_override(); @@ -220,7 +218,7 @@ } else { let output = val.manifest(manifest_format)?; if !output.is_empty() { - println!("{}", output); + println!("{output}"); } } --- a/crates/jrsonnet-cli/src/lib.rs +++ b/crates/jrsonnet-cli/src/lib.rs @@ -6,7 +6,10 @@ use std::{env, marker::PhantomData, path::PathBuf}; use clap::Parser; -use jrsonnet_evaluator::{error::Result, stack::{set_stack_depth_limit, StackDepthLimitOverrideGuard, limit_stack_depth}, FileImportResolver, State, ImportResolver}; +use jrsonnet_evaluator::{ + stack::{limit_stack_depth, StackDepthLimitOverrideGuard}, + FileImportResolver, +}; use jrsonnet_gcmodule::with_thread_object_space; pub use manifest::*; pub use stdlib::*; @@ -71,6 +74,7 @@ } impl GcOpts { pub fn stats_printer(&self) -> Option { + #[allow(clippy::unnecessary_lazy_evaluations/*, reason = "GcStatsPrinter has side-effect on Drop"*/)] self.gc_print_stats.then(|| GcStatsPrinter { collect_before_printing_stats: self.gc_collect_before_printing_stats, }) @@ -96,7 +100,7 @@ eprintln!("=== GC STATS ==="); if self.collect_before_printing_stats { let collected = jrsonnet_gcmodule::collect_thread_cycles(); - eprintln!("Collected: {}", collected); + eprintln!("Collected: {collected}"); } eprintln!("Tracked: {}", jrsonnet_gcmodule::count_thread_tracked()) } --- a/crates/jrsonnet-cli/src/manifest.rs +++ b/crates/jrsonnet-cli/src/manifest.rs @@ -1,10 +1,8 @@ use std::path::PathBuf; use clap::{Parser, ValueEnum}; -use jrsonnet_evaluator::{ - error::Result, - manifest::{JsonFormat, ManifestFormat, StringFormat, ToStringFormat, YamlStreamFormat}, - State, +use jrsonnet_evaluator::manifest::{ + JsonFormat, ManifestFormat, StringFormat, ToStringFormat, YamlStreamFormat, }; use jrsonnet_stdlib::{TomlFormat, YamlFormat}; --- a/crates/jrsonnet-cli/src/stdlib.rs +++ b/crates/jrsonnet-cli/src/stdlib.rs @@ -1,7 +1,7 @@ use std::{fs::read_to_string, str::FromStr}; use clap::Parser; -use jrsonnet_evaluator::{error::Result, tb, trace::PathResolver, State}; +use jrsonnet_evaluator::{error::Result, trace::PathResolver, State}; use jrsonnet_stdlib::ContextInitializer; #[derive(Clone)] @@ -49,7 +49,7 @@ name: out[0].into(), value: content, }), - Err(e) => Err(format!("{}", e)), + Err(e) => Err(format!("{e}")), } } } @@ -86,8 +86,7 @@ if self.no_stdlib { return Ok(None); } - let ctx = - ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback()); + let ctx = ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback()); for ext in self.ext_str.iter() { ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into()); } --- a/crates/jrsonnet-cli/src/tla.rs +++ b/crates/jrsonnet-cli/src/tla.rs @@ -3,7 +3,7 @@ error::{ErrorKind, Result}, function::TlaArg, gc::GcHashMap, - IStr, State, + IStr, }; use jrsonnet_parser::{ParserSettings, Source}; --- a/crates/jrsonnet-cli/src/trace.rs +++ b/crates/jrsonnet-cli/src/trace.rs @@ -1,9 +1,5 @@ use clap::{Parser, ValueEnum}; -use jrsonnet_evaluator::{ - error::Result, - trace::{CompactFormat, ExplainingFormat, PathResolver, TraceFormat}, - State, -}; +use jrsonnet_evaluator::trace::{CompactFormat, ExplainingFormat, PathResolver, TraceFormat}; #[derive(PartialEq, Eq, ValueEnum, Clone)] pub enum TraceFormatName { --- a/crates/jrsonnet-evaluator/src/error.rs +++ b/crates/jrsonnet-evaluator/src/error.rs @@ -274,6 +274,7 @@ f.debug_tuple("LocError").field(&self.0).finish() } } +impl std::error::Error for Error {} pub trait ErrorSource { fn to_location(self) -> Option; --- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs +++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs @@ -104,28 +104,15 @@ } } } else { - { - let ai = a.iter(); - let bi = b.iter(); + let ai = a.iter(); + let bi = b.iter(); - for (a, b) in ai.zip(bi) { - let ord = evaluate_compare_op(&a?, &b?, op)?; - if !ord.is_eq() { - return Ok(ord); - } + for (a, b) in ai.zip(bi) { + let ord = evaluate_compare_op(&a?, &b?, op)?; + if !ord.is_eq() { + return Ok(ord); } } - // { - // let ai = a.iter_expl(); - // let bi = b.iter_expl(); - - // for (a, b) in ai.zip(bi) { - // let ord = evaluate_compare_op(&a?, &b?, op)?; - // if !ord.is_eq() { - // return Ok(ord); - // } - // } - // } } a.len().cmp(&b.len()) } --- a/crates/jrsonnet-evaluator/src/lib.rs +++ b/crates/jrsonnet-evaluator/src/lib.rs @@ -36,6 +36,7 @@ clippy::use_self, // https://github.com/rust-lang/rust-clippy/issues/8539 clippy::iter_with_drain, + clippy::type_repetition_in_bounds, // ci is being run with nightly, but library should work on stable clippy::missing_const_for_fn, )] --- a/crates/jrsonnet-evaluator/src/obj.rs +++ b/crates/jrsonnet-evaluator/src/obj.rs @@ -54,7 +54,7 @@ #[cfg(feature = "exp-preserve-order")] mod ordering { - use std::cmp::Reverse; + use std::cmp::{Ordering, Reverse}; use jrsonnet_gcmodule::Trace; @@ -81,12 +81,10 @@ Self(Reverse(depth), index) } pub fn collide(self, other: Self) -> Self { - if self.0 .0 > other.0 .0 { - self - } else if self.0 .0 < other.0 .0 { - other - } else { - unreachable!("object can't have two fields with same name") + match self.0 .0.cmp(&other.0 .0) { + Ordering::Greater => self, + Ordering::Less => other, + Ordering::Equal => unreachable!("object can't have two fields with the same name"), } } } @@ -188,6 +186,12 @@ pub fn new_empty() -> Self { Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new())) } + pub fn builder() -> ObjValueBuilder { + ObjValueBuilder::new() + } + pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder { + ObjValueBuilder::with_capacity(capacity) + } #[must_use] pub fn extend_from(&self, sup: Self) -> Self { match &self.0.sup { @@ -304,7 +308,7 @@ break; } fields[j] = fields[k].clone(); - j = k + j = k; } fields[j] = x; } --- a/crates/jrsonnet-evaluator/src/val.rs +++ b/crates/jrsonnet-evaluator/src/val.rs @@ -33,6 +33,7 @@ Pending, } +/// Lazily evaluated value #[allow(clippy::module_name_repetitions)] #[derive(Clone, Trace)] pub struct Thunk(Cc>>); @@ -57,6 +58,13 @@ self.evaluate()?; Ok(()) } + + /// Evaluate thunk, or return cached value + /// + /// # Errors + /// + /// - Lazy value evaluation returned error + /// - This method was called during inner value evaluation pub fn evaluate(&self) -> Result { match &*self.0.borrow() { ThunkInner::Computed(v) => return Ok(v.clone()), @@ -132,7 +140,7 @@ } } -/// Represents a Jsonnet value, which can be spliced or indexed (string or array). +/// Represents a Jsonnet value, which can be sliced or indexed (string or array). #[allow(clippy::module_name_repetitions)] pub enum IndexableVal { /// String. @@ -247,6 +255,16 @@ } } } +impl From<&str> for StrValue { + fn from(value: &str) -> Self { + Self::Flat(value.into()) + } +} +impl From for StrValue { + fn from(value: String) -> Self { + Self::Flat(value.into()) + } +} impl Display for StrValue { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { --- a/crates/jrsonnet-parser/src/source.rs +++ b/crates/jrsonnet-parser/src/source.rs @@ -33,8 +33,8 @@ } fn dyn_eq(&self, other: &dyn $T) -> bool { let Some(other) = other.as_any().downcast_ref::() else { - return false - }; + return false + }; let this = ::as_any(self) .downcast_ref::() .expect("restricted by impl"); --- a/crates/jrsonnet-stdlib/src/lib.rs +++ b/crates/jrsonnet-stdlib/src/lib.rs @@ -211,7 +211,7 @@ locs[0].line ); } - eprintln!(" {}", value); + eprintln!(" {value}"); } } @@ -229,7 +229,7 @@ } fn extvar_source(name: &str, code: impl Into) -> Source { - let source_name = format!("", name); + let source_name = format!(""); Source::new_virtual(source_name.into(), code.into()) } --- a/crates/jrsonnet-stdlib/src/misc.rs +++ b/crates/jrsonnet-stdlib/src/misc.rs @@ -46,7 +46,7 @@ .ext_natives .get(&x) .cloned() - .map_or(Val::Null, |v| Val::Func(FuncVal::Builtin(v.clone()))) + .map_or(Val::Null, |v| Val::Func(FuncVal::Builtin(v))) } #[builtin(fields( --- a/crates/jrsonnet-stdlib/src/parse.rs +++ b/crates/jrsonnet-stdlib/src/parse.rs @@ -8,7 +8,7 @@ #[builtin] pub fn builtin_parse_json(str: IStr) -> Result { let value: Val = serde_json::from_str(&str) - .map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?; + .map_err(|e| RuntimeError(format!("failed to parse json: {e}").into()))?; Ok(value) } @@ -22,7 +22,7 @@ let mut out = vec![]; for item in value { let val = Val::deserialize(item) - .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?; + .map_err(|e| RuntimeError(format!("failed to parse yaml: {e}").into()))?; out.push(val); } Ok(if out.is_empty() { --- a/crates/jrsonnet-types/src/lib.rs +++ b/crates/jrsonnet-types/src/lib.rs @@ -150,7 +150,7 @@ if should_add_braces { write!(f, "(")?; } - write!(f, "{}", v)?; + write!(f, "{v}")?; if should_add_braces { write!(f, ")")?; } @@ -162,7 +162,7 @@ if *a == ComplexValType::Any { write!(f, "array")? } else { - write!(f, "Array<{}>", a)? + write!(f, "Array<{a}>")? } Ok(()) } @@ -171,7 +171,7 @@ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ComplexValType::Any => write!(f, "any")?, - ComplexValType::Simple(s) => write!(f, "{}", s)?, + ComplexValType::Simple(s) => write!(f, "{s}")?, ComplexValType::Char => write!(f, "char")?, ComplexValType::BoundedNumber(a, b) => write!( f, @@ -187,7 +187,7 @@ if i != 0 { write!(f, ", ")?; } - write!(f, "{}: {}", k, v)?; + write!(f, "{k}: {v}")?; } write!(f, "}}")?; } -- gitstuff