From 46d9d1dd22a7a0c6db1497f8ec70cac281efc2e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?joseLu=C3=ADs?= Date: Mon, 18 Nov 2024 11:13:45 +0100 Subject: [PATCH] fix hundreds of clippy warnings - aLlow single instances of: `clippy::wrong_self_convention`, `clippy::enum_variant_names` and `clippy::vec_box`. - rustfmt. --- derive/src/lib.rs | 60 +++++++--------- derive/src/parse.rs | 148 +++++++++++++++++---------------------- derive/src/serde_bin.rs | 4 +- derive/src/serde_json.rs | 52 +++++++------- derive/src/serde_ron.rs | 31 +++----- derive/src/shared.rs | 4 +- src/serde_bin.rs | 2 +- src/serde_json.rs | 73 ++++++++----------- src/serde_ron.rs | 47 +++++-------- src/toml.rs | 11 ++- 10 files changed, 183 insertions(+), 249 deletions(-) diff --git a/derive/src/lib.rs b/derive/src/lib.rs index 99943d0..bb79dd2 100644 --- a/derive/src/lib.rs +++ b/derive/src/lib.rs @@ -30,19 +30,17 @@ mod parse; pub fn derive_ser_bin(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse::parse_data(input); - if let Some(proxy) = shared::attrs_proxy(&input.attributes()) { - return derive_ser_bin_proxy(&proxy, &input.name()); + if let Some(proxy) = shared::attrs_proxy(input.attributes()) { + return derive_ser_bin_proxy(&proxy, input.name()); } // ok we have an ident, its either a struct or a enum - let ts = match &input { + match &input { parse::Data::Struct(struct_) if struct_.named => derive_ser_bin_struct(struct_), parse::Data::Struct(struct_) => derive_ser_bin_struct_unnamed(struct_), parse::Data::Enum(enum_) => derive_ser_bin_enum(enum_), _ => unimplemented!("Only structs and enums are supported"), - }; - - ts + } } #[cfg(feature = "binary")] @@ -50,20 +48,18 @@ pub fn derive_ser_bin(input: proc_macro::TokenStream) -> proc_macro::TokenStream pub fn derive_de_bin(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse::parse_data(input); - if let Some(proxy) = shared::attrs_proxy(&input.attributes()) { - return derive_de_bin_proxy(&proxy, &input.name()); + if let Some(proxy) = shared::attrs_proxy(input.attributes()) { + return derive_de_bin_proxy(&proxy, input.name()); } // ok we have an ident, its either a struct or a enum - let ts = match &input { + match &input { parse::Data::Struct(struct_) if struct_.named => derive_de_bin_struct(struct_), parse::Data::Struct(struct_) => derive_de_bin_struct_unnamed(struct_), parse::Data::Enum(enum_) => derive_de_bin_enum(enum_), _ => unimplemented!("Only structs and enums are supported"), - }; - - ts + } } #[cfg(feature = "ron")] @@ -71,19 +67,17 @@ pub fn derive_de_bin(input: proc_macro::TokenStream) -> proc_macro::TokenStream pub fn derive_ser_ron(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse::parse_data(input); - if let Some(proxy) = shared::attrs_proxy(&input.attributes()) { - return derive_ser_ron_proxy(&proxy, &input.name()); + if let Some(proxy) = shared::attrs_proxy(input.attributes()) { + return derive_ser_ron_proxy(&proxy, input.name()); } // ok we have an ident, its either a struct or a enum - let ts = match &input { + match &input { parse::Data::Struct(struct_) if struct_.named => derive_ser_ron_struct(struct_), parse::Data::Struct(struct_) => derive_ser_ron_struct_unnamed(struct_), parse::Data::Enum(enum_) => derive_ser_ron_enum(enum_), _ => unimplemented!("Only structs and enums are supported"), - }; - - ts + } } #[cfg(feature = "ron")] @@ -91,19 +85,17 @@ pub fn derive_ser_ron(input: proc_macro::TokenStream) -> proc_macro::TokenStream pub fn derive_de_ron(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse::parse_data(input); - if let Some(proxy) = shared::attrs_proxy(&input.attributes()) { - return derive_de_ron_proxy(&proxy, &input.name()); + if let Some(proxy) = shared::attrs_proxy(input.attributes()) { + return derive_de_ron_proxy(&proxy, input.name()); } // ok we have an ident, its either a struct or a enum - let ts = match &input { + match &input { parse::Data::Struct(struct_) if struct_.named => derive_de_ron_struct(struct_), parse::Data::Struct(struct_) => derive_de_ron_struct_unnamed(struct_), parse::Data::Enum(enum_) => derive_de_ron_enum(enum_), _ => unimplemented!("Only structs and enums are supported"), - }; - - ts + } } #[cfg(feature = "json")] @@ -111,19 +103,17 @@ pub fn derive_de_ron(input: proc_macro::TokenStream) -> proc_macro::TokenStream pub fn derive_ser_json(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse::parse_data(input); - if let Some(proxy) = shared::attrs_proxy(&input.attributes()) { - return derive_ser_json_proxy(&proxy, &input.name()); + if let Some(proxy) = shared::attrs_proxy(input.attributes()) { + return derive_ser_json_proxy(&proxy, input.name()); } // ok we have an ident, its either a struct or a enum - let ts = match &input { + match &input { parse::Data::Struct(struct_) if struct_.named => derive_ser_json_struct(struct_), parse::Data::Struct(struct_) => derive_ser_json_struct_unnamed(struct_), parse::Data::Enum(enum_) => derive_ser_json_enum(enum_), _ => unimplemented!(""), - }; - - ts + } } #[cfg(feature = "json")] @@ -131,17 +121,15 @@ pub fn derive_ser_json(input: proc_macro::TokenStream) -> proc_macro::TokenStrea pub fn derive_de_json(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse::parse_data(input); - if let Some(proxy) = shared::attrs_proxy(&input.attributes()) { - return derive_de_json_proxy(&proxy, &input.name()); + if let Some(proxy) = shared::attrs_proxy(input.attributes()) { + return derive_de_json_proxy(&proxy, input.name()); } // ok we have an ident, its either a struct or a enum - let ts = match &input { + match &input { parse::Data::Struct(struct_) if struct_.named => derive_de_json_struct(struct_), parse::Data::Struct(struct_) => derive_de_json_struct_unnamed(struct_), parse::Data::Enum(enum_) => derive_de_json_enum(enum_), parse::Data::Union(_) => unimplemented!("Unions are not supported"), - }; - - ts + } } diff --git a/derive/src/parse.rs b/derive/src/parse.rs index 6a7a104..56c79ae 100644 --- a/derive/src/parse.rs +++ b/derive/src/parse.rs @@ -82,6 +82,7 @@ pub enum Category { }, Object { is_dyn: bool, + #[allow(clippy::vec_box)] trait_names: Vec>, }, Associated { @@ -108,6 +109,7 @@ pub struct Type { } #[derive(Debug, Clone)] +#[allow(clippy::enum_variant_names)] pub enum Generic { ConstGeneric { name: String, @@ -251,7 +253,7 @@ impl Generic { if bounds.is_empty() { bounds = extra_bounds.join(" + ") } else { - bounds = vec![bounds, extra_bounds.join(" + ")].join(" + ") + bounds = [bounds, extra_bounds.join(" + ")].join(" + ") } } bounds @@ -429,7 +431,7 @@ impl Type { }, None => String::default(), }; - base.push_str(&self.ident.path(&self, false)); + base.push_str(&self.ident.path(self, false)); base } @@ -441,12 +443,12 @@ impl Type { }, None => String::default(), }; - base.push_str(&self.ident.path(&self, false)); + base.push_str(&self.ident.path(self, false)); if let (Some(wrapped), Category::Named { .. }) = (&self.wraps, &self.ident) { base.push('<'); base.push_str( wrapped - .into_iter() + .iter() .map(|x| x.full()) .collect::>() .join(",") @@ -480,8 +482,7 @@ pub fn next_visibility_modifier( return Some("pub".to_string()); } } - - return None; + None } pub fn next_punct(source: &mut Peekable>) -> Option { @@ -490,8 +491,7 @@ pub fn next_punct(source: &mut Peekable>) -> Opt source.next(); return Some(punct); } - - return None; + None } pub fn next_exact_punct( @@ -505,8 +505,7 @@ pub fn next_exact_punct( return Some(punct); } } - - return None; + None } pub fn next_literal(source: &mut Peekable>) -> Option { @@ -521,8 +520,7 @@ pub fn next_literal(source: &mut Peekable>) -> O source.next(); return Some(literal); } - - return None; + None } pub fn next_eof(source: &mut Peekable) -> Option<()> { @@ -573,7 +571,7 @@ pub fn next_lifetime>(source: &mut Peekable) -> }) } -fn next_type + Clone>(mut source: &mut Peekable) -> Option { +fn next_type + Clone>(source: &mut Peekable) -> Option { fn as_associated_definition + Clone>( source: &mut Peekable, ) -> Option { @@ -599,11 +597,11 @@ fn next_type + Clone>(mut source: &mut Peekable None } pub fn next_array + Clone>( - mut source: &mut Peekable, + source: &mut Peekable, ) -> Option { - let next = next_type(&mut source).expect("Must be type after array declaration"); + let next = next_type(source).expect("Must be type after array declaration"); - let Some(_) = next_exact_punct(&mut source, ";") else { + let Some(_) = next_exact_punct(source, ";") else { // This is an unbounded array, legal at end for unsized types return Some(Type { ident: Category::Array { @@ -656,7 +654,7 @@ fn next_type + Clone>(mut source: &mut Peekable let mut path = "(".to_owned(); while let Some(next_ty) = next_type(source) { wraps.push(next_ty.clone()); - path.push_str(&format!("{}", next_ty.full())); + path.push_str(&next_ty.full().to_string()); if next_exact_punct(source, ",").is_none() { break; } @@ -673,7 +671,7 @@ fn next_type + Clone>(mut source: &mut Peekable as_other: None, }; - return Some(tuple_type); + Some(tuple_type) } pub fn next_function_like + Clone>( @@ -713,14 +711,14 @@ fn next_type + Clone>(mut source: &mut Peekable let mut base = ret .iter() .filter_map(|x| x.wraps.as_ref()) - .cloned() .flatten() + .cloned() .collect::>(); base.extend( args.iter() .filter_map(|x| x.wraps.as_ref()) - .cloned() - .flatten(), + .flatten() + .cloned(), ); Some(base) } else { @@ -738,7 +736,7 @@ fn next_type + Clone>(mut source: &mut Peekable } } - let Some(TokenTree::Ident(ident)) = source.peek().clone() else { + let Some(TokenTree::Ident(ident)) = source.peek() else { return None; }; let true = matches!(ident.to_string().as_str(), "fn" | "FnOnce" | "FnMut" | "Fn") else { @@ -764,8 +762,8 @@ fn next_type + Clone>(mut source: &mut Peekable let mut base = ret .iter() .filter_map(|x| x.wraps.as_ref()) - .cloned() .flatten() + .cloned() .collect::>(); base.extend_from_slice(args.wraps.clone().unwrap_or_default().as_ref()); Some(base) @@ -804,7 +802,7 @@ fn next_type + Clone>(mut source: &mut Peekable let mut ident_types = vec![Box::new( next_type(source).expect("impl must be followed by trait"), )]; - while let Some(_) = next_exact_punct(source, "+") { + while next_exact_punct(source, "+").is_some() { ident_types.push(Box::new( next_type(source).expect("impl must be followed by trait"), )) @@ -826,7 +824,7 @@ fn next_type + Clone>(mut source: &mut Peekable let mut ident_types = vec![Box::new( next_type(source).expect("impl must be followed by trait"), )]; - while let Some(_) = next_exact_punct(source, "+") { + while next_exact_punct(source, "+").is_some() { ident_types.push(Box::new( next_type(source).expect("impl must be followed by trait"), )) @@ -851,11 +849,11 @@ fn next_type + Clone>(mut source: &mut Peekable // // - if let Some(_) = next_exact_punct(&mut source, ",") { + if next_exact_punct(source, ",").is_some() { return None; }; - if let Some(_) = next_exact_punct(&mut source, "!") { + if next_exact_punct(source, "!").is_some() { return Some(Type { ident: Category::Never, wraps: None, @@ -875,31 +873,20 @@ fn next_type + Clone>(mut source: &mut Peekable }); }; - let ref_type = match next_exact_punct(&mut source, "&") { - Some(_) => Some(next_lifetime(source)), - None => None, - }; + let ref_type = next_exact_punct(source, "&").map(|_| next_lifetime(source)); if let Some(group) = next_group(&mut source.clone()) { match group.delimiter() { Delimiter::Bracket => { - let mut group_stream = next_group(&mut source) - .unwrap() - .stream() - .into_iter() - .peekable(); + let mut group_stream = next_group(source).unwrap().stream().into_iter().peekable(); return next_array(&mut group_stream).map(|x| x.set_ref_type(ref_type)); } Delimiter::Parenthesis => { - let mut group_stream = next_group(&mut source) - .unwrap() - .stream() - .into_iter() - .peekable(); + let mut group_stream = next_group(source).unwrap().stream().into_iter().peekable(); return next_tuple(&mut group_stream).map(|x| x.set_ref_type(ref_type)); } Delimiter::Brace => { - let anonymous_struct = next_struct(&mut source); + let anonymous_struct = next_struct(source); let wraps = Some( anonymous_struct .fields @@ -937,7 +924,7 @@ fn next_type + Clone>(mut source: &mut Peekable } // read a path like a::b::c::d - let mut ty = next_ident(&mut source).unwrap_or_default(); + let mut ty = next_ident(source).unwrap_or_default(); while let Some(TokenTree::Punct(_)) = source.peek() { let mut tmp = source.clone(); let (Some(_), Some(_)) = ( @@ -949,11 +936,11 @@ fn next_type + Clone>(mut source: &mut Peekable drop(tmp); let _ = (source.next(), source.next()); //skip the colons - let next_ident = next_ident(&mut source).expect("Expecting next path part after ::"); + let next_ident = next_ident(source).expect("Expecting next path part after ::"); ty.push_str(&format!("::{}", next_ident)); } - let angel_bracket = next_exact_punct(&mut source, "<"); + let angel_bracket = next_exact_punct(source, "<"); if angel_bracket.is_some() { if ty.is_empty() { let ty = next_type(source).expect("Need a base type before 'as'"); @@ -967,10 +954,7 @@ fn next_type + Clone>(mut source: &mut Peekable assert_eq!(Some(">".to_owned()), next_exact_punct(source, ">")); assert_eq!( (Some(":".to_owned()), Some(":".to_owned())), - ( - next_exact_punct(&mut source, ":"), - next_exact_punct(&mut source, ":") - ) + (next_exact_punct(source, ":"), next_exact_punct(source, ":")) ); let associated = next_type(source).expect("Must be an associated type name after the trait"); @@ -987,14 +971,14 @@ fn next_type + Clone>(mut source: &mut Peekable associated: Box::new(associated), }, wraps: ty.wraps, - ref_type: ref_type, + ref_type, as_other: None, }); } let mut generics = vec![next_type(source).expect("Expecting at least one generic argument")]; - while let Some(_comma) = next_exact_punct(&mut source, ",") { + while let Some(_comma) = next_exact_punct(source, ",") { generics.push(next_type(source).expect("Expecting generic argument after comma")); } @@ -1002,7 +986,7 @@ fn next_type + Clone>(mut source: &mut Peekable if let Some(assoc_def) = as_associated_definition(source) { let _closing_bracket = - next_exact_punct(&mut source, ">").expect("Expecting closing generic bracket"); + next_exact_punct(source, ">").expect("Expecting closing generic bracket"); return Some(Type { ident: Category::AssociatedBound { associated: ty, @@ -1015,7 +999,7 @@ fn next_type + Clone>(mut source: &mut Peekable } let _closing_bracket = - next_exact_punct(&mut source, ">").expect("Expecting closing generic bracket"); + next_exact_punct(source, ">").expect("Expecting closing generic bracket"); Some(Type { ident: Category::Named { path: ty }, @@ -1044,15 +1028,15 @@ fn next_type + Clone>(mut source: &mut Peekable } fn next_attribute>( - mut source: &mut Peekable, + source: &mut Peekable, ) -> Option>> { // all attributes, even doc-comments, starts with "#" - let next_attr_punct = next_punct(&mut source); + let next_attr_punct = next_punct(source); let Some("#") = next_attr_punct.as_deref() else { return None; }; - let mut attr_group = next_group(&mut source) + let mut attr_group = next_group(source) .expect("Expecting attribute body") .stream() .into_iter() @@ -1125,7 +1109,7 @@ fn next_attribute>( } } - return Some(Some(attrs)); + Some(Some(attrs)) } fn next_attributes_list(source: &mut Peekable>) -> Vec { @@ -1141,30 +1125,30 @@ fn next_attributes_list(source: &mut Peekable>) } fn next_fields + Clone>( - mut body: &mut Peekable, + body: &mut Peekable, named: bool, ) -> Vec { let mut fields = vec![]; loop { - if next_eof(&mut body).is_some() { + if next_eof(body).is_some() { break; } - let attributes = next_attributes_list(&mut body); - let _visibility = next_visibility_modifier(&mut body); + let attributes = next_attributes_list(body); + let _visibility = next_visibility_modifier(body); let field_name = if named { - let field_name = next_ident(&mut body).expect("Field name expected"); + let field_name = next_ident(body).expect("Field name expected"); - let _ = next_exact_punct(&mut body, ":").expect("Delimeter after field name expected"); + let _ = next_exact_punct(body, ":").expect("Delimeter after field name expected"); Some(field_name) } else { None }; - let ty = next_type(&mut body).expect("Expected field type"); - let _punct = next_punct(&mut body); + let ty = next_type(body).expect("Expected field type"); + let _punct = next_punct(body); fields.push(Field { attributes, @@ -1176,14 +1160,14 @@ fn next_fields + Clone>( fields } -fn next_struct + Clone>(mut source: &mut Peekable) -> Struct { - let struct_name = next_ident(&mut source); +fn next_struct + Clone>(source: &mut Peekable) -> Struct { + let struct_name = next_ident(source); let generics = get_all_bounds(source); - let group = next_group(&mut source); + let group = next_group(source); // unit struct if group.is_none() { // skip ; at the end of struct like this: "struct Foo;" - let _ = next_punct(&mut source); + let _ = next_punct(source); return Struct { name: struct_name, @@ -1206,8 +1190,8 @@ fn next_struct + Clone>(mut source: &mut Peekable< let mut body = group.stream().into_iter().peekable(); let fields = next_fields(&mut body, named); - if named == false { - next_exact_punct(&mut source, ";").expect("Expected ; on the end of tuple struct"); + if !named { + next_exact_punct(source, ";").expect("Expected ; on the end of tuple struct"); } Struct { @@ -1219,10 +1203,10 @@ fn next_struct + Clone>(mut source: &mut Peekable< } } -fn next_enum + Clone>(mut source: &mut Peekable) -> Enum { - let enum_name = next_ident(&mut source).expect("Unnamed enums are not supported"); +fn next_enum + Clone>(source: &mut Peekable) -> Enum { + let enum_name = next_ident(source).expect("Unnamed enums are not supported"); let generic_types = get_all_bounds(source); - let group = next_group(&mut source); + let group = next_group(source); // unit enum if group.is_none() { return Enum { @@ -1270,7 +1254,7 @@ fn next_enum + Clone>(mut source: &mut Peekable { variants.push(Field { field_name: Some(variant_name), - ty: ty, + ty, attributes, vis: Visibility::Public, }); @@ -1301,7 +1285,7 @@ fn next_const_generic + Clone>( "Colon should follow const generic typename" ); let cg_type = next_type(source).expect("Missing const generic type after 'colon'"); - if let Some(_) = next_exact_punct(source, "=") { + if next_exact_punct(source, "=").is_some() { if let Ok(default_value) = source .peek() .expect("default should follow equal for const generic") @@ -1323,9 +1307,7 @@ fn next_const_generic + Clone>( fn next_generic + Clone>( source: &mut Peekable, ) -> Option { - let Some(tok) = source.peek() else { - return None; - }; + let tok = source.peek()?; match tok { TokenTree::Group(g) => { if matches!(g.delimiter(), Delimiter::Brace) { @@ -1333,7 +1315,7 @@ fn next_generic + Clone>( } let mut bounds = vec![]; let _type = next_type(source).expect("must be a type in group"); - if let Some(_) = next_exact_punct(source, ":") { + if next_exact_punct(source, ":").is_some() { while let Some(bound) = next_type(source) { bounds.push(bound); if next_exact_punct(source, "+").is_none() { @@ -1362,7 +1344,7 @@ fn next_generic + Clone>( let mut bounds = vec![]; - if let Some(_) = next_exact_punct(source, ":") { + if next_exact_punct(source, ":").is_some() { loop { if let Some(ty) = next_type(source) { bounds.push(ty); @@ -1373,7 +1355,7 @@ fn next_generic + Clone>( } } - if let Some(_) = next_exact_punct(source, "=") { + if next_exact_punct(source, "=").is_some() { default = Some(next_type(source).expect("Must be a default after eq sign")); } Some(Generic::Generic { @@ -1387,7 +1369,7 @@ fn next_generic + Clone>( '\'' => { let ty = next_lifetime(source).expect("must be lifetime after \' mark"); let mut bounds = vec![]; - if let Some(_) = next_exact_punct(source, ":") { + if next_exact_punct(source, ":").is_some() { while let Some(bound) = next_lifetime(source) { bounds.push(bound); if next_exact_punct(source, "+").is_none() { diff --git a/derive/src/serde_bin.rs b/derive/src/serde_bin.rs index c9300c8..7c775fe 100644 --- a/derive/src/serde_bin.rs +++ b/derive/src/serde_bin.rs @@ -219,7 +219,7 @@ pub fn derive_ser_bin_enum(enum_: &Enum) -> TokenStream { .. } => { l!(r, "Self::{} {{", ident); - for (_, f) in contents.fields.iter().enumerate() { + for f in contents.fields.iter() { l!( r, "{}, ", @@ -229,7 +229,7 @@ pub fn derive_ser_bin_enum(enum_: &Enum) -> TokenStream { l!(r, "} => {"); l!(r, "{}.ser_bin(s);", lit); - for (_, f) in contents.fields.iter().enumerate() { + for f in contents.fields.iter() { l!( r, "{}.ser_bin(s);", diff --git a/derive/src/serde_json.rs b/derive/src/serde_json.rs index fb3c599..36564ba 100644 --- a/derive/src/serde_json.rs +++ b/derive/src/serde_json.rs @@ -35,7 +35,7 @@ fn ser_proxy_guard(fieldname: &str, field: &Field) -> String { format!("{{let proxy: {proxy} = Into::into(&{fieldname});proxy}}",) } } else { - format!("{fieldname}") + fieldname.to_string() } } @@ -45,8 +45,8 @@ pub fn derive_ser_json_struct(struct_: &Struct) -> TokenStream { l!(s, "let mut first_field_was_serialized = false;"); - if struct_.fields.len() >= 1 { - for (_index, field) in struct_.fields.iter().enumerate() { + if !struct_.fields.is_empty() { + for field in struct_.fields.iter() { let struct_fieldname = field.field_name.clone().unwrap(); let json_fieldname = shared::attrs_rename(&field.attributes).unwrap_or_else(|| struct_fieldname.clone()); @@ -153,12 +153,10 @@ pub fn derive_de_json_named(name: &str, defaults: bool, fields: &[Field]) -> Tok val = format!("Some({})", val); } Some(val) + } else if field.ty.base() != "Option" { + Some(String::from("Default::default()")) } else { - if field.ty.base() != "Option" { - Some(String::from("Default::default()")) - } else { - Some(String::from("None")) - } + Some(String::from("None")) } } else if let Some(mut v) = field_attr_default_with { v.push_str("()"); @@ -178,10 +176,10 @@ pub fn derive_de_json_named(name: &str, defaults: bool, fields: &[Field]) -> Tok format!("From::<&{proxy}>::from(&t)") } } else { - format!("t") + "t".to_string() }; - if skip == false { + if !skip { if field.ty.base() == "Option" { unwraps.push(format!( "{{if let Some(t) = {} {{ {} }} else {{ {} }} }}", @@ -219,7 +217,7 @@ pub fn derive_de_json_named(name: &str, defaults: bool, fields: &[Field]) -> Tok l!(r, "s.curly_open(i) ?;"); l!(r, "while let Some(_) = s.next_str() {"); - if json_field_names.len() != 0 { + if !json_field_names.is_empty() { l!(r, "match AsRef::::as_ref(&s.strbuf) {"); for (json_field_name, local_var) in matches.iter() { l!( @@ -266,7 +264,7 @@ pub fn derive_de_json_proxy(proxy_type: &str, type_: &str) -> TokenStream { pub fn derive_de_json_struct(struct_: &Struct) -> TokenStream { let body = derive_de_json_named( - &struct_ + struct_ .name .as_ref() .expect("Cannot implement for anonymous struct"), @@ -337,23 +335,21 @@ pub fn derive_ser_json_enum(enum_: &Enum) -> TokenStream { proxied_field ) } - } else { - if field.ty.base() == "Option" { - l!( - items, - "if {}.is_some(){{s.field(d+1, \"{}\");{}.ser_json(d+1, s);s.conl();}}", - name, - name, - proxied_field - ); - } else { - l!( + } else if field.ty.base() == "Option" { + l!( items, - "s.field(d+1, \"{}\");{}.ser_json(d+1, s);s.conl();", + "if {}.is_some(){{s.field(d+1, \"{}\");{}.ser_json(d+1, s);s.conl();}}", + name, name, proxied_field ); - } + } else { + l!( + items, + "s.field(d+1, \"{}\");{}.ser_json(d+1, s);s.conl();", + name, + proxied_field + ); } field_names.push(name.clone()); } @@ -548,7 +544,7 @@ pub fn derive_ser_json_struct_unnamed(struct_: &Struct) -> TokenStream { let transparent = shared::attrs_transparent(&struct_.attributes); // encode empty struct as {} - if struct_.fields.len() == 0 { + if struct_.fields.is_empty() { l!(body, "s.out.push('}');"); l!(body, "s.out.push('{');"); } @@ -605,8 +601,8 @@ pub fn derive_de_json_struct_unnamed(struct_: &Struct) -> TokenStream { } // no fields - was encoded as {} - let body = if struct_.fields.len() == 0 { - format!("s.curly_open(i)?;let r = Self;s.curly_close(i)?;") + let body = if struct_.fields.is_empty() { + "s.curly_open(i)?;let r = Self;s.curly_close(i)?;".to_string() } // if it was transparent newtype struct - skip "container" // and just deserialize content diff --git a/derive/src/serde_ron.rs b/derive/src/serde_ron.rs index 0f0bc60..87ad9b1 100644 --- a/derive/src/serde_ron.rs +++ b/derive/src/serde_ron.rs @@ -1,6 +1,6 @@ use alloc::format; use alloc::string::{String, ToString}; -use alloc::{vec, vec::Vec}; +use alloc::vec::Vec; use crate::parse::{Attribute, Category, Enum, Field, Struct, Type}; @@ -119,11 +119,7 @@ pub fn derive_ser_ron_struct_unnamed(struct_: &Struct) -> TokenStream { .unwrap() } -pub fn derive_de_ron_named( - name: &String, - fields: &Vec, - attributes: &Vec, -) -> String { +pub fn derive_de_ron_named(name: &String, fields: &Vec, attributes: &[Attribute]) -> String { let mut local_vars = Vec::new(); let mut struct_field_names = Vec::new(); let mut ron_field_names = Vec::new(); @@ -145,12 +141,10 @@ pub fn derive_de_ron_named( val = format!("Some({})", val); } Some(val) + } else if field.ty.base() != "Option" { + Some(String::from("Default::default()")) } else { - if field.ty.base() != "Option" { - Some(String::from("Default::default()")) - } else { - Some(String::from("None")) - } + Some(String::from("None")) } } else if let Some(mut v) = field_attr_default_with { v.push_str("()"); @@ -162,7 +156,7 @@ pub fn derive_de_ron_named( shared::attrs_rename(&field.attributes).unwrap_or(struct_fieldname.clone()); let skip = crate::shared::attrs_skip(&field.attributes); - if skip == false { + if !skip { if field.ty.base() == "Option" { unwraps.push(format!( "{{ @@ -202,10 +196,7 @@ pub fn derive_de_ron_named( } else { unwraps.push(format!( "{{ {} }}", - default_val - .as_ref() - .map(|x| x.as_str()) - .unwrap_or_else(|| "Default::default()") + default_val.as_deref().unwrap_or("Default::default()") )); } @@ -225,7 +216,7 @@ pub fn derive_de_ron_named( ) } - let match_names = if ron_field_names.len() != 0 { + let match_names = if !ron_field_names.is_empty() { let mut inner = String::new(); for (ron_field_name, (local_var, _)) in ron_field_names.iter().zip(local_vars.iter()) { l!( @@ -274,7 +265,7 @@ pub fn derive_de_ron_named( pub fn derive_de_ron_struct(struct_: &Struct) -> TokenStream { let body = derive_de_ron_named( - &struct_ + struct_ .name .as_ref() .expect("Cannot implement for anonymous struct"), @@ -337,7 +328,7 @@ pub fn derive_ser_ron_enum(enum_: &Enum) -> TokenStream { } => { let mut names = Vec::new(); let mut inner = String::new(); - for (_, field) in contents.fields.iter().enumerate() { + for field in contents.fields.iter() { let name = field.field_name.as_ref().unwrap(); names.push(name.clone()); if field.ty.base() == "Option" { @@ -445,7 +436,7 @@ pub fn derive_de_ron_enum(enum_: &Enum) -> TokenStream { .. } => { let name = format!("{}::{}", enum_.name, ident); - let inner = derive_de_ron_named(&name, &contents.fields, &vec![]); + let inner = derive_de_ron_named(&name, &contents.fields, &[]); l!(body, "\"{}\" => {}", ident, inner); } Type { diff --git a/derive/src/shared.rs b/derive/src/shared.rs index 4bd499f..a1fbce2 100644 --- a/derive/src/shared.rs +++ b/derive/src/shared.rs @@ -106,7 +106,7 @@ pub(crate) fn struct_bounds_strings(struct_: &Struct, bound_name: &str) -> (Stri generic_no_bounds += ", "; } generic_no_bounds += ">"; - return (generic_w_bounds, generic_no_bounds); + (generic_w_bounds, generic_no_bounds) } #[cfg(any(feature = "binary", feature = "json"))] @@ -131,5 +131,5 @@ pub(crate) fn enum_bounds_strings(enum_: &Enum, bound_name: &str) -> (String, St generic_no_bounds += ", "; } generic_no_bounds += ">"; - return (generic_w_bounds, generic_no_bounds); + (generic_w_bounds, generic_no_bounds) } diff --git a/src/serde_bin.rs b/src/serde_bin.rs index 4e389fb..6521aa6 100644 --- a/src/serde_bin.rs +++ b/src/serde_bin.rs @@ -107,7 +107,7 @@ macro_rules! impl_ser_de_bin_for { if *o + l > d.len() { return Err(DeBinErr { o: *o, - l: l, + l, s: d.len(), }); } diff --git a/src/serde_json.rs b/src/serde_json.rs index a025b7d..0f6306d 100644 --- a/src/serde_json.rs +++ b/src/serde_json.rs @@ -107,7 +107,7 @@ pub trait DeJson: Sized { } /// A JSON parsed token. -#[derive(PartialEq, Debug)] +#[derive(PartialEq, Debug, Default)] #[non_exhaustive] pub enum DeJsonTok { Str, @@ -124,16 +124,11 @@ pub enum DeJsonTok { BlockOpen, BlockClose, Comma, + #[default] Bof, Eof, } -impl Default for DeJsonTok { - fn default() -> Self { - DeJsonTok::Bof - } -} - /// The internal state of a JSON deserialization. #[derive(Default)] #[non_exhaustive] @@ -468,32 +463,32 @@ impl DeJsonState { ':' => { self.next(i); self.tok = DeJsonTok::Colon; - return Ok(()); + Ok(()) } ',' => { self.next(i); self.tok = DeJsonTok::Comma; - return Ok(()); + Ok(()) } '[' => { self.next(i); self.tok = DeJsonTok::BlockOpen; - return Ok(()); + Ok(()) } ']' => { self.next(i); self.tok = DeJsonTok::BlockClose; - return Ok(()); + Ok(()) } '{' => { self.next(i); self.tok = DeJsonTok::CurlyOpen; - return Ok(()); + Ok(()) } '}' => { self.next(i); self.tok = DeJsonTok::CurlyClose; - return Ok(()); + Ok(()) } '-' | '+' | '0'..='9' => { self.numbuf.truncate(0); @@ -535,9 +530,9 @@ impl DeJsonState { if is_float { if let Ok(num) = self.numbuf.parse() { self.tok = DeJsonTok::F64(num); - return Ok(()); + Ok(()) } else { - return Err(self.err_parse("number")); + Err(self.err_parse("number")) } } else { if is_neg { @@ -550,9 +545,9 @@ impl DeJsonState { } if let Ok(num) = self.numbuf.parse() { self.tok = DeJsonTok::U64(num); - return Ok(()); + Ok(()) } else { - return Err(self.err_parse("number")); + Err(self.err_parse("number")) } } } @@ -578,10 +573,10 @@ impl DeJsonState { return Ok(()); } self.tok = DeJsonTok::BareIdent; - return Err(self.err_token(&format!( + Err(self.err_token(&format!( "Got ##{}## needed true, false, null", self.identbuf - ))); + ))) } '"' => { self.strbuf.truncate(0); @@ -620,11 +615,9 @@ impl DeJsonState { } self.next(i); self.tok = DeJsonTok::Str; - return Ok(()); - } - _ => { - return Err(self.err_token("tokenizer")); + Ok(()) } + _ => Err(self.err_token("tokenizer")), } } @@ -740,15 +733,15 @@ macro_rules! impl_ser_de_json_float { }; } -impl_ser_de_json_unsigned!(usize, core::u64::MAX); -impl_ser_de_json_unsigned!(u64, core::u64::MAX); -impl_ser_de_json_unsigned!(u32, core::u32::MAX); -impl_ser_de_json_unsigned!(u16, core::u16::MAX); -impl_ser_de_json_unsigned!(u8, core::u8::MAX); -impl_ser_de_json_signed!(i64, core::i64::MIN, core::i64::MAX); -impl_ser_de_json_signed!(i32, core::i32::MIN, core::i32::MAX); -impl_ser_de_json_signed!(i16, core::i16::MIN, core::i16::MAX); -impl_ser_de_json_signed!(i8, core::i8::MIN, core::i8::MAX); +impl_ser_de_json_unsigned!(usize, u64::MAX); +impl_ser_de_json_unsigned!(u64, u64::MAX); +impl_ser_de_json_unsigned!(u32, u32::MAX); +impl_ser_de_json_unsigned!(u16, u16::MAX); +impl_ser_de_json_unsigned!(u8, u8::MAX); +impl_ser_de_json_signed!(i64, i64::MIN, i64::MAX); +impl_ser_de_json_signed!(i32, i32::MIN, i32::MAX); +impl_ser_de_json_signed!(i16, i16::MIN, i16::MAX); +impl_ser_de_json_signed!(i8, i8::MIN, i8::MAX); impl_ser_de_json_float!(f64); impl_ser_de_json_float!(f32); @@ -857,7 +850,7 @@ where { fn ser_json(&self, d: usize, s: &mut SerJsonState) { s.out.push('['); - if self.len() > 0 { + if !self.is_empty() { let last = self.len() - 1; for (index, item) in self.iter().enumerate() { s.indent(d + 1); @@ -895,7 +888,7 @@ where { fn ser_json(&self, d: usize, s: &mut SerJsonState) { s.out.push('['); - if self.len() > 0 { + if !self.is_empty() { let last = self.len() - 1; for (index, item) in self.iter().enumerate() { s.indent(d + 1); @@ -933,7 +926,7 @@ where { fn ser_json(&self, d: usize, s: &mut SerJsonState) { s.out.push('['); - if self.len() > 0 { + if !self.is_empty() { let last = self.len() - 1; for (index, item) in self.iter().enumerate() { s.indent(d + 1); @@ -970,7 +963,7 @@ where { fn ser_json(&self, d: usize, s: &mut SerJsonState) { s.out.push('['); - if self.len() > 0 { + if !self.is_empty() { let last = self.len() - 1; for (index, item) in self.iter().enumerate() { s.indent(d + 1); @@ -1191,8 +1184,7 @@ where fn ser_json(&self, d: usize, s: &mut SerJsonState) { s.out.push('{'); let len = self.len(); - let mut index = 0; - for (k, v) in self { + for (index, (k, v)) in self.iter().enumerate() { s.indent(d + 1); k.ser_json(d + 1, s); s.out.push(':'); @@ -1200,7 +1192,6 @@ where if (index + 1) < len { s.conl(); } - index += 1; } s.indent(d); s.out.push('}'); @@ -1236,8 +1227,7 @@ where fn ser_json(&self, d: usize, s: &mut SerJsonState) { s.out.push('{'); let len = self.len(); - let mut index = 0; - for (k, v) in self { + for (index, (k, v)) in self.iter().enumerate() { s.indent(d + 1); k.ser_json(d + 1, s); s.out.push(':'); @@ -1245,7 +1235,6 @@ where if (index + 1) < len { s.conl(); } - index += 1; } s.indent(d); s.out.push('}'); diff --git a/src/serde_ron.rs b/src/serde_ron.rs index 2f6db47..a5e92fd 100644 --- a/src/serde_ron.rs +++ b/src/serde_ron.rs @@ -98,7 +98,7 @@ pub trait DeRon: Sized { } /// A RON parsed token. -#[derive(PartialEq, Debug)] +#[derive(PartialEq, Debug, Default)] pub enum DeRonTok { Ident, Str, @@ -115,16 +115,11 @@ pub enum DeRonTok { BlockOpen, BlockClose, Comma, + #[default] Bof, Eof, } -impl Default for DeRonTok { - fn default() -> Self { - DeRonTok::Bof - } -} - /// The internal state of a RON deserialization. #[derive(Default)] #[non_exhaustive] @@ -480,11 +475,7 @@ impl DeRonState { self.next(i); break; } - if self.cur == '*' { - last_star = true - } else { - last_star = false - } + last_star = self.cur == '*'; self.next(i); } } else { @@ -745,15 +736,15 @@ macro_rules! impl_ser_de_ron_float { }; } -impl_ser_de_ron_unsigned!(usize, core::u64::MAX); -impl_ser_de_ron_unsigned!(u64, core::u64::MAX); -impl_ser_de_ron_unsigned!(u32, core::u32::MAX); -impl_ser_de_ron_unsigned!(u16, core::u16::MAX); -impl_ser_de_ron_unsigned!(u8, core::u8::MAX); -impl_ser_de_ron_signed!(i64, core::i64::MIN, core::i64::MAX); -impl_ser_de_ron_signed!(i32, core::i32::MIN, core::i32::MAX); -impl_ser_de_ron_signed!(i16, core::i16::MIN, core::i16::MAX); -impl_ser_de_ron_signed!(i8, core::i8::MIN, core::i8::MAX); +impl_ser_de_ron_unsigned!(usize, u64::MAX); +impl_ser_de_ron_unsigned!(u64, u64::MAX); +impl_ser_de_ron_unsigned!(u32, u32::MAX); +impl_ser_de_ron_unsigned!(u16, u16::MAX); +impl_ser_de_ron_unsigned!(u8, u8::MAX); +impl_ser_de_ron_signed!(i64, i64::MIN, i64::MAX); +impl_ser_de_ron_signed!(i32, i32::MIN, i32::MAX); +impl_ser_de_ron_signed!(i16, i16::MIN, i16::MAX); +impl_ser_de_ron_signed!(i8, i8::MIN, i8::MAX); impl_ser_de_ron_float!(f64); impl_ser_de_ron_float!(f32); @@ -799,7 +790,7 @@ impl DeRon for bool { fn de_ron(s: &mut DeRonState, i: &mut Chars) -> Result { let val = s.as_bool()?; s.next_tok(i)?; - return Ok(val); + Ok(val) } } @@ -843,7 +834,7 @@ impl DeRon for String { fn de_ron(s: &mut DeRonState, i: &mut Chars) -> Result { let val = s.as_string()?; s.next_tok(i)?; - return Ok(val); + Ok(val) } } @@ -887,7 +878,7 @@ where { fn ser_ron(&self, d: usize, s: &mut SerRonState) { s.out.push('['); - if self.len() > 0 { + if !self.is_empty() { let last = self.len() - 1; for (index, item) in self.iter().enumerate() { s.indent(d + 1); @@ -925,7 +916,7 @@ where { fn ser_ron(&self, d: usize, s: &mut SerRonState) { s.out.push('['); - if self.len() > 0 { + if !self.is_empty() { let last = self.len() - 1; for (index, item) in self.iter().enumerate() { s.indent(d + 1); @@ -962,7 +953,7 @@ where { fn ser_ron(&self, d: usize, s: &mut SerRonState) { s.out.push('['); - if self.len() > 0 { + if !self.is_empty() { let last = self.len() - 1; for (index, item) in self.iter().enumerate() { s.indent(d + 1); @@ -1199,7 +1190,7 @@ where for (k, v) in self { s.indent(d + 1); k.ser_ron(d + 1, s); - s.out.push_str(":"); + s.out.push(':'); v.ser_ron(d + 1, s); s.conl(); } @@ -1239,7 +1230,7 @@ where for (k, v) in self { s.indent(d + 1); k.ser_ron(d + 1, s); - s.out.push_str(":"); + s.out.push(':'); v.ser_ron(d + 1, s); s.conl(); } diff --git a/src/toml.rs b/src/toml.rs index f928778..731ceed 100644 --- a/src/toml.rs +++ b/src/toml.rs @@ -340,6 +340,7 @@ impl TomlParser { Ok(true) } + #[allow(clippy::wrong_self_convention)] fn to_val(&mut self, tok: TomlTok, i: &mut Chars) -> Result { match tok { TomlTok::BlockOpen => { @@ -360,12 +361,8 @@ impl TomlParser { TomlTok::I64(v) => Ok(Toml::Num(v as f64)), TomlTok::F64(v) => Ok(Toml::Num(v)), TomlTok::Bool(v) => Ok(Toml::Bool(v)), - TomlTok::Nan(v) => Ok(Toml::Num(if v { -core::f64::NAN } else { core::f64::NAN })), - TomlTok::Inf(v) => Ok(Toml::Num(if v { - -core::f64::INFINITY - } else { - core::f64::INFINITY - })), + TomlTok::Nan(v) => Ok(Toml::Num(if v { -f64::NAN } else { f64::NAN })), + TomlTok::Inf(v) => Ok(Toml::Num(if v { -f64::INFINITY } else { f64::INFINITY })), TomlTok::Date(v) => Ok(Toml::Date(v)), _ => Err(self.err_token(tok)), } @@ -474,7 +471,7 @@ impl TomlParser { } let escaped_string = braces == 3; loop { - if self.cur == '"' && escaped_string == false { + if self.cur == '"' && !escaped_string { break; } if self.cur == '"' && escaped_string {