diff --git a/compile_tests/compiler.rs b/compile_tests/compiler.rs index 0ad883e..41cb514 100644 --- a/compile_tests/compiler.rs +++ b/compile_tests/compiler.rs @@ -12,4 +12,5 @@ fn compile_tests() { if rustversion::cfg!(all(stable, since(1.68.0))) { t.compile_fail("compile_tests/no_display_no_impl.rs"); } + t.pass("compile_tests/skip_positional.rs"); } diff --git a/compile_tests/empty.rs b/compile_tests/empty.rs index 4a2e580..6d5c937 100644 --- a/compile_tests/empty.rs +++ b/compile_tests/empty.rs @@ -1,3 +1,5 @@ +#![allow(dead_code)] + #[derive(Debug, onlyerror::Error)] enum Error {} diff --git a/compile_tests/skip_positional.rs b/compile_tests/skip_positional.rs new file mode 100644 index 0000000..ab9f1e7 --- /dev/null +++ b/compile_tests/skip_positional.rs @@ -0,0 +1,9 @@ +#![allow(dead_code)] + +#[derive(Debug, onlyerror::Error)] +enum Error { + /// Skip positional tuple fields {1} + Skip(u8, u8), +} + +fn main() {} diff --git a/src/lib.rs b/src/lib.rs index 4e3a2d5..68cc273 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -142,22 +142,21 @@ pub fn derive_error(input: TokenStream) -> TokenStream { v.display_fields .iter() .fold(String::new(), |mut fields, field| { - write!(fields, "{field},").unwrap(); + let _ = write!(fields, "{field},"); fields }); Ok(match &v.ty { VariantType::Unit => format!("Self::{name} => write!(f, {display:?}),"), VariantType::Tuple => { - let fields = (0..v.fields.len()) - .map(|i| { - if v.display_fields.contains(&Rc::from(format!("field_{i}"))) { - format!("field_{i},") - } else { - String::from("_,") - } - }) - .collect::(); + let fields = (0..v.fields.len()).fold(String::new(), |mut fields, i| { + if v.display_fields.contains(&Rc::from(format!("field_{i}"))) { + let _ = write!(fields, "field_{i},"); + } else { + let _ = fields.write_str("_,"); + } + fields + }); format!("Self::{name}({fields}) => write!(f, {display:?}, {display_fields}),") } VariantType::Struct => { diff --git a/src/parser.rs b/src/parser.rs index cda1f66..e8b6345 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -154,7 +154,7 @@ impl Variant { .to_string(); // Collect field references. - let display_fields = display + let display_fields: Vec> = display .split('{') .skip(1) .filter_map(|s| s.split('}').next()) @@ -170,6 +170,16 @@ impl Variant { // Remove field references from format string. for field in &display_fields { + // Special case for tuples + if ty == VariantType::Tuple { + if let Some(num) = field.strip_prefix("field_") { + display = display + .replace(&format!("{{{num}:"), "{:") + .replace(&format!("{{{num}}}"), "{}"); + continue; + } + } + display = display .replace(&format!("{{{field}:"), "{:") .replace(&format!("{{{field}}}"), "{}");