difftreelog
style fix clippy warnings
in: master
17 files changed
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -372,7 +372,7 @@
pub fn new_inclusive(start: i32, end: i32) -> Self {
Self { start, end }
}
- fn range(&self) -> impl Iterator<Item = i32> + ExactSizeIterator + DoubleEndedIterator {
+ fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {
WithExactSize(
self.start..=self.end,
(self.end as usize)
@@ -461,7 +461,7 @@
ArrayThunk::Waiting(..) => {}
};
- let ArrayThunk::Waiting(_) =
+ let ArrayThunk::Waiting(()) =
replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)
else {
unreachable!()
@@ -508,7 +508,7 @@
match &self.cached.borrow()[index] {
ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
- ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}
+ ArrayThunk::Waiting(()) | ArrayThunk::Pending => {}
};
Some(Thunk::new(ArrayElement {
@@ -597,9 +597,7 @@
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- let Some(key) = self.keys.get(index) else {
- return None;
- };
+ let key = self.keys.get(index)?;
Some(self.obj.get_lazy_or_bail(key.clone()))
}
@@ -649,9 +647,7 @@
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- let Some(key) = self.keys.get(index) else {
- return None;
- };
+ let key = self.keys.get(index)?;
// Nothing can fail in the key part, yet value is still
// lazy-evaluated
Some(Thunk::evaluated(
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -89,7 +89,7 @@
specs: &[CompSpec],
callback: &mut impl FnMut(Context) -> Result<()>,
) -> Result<()> {
- match specs.get(0) {
+ match specs.first() {
None => callback(ctx)?,
Some(CompSpec::IfSpec(IfSpecData(cond))) => {
if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {
crates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -6,8 +6,8 @@
use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
use crate::{gc::TraceBox, tb, Context, Result, Val};
-/// Can't have str | IStr, because constant BuiltinParam causes
-/// E0492: constant functions cannot refer to interior mutable data
+/// Can't have `str` | `IStr`, because constant `BuiltinParam` causes
+/// `E0492: constant functions cannot refer to interior mutable data`
#[derive(Clone, Trace)]
pub struct ParamName(Option<Cow<'static, str>>);
impl ParamName {
@@ -27,10 +27,9 @@
}
impl PartialEq<IStr> for ParamName {
fn eq(&self, other: &IStr) -> bool {
- match &self.0 {
- Some(s) => s.as_bytes() == other.as_bytes(),
- None => false,
- }
+ self.0
+ .as_ref()
+ .map_or(false, |s| s.as_bytes() == other.as_bytes())
}
}
@@ -87,7 +86,7 @@
params: params
.into_iter()
.map(|n| BuiltinParam {
- name: ParamName::new_dynamic(n.to_string()),
+ name: ParamName::new_dynamic(n),
has_default: false,
})
.collect(),
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -159,11 +159,11 @@
Val::Null => serializer.serialize_none(),
Val::Str(s) => serializer.serialize_str(&s.clone().into_flat()),
Val::Num(n) => {
- if n.fract() != 0.0 {
- serializer.serialize_f64(*n)
- } else {
+ if n.fract() == 0.0 {
let n = *n as i64;
serializer.serialize_i64(n)
+ } else {
+ serializer.serialize_f64(*n)
}
}
#[cfg(feature = "exp-bigint")]
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -41,10 +41,12 @@
clippy::missing_const_for_fn,
// too many false-positives with .expect() calls
clippy::missing_panics_doc,
- // false positive for IStr type. There is an configuration option for
- // such cases, but it doesn't work:
- // https://github.com/rust-lang/rust-clippy/issues/9801
- clippy::mutable_key_type,
+ // false positive for IStr type. There is an configuration option for
+ // such cases, but it doesn't work:
+ // https://github.com/rust-lang/rust-clippy/issues/9801
+ clippy::mutable_key_type,
+ // false positives
+ clippy::redundant_pub_crate,
)]
// For jrsonnet-macros
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -175,6 +175,8 @@
manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;
Ok(out)
}
+
+#[allow(clippy::too_many_lines)]
fn manifest_json_ex_buf(
val: &Val,
buf: &mut String,
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -171,7 +171,7 @@
// .field("assertions_ran", &self.assertions_ran)
.field("this_entries", &self.this_entries)
// .field("value_cache", &self.value_cache)
- .finish()
+ .finish_non_exhaustive()
}
}
@@ -347,7 +347,7 @@
out.with_super(self);
let mut member = out.field(key);
if value.flags.add() {
- member = member.add()
+ member = member.add();
}
if let Some(loc) = value.location {
member = member.with_location(loc);
@@ -395,7 +395,7 @@
pub fn get(&self, key: IStr) -> Result<Option<Val>> {
self.run_assertions()?;
- self.get_for(key, self.0.this().unwrap_or(self.clone()))
+ self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))
}
pub fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
@@ -474,7 +474,7 @@
type Output = Val;
fn get(self: Box<Self>) -> Result<Self::Output> {
- Ok(self.obj.get_or_bail(self.key)?)
+ self.obj.get_or_bail(self.key)
}
}
@@ -495,7 +495,7 @@
SuperDepth::default(),
&mut |depth, index, name, visibility| {
let new_sort_key = FieldSortKey::new(depth, index);
- let entry = out.entry(name.clone());
+ let entry = out.entry(name);
let (visible, _) = entry.or_insert((true, new_sort_key));
match visibility {
Visibility::Normal => {}
@@ -634,7 +634,7 @@
SuperDepth::default(),
&mut |depth, index, name, visibility| {
let new_sort_key = FieldSortKey::new(depth, index);
- let entry = out.entry(name.clone());
+ let entry = out.entry(name);
let (visible, _) = entry.or_insert((true, new_sort_key));
match visibility {
Visibility::Normal => {}
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -248,7 +248,7 @@
let (cflags, str) = try_parse_cflags(str)?;
let (width, str) = try_parse_field_width(str)?;
let (precision, str) = try_parse_precision(str)?;
- let (_, str) = try_parse_length_modifier(str)?;
+ let ((), str) = try_parse_length_modifier(str)?;
let (convtype, str) = parse_conversion_type(str)?;
Ok((
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -449,25 +449,21 @@
}
fn from_untyped(value: Val) -> Result<Self> {
- match &value {
- Val::Arr(a) => {
- if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
- return Ok(bytes.0.as_slice().into());
- };
- <Self as Typed>::TYPE.check(&value)?;
- // Any::downcast_ref::<ByteArray>(&a);
- let mut out = Vec::with_capacity(a.len());
- for e in a.iter() {
- let r = e?;
- out.push(u8::from_untyped(r)?);
- }
- Ok(out.as_slice().into())
- }
- _ => {
- <Self as Typed>::TYPE.check(&value)?;
- unreachable!()
- }
+ let Val::Arr(a) = &value else {
+ <Self as Typed>::TYPE.check(&value)?;
+ unreachable!()
+ };
+ if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
+ return Ok(bytes.0.as_slice().into());
+ };
+ <Self as Typed>::TYPE.check(&value)?;
+ // Any::downcast_ref::<ByteArray>(&a);
+ let mut out = Vec::with_capacity(a.len());
+ for e in a.iter() {
+ let r = e?;
+ out.push(u8::from_untyped(r)?);
}
+ Ok(out.as_slice().into())
}
}
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -90,7 +90,7 @@
item: impl Fn() -> Result<()>,
) -> Result<()> {
State::push_description(error_reason, || match item() {
- Ok(_) => Ok(()),
+ Ok(()) => Ok(()),
Err(mut e) => {
if let ErrorKind::TypeError(e) = &mut e.error_mut() {
(e.1).0.push(path());
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -351,6 +351,8 @@
}
}
impl PartialEq for StrValue {
+ // False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.
+ #[allow(clippy::unconditional_recursion)]
fn eq(&self, other: &Self) -> bool {
let a = self.clone().into_flat();
let b = other.clone().into_flat();
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth1#![deny(2 unsafe_op_in_unsafe_fn,3 clippy::missing_safety_doc,4 clippy::undocumented_unsafe_blocks5)]6#![warn(clippy::pedantic, clippy::nursery)]7#![allow(clippy::missing_const_for_fn)]8use std::{9 borrow::Cow,10 cell::RefCell,11 fmt::{self, Display},12 hash::{BuildHasherDefault, Hash, Hasher},13 ops::Deref,14 str,15};1617use hashbrown::{hash_map::RawEntryMut, HashMap};18use jrsonnet_gcmodule::Trace;19use rustc_hash::FxHasher;2021mod inner;22use inner::Inner;2324/// Interned string25///26/// Provides O(1) comparsions and hashing, cheap copy, and cheap conversion to [`IBytes`]27#[derive(Clone, PartialOrd, Ord, Eq)]28pub struct IStr(Inner);29impl Trace for IStr {30 fn is_type_tracked() -> bool {31 false32 }33}3435impl IStr {36 #[must_use]37 pub fn empty() -> Self {38 "".into()39 }40 #[must_use]41 pub fn as_str(&self) -> &str {42 self as &str43 }4445 #[must_use]46 pub fn cast_bytes(self) -> IBytes {47 IBytes(self.0.clone())48 }49}5051impl Deref for IStr {52 type Target = str;5354 fn deref(&self) -> &Self::Target {55 // SAFETY: Inner::check_utf8 is called on IStr construction, data is utf-856 unsafe { self.0.as_str_unchecked() }57 }58}5960impl PartialEq for IStr {61 fn eq(&self, other: &Self) -> bool {62 // all IStr should be inlined into same pool63 Inner::ptr_eq(&self.0, &other.0)64 }65}6667impl PartialEq<str> for IStr {68 fn eq(&self, other: &str) -> bool {69 self as &str == other70 }71}7273impl Hash for IStr {74 fn hash<H: Hasher>(&self, state: &mut H) {75 // IStr is always obtained from pool, where no string have duplicate, thus every unique string has unique address76 state.write_usize(Inner::as_ptr(&self.0).cast::<()>() as usize);77 }78}7980impl Drop for IStr {81 fn drop(&mut self) {82 maybe_unpool(&self.0);83 }84}8586impl fmt::Debug for IStr {87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {88 fmt::Debug::fmt(self as &str, f)89 }90}9192impl Display for IStr {93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {94 fmt::Display::fmt(self as &str, f)95 }96}9798/// Interned byte array99#[derive(Clone, PartialOrd, Ord, Eq)]100pub struct IBytes(Inner);101impl Trace for IBytes {102 fn is_type_tracked() -> bool {103 false104 }105}106107impl IBytes {108 #[must_use]109 pub fn cast_str(self) -> Option<IStr> {110 if Inner::check_utf8(&self.0) {111 Some(IStr(self.0.clone()))112 } else {113 None114 }115 }116 /// # Safety117 /// data should be valid utf8118 unsafe fn cast_str_unchecked(self) -> IStr {119 // SAFETY: data is utf8120 unsafe { Inner::assume_utf8(&self.0) };121 IStr(self.0.clone())122 }123124 #[must_use]125 pub fn as_slice(&self) -> &[u8] {126 self.0.as_slice()127 }128}129130impl Deref for IBytes {131 type Target = [u8];132133 fn deref(&self) -> &Self::Target {134 self.0.as_slice()135 }136}137138impl PartialEq for IBytes {139 fn eq(&self, other: &Self) -> bool {140 // all IStr should be inlined into same pool141 Inner::ptr_eq(&self.0, &other.0)142 }143}144145impl Hash for IBytes {146 fn hash<H: Hasher>(&self, state: &mut H) {147 // IBytes is always obtained from pool, where no string have duplicate, thus every unique string has unique address148 state.write_usize(Inner::as_ptr(&self.0).cast::<()>() as usize);149 }150}151152impl Drop for IBytes {153 fn drop(&mut self) {154 maybe_unpool(&self.0);155 }156}157158fn maybe_unpool(inner: &Inner) {159 #[cold]160 #[inline(never)]161 fn unpool(inner: &Inner) {162 // May fail on program termination163 let _ = POOL.try_with(|pool| {164 let mut pool = pool.borrow_mut();165166 if pool.remove(inner).is_none() {167 // On some platforms (i.e i686-windows), try_with will not fail after TLS168 // destructor is called, but instead re-initialize the TLS with the empty pool.169 // Allow non-pooled Drop in this case.170 // https://github.com/CertainLach/jrsonnet/issues/98#issuecomment-1591624016171 //172 // However, if pool is not empty, most likely this is issue #113, and then I don't173 // have any explainations for now.174 assert!(pool.is_empty(), "received an unpooled string not during the program termination, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");175 }176 });177 }178 // First reference - current object, second - POOL179 if Inner::strong_count(inner) <= 2 {180 unpool(inner);181 }182}183184impl fmt::Debug for IBytes {185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {186 fmt::Debug::fmt(self as &[u8], f)187 }188}189190impl<'c> From<Cow<'c, str>> for IStr {191 fn from(v: Cow<'c, str>) -> Self {192 intern_str(&v)193 }194}195impl From<&str> for IStr {196 fn from(v: &str) -> Self {197 intern_str(v)198 }199}200impl From<String> for IStr {201 fn from(s: String) -> Self {202 s.as_str().into()203 }204}205impl From<&String> for IStr {206 fn from(s: &String) -> Self {207 s.as_str().into()208 }209}210impl From<char> for IStr {211 fn from(value: char) -> Self {212 let mut buf = [0; 5];213 Self::from(&*value.encode_utf8(&mut buf))214 }215}216impl From<&[u8]> for IBytes {217 fn from(v: &[u8]) -> Self {218 intern_bytes(v)219 }220}221222#[cfg(feature = "serde")]223impl serde::Serialize for IStr {224 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>225 where226 S: serde::Serializer,227 {228 self.as_str().serialize(serializer)229 }230}231232#[cfg(feature = "serde")]233impl<'de> serde::Deserialize<'de> for IStr {234 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>235 where236 D: serde::Deserializer<'de>,237 {238 let str = <&str>::deserialize(deserializer)?;239 Ok(intern_str(str))240 }241}242243#[cfg(feature = "structdump")]244impl structdump::Codegen for IStr {245 fn gen_code(246 &self,247 res: &mut structdump::CodegenResult,248 _unique: bool,249 ) -> structdump::TokenStream {250 let s: &str = self;251 res.add_code(252 structdump::quote! {253 structdump_import::IStr::from(#s)254 },255 Some(structdump::quote![structdump_import::IStr]),256 false,257 )258 }259}260261thread_local! {262 static POOL: RefCell<HashMap<Inner, (), BuildHasherDefault<FxHasher>>> = RefCell::new(HashMap::with_capacity_and_hasher(200, BuildHasherDefault::default()));263}264265#[must_use]266pub fn intern_bytes(bytes: &[u8]) -> IBytes {267 POOL.with(|pool| {268 let mut pool = pool.borrow_mut();269 let entry = pool.raw_entry_mut().from_key(bytes);270 match entry {271 RawEntryMut::Occupied(i) => IBytes(i.get_key_value().0.clone()),272 RawEntryMut::Vacant(e) => {273 let (k, ()) = e.insert(Inner::new_bytes(bytes), ());274 IBytes(k.clone())275 }276 }277 })278}279280#[must_use]281pub fn intern_str(str: &str) -> IStr {282 // SAFETY: Rust strings always utf8283 unsafe { intern_bytes(str.as_bytes()).cast_str_unchecked() }284}285286#[cfg(test)]287mod tests {288 use crate::IStr;289290 #[test]291 fn simple() {292 let a = IStr::from("a");293 let b = IStr::from("a");294295 assert_eq!(a.as_ptr(), b.as_ptr());296 }297}crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -374,6 +374,7 @@
fn params(&self) -> &[BuiltinParam] {
PARAMS
}
+ #[allow(unused_variable)]
fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;
crates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -39,5 +39,5 @@
let bytes = STANDARD
.decode(str.as_bytes())
.map_err(|e| runtime_error!("invalid base64: {e}"))?;
- Ok(String::from_utf8(bytes).map_err(|_| runtime_error!("bad utf8"))?)
+ String::from_utf8(bytes).map_err(|_| runtime_error!("bad utf8"))
}
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -47,7 +47,7 @@
.ext_natives
.get(&x)
.cloned()
- .map_or(Val::Null, |v| Val::Func(v))
+ .map_or(Val::Null, Val::Func)
}
#[builtin(fields(
flake.lockdiffbeforeafterboth--- a/flake.lock
+++ b/flake.lock
@@ -5,11 +5,11 @@
"systems": "systems"
},
"locked": {
- "lastModified": 1694529238,
- "narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
+ "lastModified": 1705309234,
+ "narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
"owner": "numtide",
"repo": "flake-utils",
- "rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
+ "rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
"type": "github"
},
"original": {
@@ -20,11 +20,11 @@
},
"nixpkgs": {
"locked": {
- "lastModified": 1701376520,
- "narHash": "sha256-U3iGiOZqgu7wvVzgfoQzGGFMqNsDj/q/6zPIjCy7ajg=",
+ "lastModified": 1705391267,
+ "narHash": "sha256-gGVm9QudiRtYTX8PN9cTTy7uuJcL4I2lRMoPx496kXk=",
"owner": "nixos",
"repo": "nixpkgs",
- "rev": "c74cc3c3db2ed5e68895953d75c397797d499133",
+ "rev": "41a9a7f170c740acb24f3390323877d11c69d5ee",
"type": "github"
},
"original": {
@@ -50,11 +50,11 @@
]
},
"locked": {
- "lastModified": 1701310566,
- "narHash": "sha256-CL9J3xUR2Ejni4LysrEGX0IdO+Y4BXCiH/By0lmF3eQ=",
+ "lastModified": 1705371439,
+ "narHash": "sha256-P1kulUXpYWkcrjiX3sV4j8ACJZh9XXSaaD+jDLBDLKo=",
"owner": "oxalica",
"repo": "rust-overlay",
- "rev": "6d3c6e185198b8bf7ad639f22404a75aa9a09bff",
+ "rev": "b21f3c0d5bf0f0179f5f0140e8e0cd099618bd04",
"type": "github"
},
"original": {
flake.nixdiffbeforeafterboth--- a/flake.nix
+++ b/flake.nix
@@ -25,14 +25,14 @@
lib = pkgs.lib;
rust =
(pkgs.rustChannelOf {
- date = "2023-10-28";
+ date = "2024-01-10";
channel = "nightly";
})
.default
.override {
extensions = ["rust-src" "miri" "rust-analyzer" "clippy"];
};
- in rec {
+ in {
packages = rec {
go-jsonnet = pkgs.callPackage ./nix/go-jsonnet.nix {};
sjsonnet = pkgs.callPackage ./nix/sjsonnet.nix {};