From d50231ee288daa13ee8992e2dd878808a101d24b Mon Sep 17 00:00:00 2001 From: Jay Oster Date: Thu, 4 May 2023 15:45:08 -0700 Subject: [PATCH] Safe codegen (#12) * Run the flaky compile test only on stable * Use a conditional match statement in codegen This removes `unsafe` from codegen, which is unnecessary and rather obscure. * Use String::from() consistently --- compile_tests/compiler.rs | 2 +- src/lib.rs | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/compile_tests/compiler.rs b/compile_tests/compiler.rs index 23d1178..0ad883e 100644 --- a/compile_tests/compiler.rs +++ b/compile_tests/compiler.rs @@ -9,7 +9,7 @@ fn compile_tests() { t.compile_fail("compile_tests/multiple_non_signed.rs"); t.compile_fail("compile_tests/multiple_one_non_signed.rs"); t.pass("compile_tests/no_display.rs"); - if rustversion::cfg!(since(1.68.0)) { + if rustversion::cfg!(all(stable, since(1.68.0))) { t.compile_fail("compile_tests/no_display_no_impl.rs"); } } diff --git a/src/lib.rs b/src/lib.rs index 105b7c1..732672a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -152,7 +152,7 @@ pub fn derive_error(input: TokenStream) -> TokenStream { if v.display_fields.contains(&Rc::from(format!("field_{i}"))) { format!("field_{i},") } else { - "_,".to_string() + String::from("_,") } }) .collect::(); @@ -175,18 +175,18 @@ pub fn derive_error(input: TokenStream) -> TokenStream { Ok(msg) => display_matches.push_str(&msg), } } - display_matches.push_str(&format!( - "_ => unsafe {{ ::{std_crate}::hint::unreachable_unchecked()}}" - )); + let display_matches = if display_matches.is_empty() { + String::from("Ok(())") + } else { + format!("match self {{ {display_matches} }}") + }; format!( r#"impl ::{std_crate}::fmt::Display for {name} {{ fn fmt(&self, f: &mut ::{std_crate}::fmt::Formatter<'_>) -> ::{std_crate}::result::Result<(), ::{std_crate}::fmt::Error> {{ - match self {{ - {display_matches} - }} + {display_matches} }} }}"# )