diff --git a/cargo-typify/src/main.rs b/cargo-typify/src/main.rs index 85f482a0..0012c551 100644 --- a/cargo-typify/src/main.rs +++ b/cargo-typify/src/main.rs @@ -28,7 +28,7 @@ fn main() -> Result<()> { format!("Failed to write output to file: {}", output_path.display()) })?; } else { - print!("{}", contents); + print!("{contents}"); } Ok(()) diff --git a/cargo-typify/tests/integration.rs b/cargo-typify/tests/integration.rs index 46028107..7b1c28c8 100644 --- a/cargo-typify/tests/integration.rs +++ b/cargo-typify/tests/integration.rs @@ -4,8 +4,6 @@ use tempdir::TempDir; #[test] fn test_simple() { - use assert_cmd::Command; - let input = concat!(env!("CARGO_MANIFEST_DIR"), "/../example.json"); let temp = TempDir::new("cargo-typify").unwrap(); @@ -14,7 +12,7 @@ fn test_simple() { let output_file = temp.path().join("simple.rs"); - let mut cmd = Command::cargo_bin("cargo-typify").unwrap(); + let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("cargo-typify"); cmd.args(["typify", input_file.to_str().unwrap()]) .assert() .success(); @@ -26,14 +24,12 @@ fn test_simple() { #[test] fn test_default_output() { - use assert_cmd::Command; - let input = concat!(env!("CARGO_MANIFEST_DIR"), "/../example.json"); let temp = TempDir::new("cargo-typify").unwrap(); let output_file = temp.path().join("output.rs"); - let mut cmd = Command::cargo_bin("cargo-typify").unwrap(); + let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("cargo-typify"); cmd.args(["typify", input, "--output", output_file.to_str().unwrap()]) .assert() .success(); @@ -45,11 +41,9 @@ fn test_default_output() { #[test] fn test_no_builder_stdout() { - use assert_cmd::Command; - let input = concat!(env!("CARGO_MANIFEST_DIR"), "/../example.json"); - let mut cmd = Command::cargo_bin("cargo-typify").unwrap(); + let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("cargo-typify"); let output = cmd .args(["typify", input, "--no-builder", "--output", "-"]) @@ -65,14 +59,12 @@ fn test_no_builder_stdout() { #[test] fn test_builder() { - use assert_cmd::Command; - let input = concat!(env!("CARGO_MANIFEST_DIR"), "/../example.json"); let temp = TempDir::new("cargo-typify").unwrap(); let output_file = temp.path().join("output.rs"); - let mut cmd = Command::cargo_bin("cargo-typify").unwrap(); + let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("cargo-typify"); cmd.args([ "typify", input, @@ -90,14 +82,12 @@ fn test_builder() { #[test] fn test_derive() { - use assert_cmd::Command; - let input = concat!(env!("CARGO_MANIFEST_DIR"), "/../example.json"); let temp = TempDir::new("cargo-typify").unwrap(); let output_file = temp.path().join("output.rs"); - let mut cmd = Command::cargo_bin("cargo-typify").unwrap(); + let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("cargo-typify"); cmd.args([ "typify", input, @@ -117,14 +107,12 @@ fn test_derive() { #[test] fn test_multi_derive() { - use assert_cmd::Command; - let input = concat!(env!("CARGO_MANIFEST_DIR"), "/../example.json"); let temp = TempDir::new("cargo-typify").unwrap(); let output_file = temp.path().join("output.rs"); - let mut cmd = Command::cargo_bin("cargo-typify").unwrap(); + let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("cargo-typify"); cmd.args([ "typify", input, @@ -146,9 +134,7 @@ fn test_multi_derive() { #[test] fn test_help() { - use assert_cmd::Command; - - let mut cmd = Command::cargo_bin("cargo-typify").unwrap(); + let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("cargo-typify"); let output = cmd.args(["typify", "--help"]).output().unwrap(); @@ -161,14 +147,12 @@ fn test_help() { #[test] fn test_btree_map() { - use assert_cmd::Command; - let input = concat!(env!("CARGO_MANIFEST_DIR"), "/../example.json"); let temp = TempDir::new("cargo-typify").unwrap(); let output_file = temp.path().join("output.rs"); - let mut cmd = Command::cargo_bin("cargo-typify").unwrap(); + let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("cargo-typify"); cmd.args([ "typify", input, diff --git a/example-build/src/main.rs b/example-build/src/main.rs index 817bb0a7..015a7914 100644 --- a/example-build/src/main.rs +++ b/example-build/src/main.rs @@ -7,7 +7,7 @@ include!(concat!(env!("OUT_DIR"), "/codegen.rs")); #[test] fn test_main() { - main() + main(); } fn main() { @@ -21,5 +21,5 @@ fn main() { fruits: vec![String::from("apple"), String::from("mango")], vegetables: vec![veg], }; - println!("{:?}", veggies); + println!("{veggies:?}"); } diff --git a/example-macro/src/main.rs b/example-macro/src/main.rs index 5da004b6..6b140952 100644 --- a/example-macro/src/main.rs +++ b/example-macro/src/main.rs @@ -23,7 +23,7 @@ import_types!( #[test] fn test_main() { - main() + main(); } fn main() { @@ -35,7 +35,7 @@ fn main() { fruits: vec![String::from("apple"), String::from("mango")], vegetables: vec![veg], }; - println!("{:?}", veggies); + println!("{veggies:?}"); let fov = FruitOrVeg::Fruit(MyFruit { seeds: () }); - println!("{:?}", fov); + println!("{fov:?}"); } diff --git a/typify-impl/src/convert.rs b/typify-impl/src/convert.rs index 22395eef..267f4efe 100644 --- a/typify-impl/src/convert.rs +++ b/typify-impl/src/convert.rs @@ -96,7 +96,7 @@ impl TypeSpace { // new name for the inner type; otherwise, the inner type // can just have this name. let inner_type_name = match &type_name { - Name::Required(name) => Name::Suggested(format!("{}Inner", name)), + Name::Required(name) => Name::Suggested(format!("{name}Inner")), _ => type_name, }; self.convert_option(inner_type_name, metadata, &ss) @@ -807,7 +807,7 @@ impl TypeSpace { if let Some(pattern) = &validation.pattern { let _ = regress::Regex::new(pattern).map_err(|e| Error::InvalidSchema { type_name: type_name.clone().into_option(), - reason: format!("invalid pattern '{}' {}", pattern, e), + reason: format!("invalid pattern '{pattern}' {e}"), })?; self.uses_regress = true; } @@ -883,7 +883,7 @@ impl TypeSpace { )), Some(unhandled) => { - info!("treating a string format '{}' as a String", unhandled); + info!("treating a string format '{unhandled}' as a String"); Ok((TypeEntryDetails::String.into(), metadata)) } } @@ -1088,9 +1088,8 @@ impl TypeSpace { // Use NonZero types for minimum 1 if min == Some(1.) { return Ok((TypeEntry::new_integer(nz_ty), metadata)); - } else { - return Ok((TypeEntry::new_integer(ty), metadata)); } + return Ok((TypeEntry::new_integer(ty), metadata)); } if min.is_none() { @@ -1342,13 +1341,13 @@ impl TypeSpace { ref_name: &str, ) -> Result<(TypeEntry, &'a Option>)> { if !ref_name.starts_with('#') { - panic!("external references are not supported: {}", ref_name); + panic!("external references are not supported: {ref_name}"); } let key = ref_key(ref_name); let type_id = self .ref_to_id .get(&key) - .unwrap_or_else(|| panic!("$ref {} is missing", ref_name)); + .unwrap_or_else(|| panic!("$ref {ref_name} is missing")); Ok(( TypeEntryDetails::Reference(type_id.clone()).into(), metadata, @@ -1701,7 +1700,7 @@ impl TypeSpace { serde_json::Value::Null | serde_json::Value::Array(_) | serde_json::Value::Object(_) => { - panic!("unhandled type for `not` construction: {}", v) + panic!("unhandled type for `not` construction: {v}") } }) .collect::>(); @@ -1742,8 +1741,7 @@ impl TypeSpace { } _ => panic!( - "multiple implied types for an un-typed enum {:?} {:?}", - instance_types, enum_values, + "multiple implied types for an un-typed enum {instance_types:?} {enum_values:?}", ), } } @@ -1780,7 +1778,7 @@ impl TypeSpace { self.id_for_schema(rest_name, &Schema::Bool(true))?.0 }; let start = items.iter().enumerate().map(|(ii, item_schema)| { - let item_name = type_name.append(&format!("item{}", ii)); + let item_name = type_name.append(&format!("item{ii}")); Ok(self.id_for_schema(item_name, item_schema)?.0) }); let rest = (items.len()..*max_items as usize).map(|_| Ok(rest_id.clone())); @@ -1794,7 +1792,7 @@ impl TypeSpace { .take(*max_items as usize) .enumerate() .map(|(ii, item_schema)| { - let item_name = type_name.append(&format!("item{}", ii)); + let item_name = type_name.append(&format!("item{ii}")); Ok(self.id_for_schema(item_name, item_schema)?.0) }) .collect::>()?; @@ -1831,7 +1829,7 @@ impl TypeSpace { contains: None, } => { let item_type_name = match get_type_name(&type_name, metadata) { - Some(s) => Name::Suggested(format!("{}Item", s)), + Some(s) => Name::Suggested(format!("{s}Item")), None => Name::Unknown, }; let (type_id, _) = self.id_for_schema(item_type_name, item.as_ref())?; @@ -1864,7 +1862,7 @@ impl TypeSpace { _ => Err(Error::InvalidSchema { type_name: type_name.into_option(), - reason: format!("unhandled array validation {:#?}", validation), + reason: format!("unhandled array validation {validation:#?}"), }), } } @@ -1924,7 +1922,7 @@ impl TypeSpace { }; let inner_type_name = match get_type_name(&type_name, &schema.metadata) { - Some(s) => Name::Suggested(format!("{}Inner", s)), + Some(s) => Name::Suggested(format!("{s}Inner")), None => Name::Unknown, }; @@ -2042,8 +2040,7 @@ impl TypeSpace { } (1, None) => unreachable!(), _ => panic!( - "multiple implied types for an un-typed enum {:?} {:?}", - instance_types, enum_values, + "multiple implied types for an un-typed enum {instance_types:?} {enum_values:?}", ), } } diff --git a/typify-impl/src/defaults.rs b/typify-impl/src/defaults.rs index c20f033e..230b2408 100644 --- a/typify-impl/src/defaults.rs +++ b/typify-impl/src/defaults.rs @@ -339,12 +339,12 @@ impl TypeEntry { TypeEntryDetails::Integer(name) => { if let Some(value) = default.as_u64() { if name.starts_with(STD_NUM_NONZERO_PREFIX) { - Some(format!("defaults::default_nzu64::<{}, {}>", name, value)) + Some(format!("defaults::default_nzu64::<{name}, {value}>")) } else { - Some(format!("defaults::default_u64::<{}, {}>", name, value)) + Some(format!("defaults::default_u64::<{name}, {value}>")) } } else if let Some(value) = default.as_i64() { - Some(format!("defaults::default_i64::<{}, {}>", name, value)) + Some(format!("defaults::default_i64::<{name}, {value}>")) } else { panic!() } @@ -366,14 +366,14 @@ impl TypeEntry { self, ) }); - let fn_name = sanitize(&format!("{}_{}", type_name, prop_name), Case::Snake); + let fn_name = sanitize(&format!("{type_name}_{prop_name}"), Case::Snake); let fn_ident = format_ident!("{}", fn_name); let def = quote! { pub(super) fn #fn_ident() -> #n { #value } }; - (format!("defaults::{}", fn_name), Some(def)) + (format!("defaults::{fn_name}"), Some(def)) } } } diff --git a/typify-impl/src/enums.rs b/typify-impl/src/enums.rs index 9ec58297..66f1a0fd 100644 --- a/typify-impl/src/enums.rs +++ b/typify-impl/src/enums.rs @@ -640,7 +640,7 @@ impl TypeSpace { // Fall back to `VariantN` naming. .unwrap_or_else(|| { (0..subschemas.len()) - .map(|idx| format!("Variant{}", idx)) + .map(|idx| format!("Variant{idx}")) .collect() }); @@ -1253,7 +1253,7 @@ mod tests { .maybe_option(Name::Unknown, &None, &subschemas) .unwrap(); - assert_eq!(type_entry.details, TypeEntryDetails::Option(TypeId(1))) + assert_eq!(type_entry.details, TypeEntryDetails::Option(TypeId(1))); } #[test] @@ -1346,11 +1346,11 @@ mod tests { .unwrap() .ends_with(variant.ident_name.as_ref().unwrap())); } - _ => panic!("{:#?}", type_entry), + _ => panic!("{type_entry:#?}"), } } } - _ => panic!("{:#?}", type_entry), + _ => panic!("{type_entry:#?}"), } } @@ -1435,7 +1435,7 @@ mod tests { tag_type: EnumTagType::Untagged, .. }) => {} - _ => panic!("{:#?}", type_entry), + _ => panic!("{type_entry:#?}"), } } diff --git a/typify-impl/src/lib.rs b/typify-impl/src/lib.rs index 2f791ba2..48a3a392 100644 --- a/typify-impl/src/lib.rs +++ b/typify-impl/src/lib.rs @@ -154,17 +154,17 @@ pub(crate) enum Name { impl Name { pub fn into_option(self) -> Option { match self { - Name::Required(s) | Name::Suggested(s) => Some(s), - Name::Unknown => None, + Self::Required(s) | Self::Suggested(s) => Some(s), + Self::Unknown => None, } } pub fn append(&self, s: &str) -> Self { match self { - Name::Required(prefix) | Name::Suggested(prefix) => { - Self::Suggested(format!("{}_{}", prefix, s)) + Self::Required(prefix) | Self::Suggested(prefix) => { + Self::Suggested(format!("{prefix}_{s}")) } - Name::Unknown => Name::Unknown, + Self::Unknown => Self::Unknown, } } } @@ -402,7 +402,7 @@ impl std::str::FromStr for TypeSpaceImpl { "FromStr" => Ok(Self::FromStr), "Display" => Ok(Self::Display), "Default" => Ok(Self::Default), - _ => Err(format!("{} is not a valid trait specifier", s)), + _ => Err(format!("{s} is not a valid trait specifier")), } } } @@ -657,7 +657,7 @@ impl TypeSpace { } else { Name::Unknown }; - self.convert_ref_type(type_name, schema, type_id)? + self.convert_ref_type(type_name, schema, type_id)?; } Some(replace_type) => { @@ -1002,7 +1002,7 @@ impl TypeSpace { impl ToTokens for TypeSpace { fn to_tokens(&self, tokens: &mut TokenStream) { - tokens.extend(self.to_stream()) + tokens.extend(self.to_stream()); } } @@ -1256,7 +1256,7 @@ mod tests { #[test] fn test_simple() { let schema = schema_for!(Foo); - println!("{:#?}", schema); + println!("{schema:#?}"); let mut type_space = TypeSpace::default(); type_space.add_ref_types(schema.definitions).unwrap(); let (ty, _) = type_space @@ -1267,14 +1267,14 @@ mod tests { ) .unwrap(); - println!("{:#?}", ty); + println!("{ty:#?}"); let mut output = OutputSpace::default(); ty.output(&type_space, &mut output); println!("{}", output.into_stream()); for ty in type_space.id_to_entry.values() { - println!("{:#?}", ty); + println!("{ty:#?}"); let mut output = OutputSpace::default(); ty.output(&type_space, &mut output); println!("{}", output.into_stream()); @@ -1301,14 +1301,14 @@ mod tests { } }); let schema = serde_json::from_value(schema).unwrap(); - println!("{:#?}", schema); + println!("{schema:#?}"); let settings = TypeSpaceSettings::default(); let mut type_space = TypeSpace::new(&settings); type_space.add_root_schema(schema).unwrap(); let tokens = type_space.to_stream().to_string(); - println!("{}", tokens); + println!("{tokens}"); assert!(tokens - .contains(" pub struct Somename { pub someproperty : :: std :: string :: String , }")) + .contains(" pub struct Somename { pub someproperty : :: std :: string :: String , }")); } #[test] @@ -1323,7 +1323,7 @@ mod tests { } let schema = schema_for!(SimpleEnum); - println!("{:#?}", schema); + println!("{schema:#?}"); let mut type_space = TypeSpace::default(); type_space.add_ref_types(schema.definitions).unwrap(); @@ -1401,10 +1401,10 @@ mod tests { .collect::>() ); } else { - panic!("not the sub-type we expected {:#?}", te) + panic!("not the sub-type we expected {te:#?}") } } else { - panic!("not the type we expected {:#?}", te) + panic!("not the type we expected {te:#?}") } } diff --git a/typify-impl/src/merge.rs b/typify-impl/src/merge.rs index 8e9104de..3b27fc1f 100644 --- a/typify-impl/src/merge.rs +++ b/typify-impl/src/merge.rs @@ -122,7 +122,7 @@ fn try_merge_schema(a: &Schema, b: &Schema, defs: &BTreeMap) -> let key = ref_key(ref_name); let resolved = defs .get(&key) - .unwrap_or_else(|| panic!("unresolved reference: {}", ref_name)); + .unwrap_or_else(|| panic!("unresolved reference: {ref_name}")); let merged_schema = try_merge_schema(resolved, other, defs)?; // If we merge a referenced schema with another schema **and** @@ -429,7 +429,7 @@ fn merge_schema_not( (Schema::Object(schema_object), any_not) => { match try_merge_schema_not(schema_object.clone(), any_not, defs) { Ok(schema_obj) => Schema::Object(schema_obj), - Err(_) => Schema::Bool(false), + Err(()) => Schema::Bool(false), } } } @@ -544,7 +544,7 @@ fn try_merge_with_subschemas_not( else_schema: None, } => match try_merge_all(all_of, defs) { Ok(merged_not_schema) => try_merge_schema_not(schema_object, &merged_not_schema, defs), - Err(_) => Ok(schema_object), + Err(()) => Ok(schema_object), }, _ => todo!( @@ -671,8 +671,8 @@ fn merge_so_instance_type( .iter() .collect::>() .intersection(&bb.iter().collect::>()) - .cloned() - .cloned() + .copied() + .copied() .collect::>(); match types.len() { @@ -701,10 +701,8 @@ fn merge_so_format(a: Option<&String>, b: Option<&String>) -> Result Ok(other.map(String::from)), - (Some("ip"), result @ Some("ipv4")) - | (Some("ip"), result @ Some("ipv6")) - | (result @ Some("ipv4"), Some("ip")) - | (result @ Some("ipv6"), Some("ip")) => Ok(result.map(String::from)), + (Some("ip"), result @ Some("ipv4" | "ipv6")) + | (result @ Some("ipv4" | "ipv6"), Some("ip")) => Ok(result.map(String::from)), // Fine if they're both the same (Some(aa), Some(bb)) if aa == bb => Ok(Some(aa.into())), @@ -939,22 +937,19 @@ fn merge_items_array<'a>( ) -> Result<(Vec, bool), ()> { let mut items = Vec::new(); for (a, b) in items_iter { - match try_merge_schema(a, b, defs) { - Ok(schema) => { - items.push(schema); - if let Some(max) = max_items { - if items.len() == max as usize { - return Ok((items, false)); - } + if let Ok(schema) = try_merge_schema(a, b, defs) { + items.push(schema); + if let Some(max) = max_items { + if items.len() == max as usize { + return Ok((items, false)); } } - Err(_) => { - let len = items.len() as u32; - if len < min_items.unwrap_or(1) { - return Err(()); - } - return Ok((items, false)); + } else { + let len = items.len() as u32; + if len < min_items.unwrap_or(1) { + return Err(()); } + return Ok((items, false)); } } @@ -1131,29 +1126,30 @@ trait Roughly { impl Roughly for schemars::schema::Schema { fn roughly(&self, other: &Self) -> bool { match (self, other) { - (Schema::Bool(a), Schema::Bool(b)) => a == b, - (Schema::Bool(false), _) | (_, Schema::Bool(false)) => false, - - (Schema::Bool(true), Schema::Object(other)) - | (Schema::Object(other), Schema::Bool(true)) => matches!( - other, - SchemaObject { - metadata: _, - instance_type: None, - format: None, - enum_values: None, - const_value: None, - subschemas: None, - number: None, - string: None, - array: None, - object: None, - reference: None, - extensions: _, - } - ), + (Self::Bool(a), Self::Bool(b)) => a == b, + (Self::Bool(false), _) | (_, Self::Bool(false)) => false, + + (Self::Bool(true), Self::Object(other)) | (Self::Object(other), Self::Bool(true)) => { + matches!( + other, + SchemaObject { + metadata: _, + instance_type: None, + format: None, + enum_values: None, + const_value: None, + subschemas: None, + number: None, + string: None, + array: None, + object: None, + reference: None, + extensions: _, + } + ) + } - (Schema::Object(a), Schema::Object(b)) => { + (Self::Object(a), Self::Object(b)) => { a.instance_type == b.instance_type && a.format == b.format && a.enum_values == b.enum_values @@ -1230,8 +1226,7 @@ fn roughly_array(a: Option<&ArrayValidation>, b: Option<&ArrayValidation>) -> bo fn roughly_object(a: Option<&ObjectValidation>, b: Option<&ObjectValidation>) -> bool { match (a, b) { (None, None) => true, - (None, Some(_)) => false, - (Some(_), None) => false, + (None, Some(_)) | (Some(_), None) => false, (Some(aa), Some(bb)) => { aa.max_properties == bb.max_properties && aa.min_properties == bb.min_properties @@ -1640,7 +1635,7 @@ mod tests { ab, "{}", serde_json::to_string_pretty(&merged).unwrap(), - ) + ); } #[test] @@ -1683,7 +1678,7 @@ mod tests { ab, "{}", serde_json::to_string_pretty(&merged).unwrap(), - ) + ); } #[test] @@ -1725,7 +1720,7 @@ mod tests { ab, "{}", serde_json::to_string_pretty(&merged).unwrap(), - ) + ); } #[test] @@ -1766,7 +1761,7 @@ mod tests { ab, "{}", serde_json::to_string_pretty(&merged).unwrap(), - ) + ); } #[test] @@ -1822,6 +1817,6 @@ mod tests { ab, "{}", serde_json::to_string_pretty(&merged).unwrap(), - ) + ); } } diff --git a/typify-impl/src/structs.rs b/typify-impl/src/structs.rs index 4e285259..68083ea7 100644 --- a/typify-impl/src/structs.rs +++ b/typify-impl/src/structs.rs @@ -96,7 +96,7 @@ impl TypeSpace { // #[serde(flatten)] so we allow them even though that doesn't seem // quite right. additional_properties @ Some(_) => { - let sub_type_name = type_name.as_ref().map(|base| format!("{}_extra", base)); + let sub_type_name = type_name.as_ref().map(|base| format!("{base}_extra")); let map_type = self.make_map( sub_type_name, &validation.property_names, @@ -197,7 +197,7 @@ impl TypeSpace { Some(Schema::Object(obj)) => { let key_type_name = match &type_name { - Some(name) => Name::Suggested(format!("{}Key", name)), + Some(name) => Name::Suggested(format!("{name}Key")), None => Name::Unknown, }; self.id_for_schema_string(key_type_name, obj)? @@ -207,7 +207,7 @@ impl TypeSpace { let (value_id, _) = match additional_properties { Some(value_schema) => { let value_type_name = match &type_name { - Some(name) => Name::Suggested(format!("{}Value", name)), + Some(name) => Name::Suggested(format!("{name}Value")), None => Name::Unknown, }; self.id_for_schema(value_type_name, value_schema)? @@ -225,28 +225,25 @@ impl TypeSpace { type_name: Name, schema_obj: &SchemaObject, ) -> Result { - match schema_obj { + if let SchemaObject { + instance_type: None, + subschemas: None, + reference: None, + .. + } = schema_obj + { // If the schema has no subschemas or references, fill in the // string instance_type if none is present. - SchemaObject { - instance_type: None, - subschemas: None, - reference: None, - .. - } => { - let schema = Schema::Object(SchemaObject { - instance_type: Some(InstanceType::String.into()), - ..schema_obj.clone() - }); - Ok(self.id_for_schema(type_name, &schema)?.0) - } - + let schema = Schema::Object(SchemaObject { + instance_type: Some(InstanceType::String.into()), + ..schema_obj.clone() + }); + Ok(self.id_for_schema(type_name, &schema)?.0) + } else { // TODO if and when we perform merging of schemas we could wrap the // schema in an { allOf: [{ type: string }, ] } - _ => { - let schema = Schema::Object(schema_obj.clone()); - Ok(self.id_for_schema(type_name, &schema)?.0) - } + let schema = Schema::Object(schema_obj.clone()); + Ok(self.id_for_schema(type_name, &schema)?.0) } } @@ -278,7 +275,7 @@ impl TypeSpace { .enumerate() .map(|(idx, schema)| { let type_name = match get_type_name(&type_name, metadata) { - Some(name) => Name::Suggested(format!("{}Subtype{}", name, idx)), + Some(name) => Name::Suggested(format!("{name}Subtype{idx}")), None => Name::Unknown, }; @@ -289,7 +286,7 @@ impl TypeSpace { // TODO we need a reasonable name that could be derived // from the name of the type - let name = format!("subtype_{}", idx); + let name = format!("subtype_{idx}"); Ok(StructProperty { name, @@ -380,7 +377,7 @@ pub(crate) fn generate_serde_attr( skip_serializing_if = "::serde_json::Map::is_empty" }); } else { - let is_empty = format!("{}::is_empty", map_to_use); + let is_empty = format!("{map_to_use}::is_empty"); serde_options.push(quote! { skip_serializing_if = #is_empty }); @@ -437,10 +434,15 @@ fn has_default( default, ) { // No default specified. - (Some(TypeEntryDetails::Option(_)), None) => StructPropertyState::Optional, - (Some(TypeEntryDetails::Vec(_)), None) => StructPropertyState::Optional, - (Some(TypeEntryDetails::Map(..)), None) => StructPropertyState::Optional, - (Some(TypeEntryDetails::Unit), None) => StructPropertyState::Optional, + ( + Some( + TypeEntryDetails::Option(_) + | TypeEntryDetails::Vec(_) + | TypeEntryDetails::Map(..) + | TypeEntryDetails::Unit, + ), + None, + ) => StructPropertyState::Optional, (_, None) => StructPropertyState::Required, // Default specified is the same as the implicit default: null diff --git a/typify-impl/src/test_util.rs b/typify-impl/src/test_util.rs index bbc2fd46..c9044c35 100644 --- a/typify-impl/src/test_util.rs +++ b/typify-impl/src/test_util.rs @@ -52,14 +52,14 @@ pub(crate) fn get_type() -> (TypeSpace, TypeId) { /// Ingest a type, spit it back out, and make sure it matches where we started. #[track_caller] pub(crate) fn validate_output() { - validate_output_impl::(false) + validate_output_impl::(false); } /// Same as `validate_output` but ignores differences of the top-level enum's /// variant names which are lost in the case of `#[serde(untagged)]` #[track_caller] pub(crate) fn validate_output_for_untagged_enm() { - validate_output_impl::(true) + validate_output_impl::(true); } #[track_caller] @@ -171,8 +171,7 @@ fn compare_attributes(attrs_a: &[Attribute], attrs_b: &[Attribute]) -> Result<() Ok(()) } else { Err(format!( - "different serde options: {:?} {:?}", - serde_options_a, serde_options_b + "different serde options: {serde_options_a:?} {serde_options_b:?}" )) } } @@ -221,7 +220,7 @@ fn get_serde(attrs: &[Attribute]) -> HashSet { impl SynCompare for syn::Ident { fn syn_cmp(&self, other: &Self, _: bool) -> Result<(), String> { if self != other { - Err(format!("idents differ: {} {}", self, other)) + Err(format!("idents differ: {self} {other}")) } else { Ok(()) } @@ -283,9 +282,9 @@ impl SynCompare for Variant { impl SynCompare for Fields { fn syn_cmp(&self, other: &Self, _: bool) -> Result<(), String> { match (self, other) { - (Fields::Named(a), Fields::Named(b)) => a.syn_cmp(b, false), - (Fields::Unnamed(a), Fields::Unnamed(b)) => a.syn_cmp(b, false), - (Fields::Unit, Fields::Unit) => Ok(()), + (Self::Named(a), Self::Named(b)) => a.syn_cmp(b, false), + (Self::Unnamed(a), Self::Unnamed(b)) => a.syn_cmp(b, false), + (Self::Unit, Self::Unit) => Ok(()), _ => Err("mismatched field types".to_string()), } } @@ -314,11 +313,10 @@ impl SynCompare for Field { impl SynCompare for Type { fn syn_cmp(&self, other: &Self, _: bool) -> Result<(), String> { match (self, other) { - (Type::Tuple(a), Type::Tuple(b)) => a.syn_cmp(b, false), - (Type::Path(a), Type::Path(b)) => a.syn_cmp(b, false), + (Self::Tuple(a), Self::Tuple(b)) => a.syn_cmp(b, false), + (Self::Path(a), Self::Path(b)) => a.syn_cmp(b, false), _ => Err(format!( - "unexpected or mismatched type pair: {:?} {:?}", - self, other + "unexpected or mismatched type pair: {self:?} {other:?}" )), } } diff --git a/typify-impl/src/type_entry.rs b/typify-impl/src/type_entry.rs index 913e78bf..e4c60a2a 100644 --- a/typify-impl/src/type_entry.rs +++ b/typify-impl/src/type_entry.rs @@ -248,15 +248,15 @@ impl TypeEntryEnum { ) -> TypeEntry { // Let's find some decent names for variants. We first try the simple // sanitization. - variants.iter_mut().for_each(|variant| { + for variant in &mut variants { let ident_name = sanitize(&variant.raw_name, Case::Pascal); variant.ident_name = Some(ident_name); - }); + } // If variants aren't unique, we're turn the elided characters into // 'x's. if !variants_unique(&variants) { - variants.iter_mut().for_each(|variant| { + for variant in &mut variants { let ident_name = sanitize( &variant .raw_name @@ -264,26 +264,26 @@ impl TypeEntryEnum { Case::Pascal, ); variant.ident_name = Some(ident_name); - }); + } } // If variants still aren't unique, we fail: we'd rather not emit code // that can't compile if !variants_unique(&variants) { let mut counts = HashMap::new(); - variants.iter().for_each(|variant| { + for variant in &variants { counts .entry(variant.ident_name.as_ref().unwrap()) .and_modify(|xxx| *xxx += 1) .or_insert(0); - }); + } let dups = variants .iter() .filter(|variant| *counts.get(variant.ident_name.as_ref().unwrap()).unwrap() > 0) .map(|variant| variant.raw_name.as_str()) .collect::>() .join(","); - panic!("Failed to make unique variant names for [{}]", dups); + panic!("Failed to make unique variant names for [{dups}]"); } let name = get_type_name(&type_name, metadata).unwrap(); @@ -546,7 +546,7 @@ impl From for TypeEntry { impl TypeEntry { pub(crate) fn new_native(type_name: S, impls: &[TypeSpaceImpl]) -> Self { - TypeEntry { + Self { details: TypeEntryDetails::Native(TypeEntryNative { type_name: type_name.to_string(), impls: impls.to_vec(), @@ -556,7 +556,7 @@ impl TypeEntry { } } pub(crate) fn new_native_params(type_name: S, params: &[TypeId]) -> Self { - TypeEntry { + Self { details: TypeEntryDetails::Native(TypeEntryNative { type_name: type_name.to_string(), impls: Default::default(), @@ -566,7 +566,7 @@ impl TypeEntry { } } pub(crate) fn new_boolean() -> Self { - TypeEntry { + Self { details: TypeEntryDetails::Boolean, extra_derives: Default::default(), } @@ -575,7 +575,7 @@ impl TypeEntry { TypeEntryDetails::Integer(type_name.to_string()).into() } pub(crate) fn new_float(type_name: S) -> Self { - TypeEntry { + Self { details: TypeEntryDetails::Float(type_name.to_string()), extra_derives: Default::default(), } @@ -733,13 +733,13 @@ impl TypeEntry { match &self.details { TypeEntryDetails::Enum(enum_details) => { - self.output_enum(type_space, output, enum_details, derive_set) + self.output_enum(type_space, output, enum_details, derive_set); } TypeEntryDetails::Struct(struct_details) => { - self.output_struct(type_space, output, struct_details, derive_set) + self.output_struct(type_space, output, struct_details, derive_set); } TypeEntryDetails::Newtype(newtype_details) => { - self.output_newtype(type_space, output, newtype_details, derive_set) + self.output_newtype(type_space, output, newtype_details, derive_set); } // We should never get here as reference types should only be used @@ -822,7 +822,7 @@ impl TypeEntry { .filter(|variant| matches!(variant.details, VariantDetails::Simple)) .count() <= 1 - ) + ); } // Display and FromStr impls for enums that are made exclusively of @@ -1039,12 +1039,12 @@ impl TypeEntry { .unwrap() .type_ident(type_space, &None) }); - let variant_type_ident = if type_ids.len() != 1 { - quote! { ( #(#variant_type_idents),* ) } - } else { + let variant_type_ident = if type_ids.len() == 1 { // A single-item tuple requires a trailing // comma. quote! { ( #(#variant_type_idents,)* ) } + } else { + quote! { ( #(#variant_type_idents),* ) } }; let variant_name = format_ident!("{}", variant.ident_name.as_ref().unwrap()); @@ -1252,7 +1252,7 @@ impl TypeEntry { } } }, - ) + ); } if type_space.settings.struct_builder { @@ -1540,7 +1540,7 @@ impl TypeEntry { } => { let max = max_length.map(|v| { let v = v as usize; - let err = format!("longer than {} characters", v); + let err = format!("longer than {v} characters"); quote! { if value.chars().count() > #v { return Err(#err.into()); @@ -1549,7 +1549,7 @@ impl TypeEntry { }); let min = min_length.map(|v| { let v = v as usize; - let err = format!("shorter than {} characters", v); + let err = format!("shorter than {v} characters"); quote! { if value.chars().count() < #v { return Err(#err.into()); @@ -1558,7 +1558,7 @@ impl TypeEntry { }); let pat = pattern.as_ref().map(|p| { - let err = format!("doesn't match pattern \"{}\"", p); + let err = format!("doesn't match pattern \"{p}\""); quote! { static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| { ::regress::Regex::new(#p).unwrap() @@ -1941,8 +1941,8 @@ impl TypeEntry { pub(crate) fn describe(&self) -> String { match &self.details { - TypeEntryDetails::Enum(TypeEntryEnum { name, .. }) => format!("enum {}", name), - TypeEntryDetails::Struct(TypeEntryStruct { name, .. }) => format!("struct {}", name), + TypeEntryDetails::Enum(TypeEntryEnum { name, .. }) => format!("enum {name}"), + TypeEntryDetails::Struct(TypeEntryStruct { name, .. }) => format!("struct {name}"), TypeEntryDetails::Newtype(TypeEntryNewtype { name, type_id, .. }) => { format!("newtype {} {}", name, type_id.0) } @@ -1986,7 +1986,7 @@ impl TypeEntry { fn make_doc(name: &str, description: Option<&String>, schema: &Schema) -> TokenStream { let desc = match description { Some(desc) => desc, - None => &format!("`{}`", name), + None => &format!("`{name}`"), }; let schema_json = serde_json::to_string_pretty(schema).unwrap(); let schema_lines = schema_json.lines(); diff --git a/typify-impl/src/util.rs b/typify-impl/src/util.rs index 848ea5b6..f5f8ebc2 100644 --- a/typify-impl/src/util.rs +++ b/typify-impl/src/util.rs @@ -28,7 +28,7 @@ pub(crate) fn metadata_title_and_description(metadata: &Option>) - metadata .as_ref() .and_then(|metadata| match (&metadata.title, &metadata.description) { - (Some(t), Some(d)) => Some(format!("{}\n\n{}", t, d)), + (Some(t), Some(d)) => Some(format!("{t}\n\n{d}")), (Some(t), None) => Some(t.clone()), (None, Some(d)) => Some(d.clone()), (None, None) => None, @@ -550,7 +550,7 @@ pub(crate) fn ref_key(ref_name: &str) -> RefKey { } else if let Some(idx) = ref_name.rfind('/') { RefKey::Def(ref_name[idx + 1..].to_string()) } else { - panic!("expected a '/' in $ref: {}", ref_name) + panic!("expected a '/' in $ref: {ref_name}") } } @@ -788,14 +788,14 @@ pub(crate) fn sanitize(input: &str, case: Case) -> String { let out = match out.chars().next() { None => prefix, Some(c) if is_xid_start(c) => out, - Some(_) => format!("{}{}", prefix, out), + Some(_) => format!("{prefix}{out}"), }; // Make sure the string is a valid Rust identifier. if syn::parse_str::(&out).is_ok() { out } else { - format!("{}_", out) + format!("{out}_") } } @@ -862,7 +862,7 @@ impl StringValidator { .map(|pattern| { regress::Regex::new(pattern).map_err(|e| Error::InvalidSchema { type_name: type_name.clone().into_option(), - reason: format!("invalid pattern '{}' {}", pattern, e), + reason: format!("invalid pattern '{pattern}' {e}"), }) }) .transpose()?; diff --git a/typify-impl/src/validate.rs b/typify-impl/src/validate.rs index ea61f7ad..57ef7cf2 100644 --- a/typify-impl/src/validate.rs +++ b/typify-impl/src/validate.rs @@ -27,8 +27,7 @@ fn schema_object_value_validate( if let Some(const_value) = &object.const_value { if value != const_value { return Err(format!( - "{} does not match the const value {}", - value, const_value, + "{value} does not match the const value {const_value}", )); } } diff --git a/typify-impl/src/value.rs b/typify-impl/src/value.rs index 61f9f066..9e660e9a 100644 --- a/typify-impl/src/value.rs +++ b/typify-impl/src/value.rs @@ -171,11 +171,11 @@ impl TypeEntry { #type_path::new(#num).unwrap() } } else { - let val = - match proc_macro2::Literal::from_str(&format!("{}_{}", value, type_name)) { - Ok(v) => v, - Err(_) => unreachable!(), - }; + let val = match proc_macro2::Literal::from_str(&format!("{value}_{type_name}")) + { + Ok(v) => v, + Err(_) => unreachable!(), + }; TokenStream::from(proc_macro2::TokenTree::from(val)) } } diff --git a/typify-macro/src/lib.rs b/typify-macro/src/lib.rs index 29e4c128..3cddb542 100644 --- a/typify-macro/src/lib.rs +++ b/typify-macro/src/lib.rs @@ -284,6 +284,6 @@ mod tests { map_type = ::my::map::Type, }; - let MacroSettings { .. } = serde_tokenstream::from_tokenstream(&item.into()).unwrap(); + let MacroSettings { .. } = serde_tokenstream::from_tokenstream(&item).unwrap(); } }