Skip to content

Commit

Permalink
Ensure expanded ref_cast_custom code compiles with forbid(unsafe_code)
Browse files Browse the repository at this point in the history
The idea is borrowed from the pin-project crate. If the expanded "unsafe" token
were attached to the caller's span, it would be rejected by forbid(unsafe_code)
at caller.

https://github.com/taiki-e/pin-project/blob/266b44e75a9cefab23a87238cff6e7118b6bbefa/pin-project-internal/src/pin_project/derive.rs#L719
  • Loading branch information
yuja committed Dec 13, 2023
1 parent 0a1a615 commit ae54280
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 4 additions & 1 deletion derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,9 @@ fn expand_function_body(function: Function) -> TokenStream2 {
}
}

// Do not apply the caller's span to our "unsafe" token. Otherwise
// `forbid(unsafe_code)` at caller would reject the expanded code.
let our_unsafe = quote!(unsafe);
quote_spanned! {semi_token.span=>
#(#attrs)*
#inline_attr
Expand All @@ -366,7 +369,7 @@ fn expand_function_body(function: Function) -> TokenStream2 {
let _ = ::ref_cast::__private::CurrentCrate::<#from_type, #to_type> {};

#allow_unused_unsafe // in case they are building with deny(unsafe_op_in_unsafe_fn)
unsafe {
#our_unsafe {
::ref_cast::__private::transmute::<#from_type, #to_type>(#arg)
}
}
Expand Down
15 changes: 15 additions & 0 deletions tests/test_trivial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,26 @@ pub struct Unsized<'a> {
pub value: str,
}

#[forbid(unsafe_code)]
mod forbid_unsafe {
use ref_cast::{ref_cast_custom, RefCastCustom};

#[derive(RefCastCustom)]
#[repr(transparent)]
pub struct Custom(str);

impl Custom {
#[ref_cast_custom]
pub fn new(s: &str) -> &Custom;
}
}

#[test]
fn test_trivial() {
ImplicitUnit::ref_cast(&0);
ImplicitPhantomData::ref_cast(&0);
ExplicitTrivial::ref_cast(&0);
Override::<u8, i8>::ref_cast(&PhantomData::<i8>);
Unsized::ref_cast("...");
forbid_unsafe::Custom::new("...");
}

0 comments on commit ae54280

Please sign in to comment.