Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions utils/zerofrom/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,17 @@ extern crate alloc;

mod macro_impls;
mod zero_from;
mod zf_transparent;

#[cfg(feature = "derive")]
pub use zerofrom_derive::ZeroFrom;

pub use crate::zero_from::ZeroFrom;

#[cfg(feature = "alloc")]
#[doc(hidden)] // for macros
pub mod internal {
pub use crate::zf_transparent::cast_transparent_box;
pub use alloc::boxed::Box;
pub use alloc::rc::Rc;
}
157 changes: 157 additions & 0 deletions utils/zerofrom/src/zf_transparent.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

#[cfg(feature = "alloc")]
use alloc::boxed::Box;

/// Internal function: casts a box of `Inner` to a box of `Outer`, assuming
/// `Outer` is transparent over `Inner`.
///
/// # Safety
///
/// `Outer` is `repr(transparent)` and has one non-zero-sized field of type `Inner`.
///
/// Suggestion: explicitly setting the generic parameters to two types satisfying this invariant
/// makes the fn safe to call.
#[cfg(feature = "alloc")]
#[inline(always)]
pub unsafe fn cast_transparent_box<Inner, Outer>(inner: Box<Inner>) -> Box<Outer> {
// Safety:
//
// - Both boxes have the same allocator (the global allocator).
// - Since `Outer` is transparent over `Inner`, they have the same layout.
// - `Box::into_raw` returns a properly aligned, non-null `*mut Inner`.
Box::from_raw(Box::into_raw(inner) as *mut Outer)
}

/// Implements [`ZeroFrom`](crate::ZeroFrom) on a transparent type
/// from a reference to the inner type.
///
/// Also supports creating concrete functions.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit:

Suggested change
/// Also supports creating concrete functions.
/// Also supports adding concrete conversion functions between various reference types.

///
/// # Examples
///
/// ```
/// use crate::zerofrom::ZeroFrom;
///
/// zerofrom::transparent!(
/// #[repr(transparent)]
/// pub struct StrWrap(str);
/// impl ZeroFrom<&str> for &StrWrap;
/// );
///
/// let s = "hello";
/// let wrap = <&StrWrap>::zero_from(s);
///
/// assert_eq!(&wrap.0, "hello");
/// ```
#[macro_export]
macro_rules! transparent {
(
#[repr(transparent)]
$(#[$meta:meta])*
Comment on lines +52 to +53
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is sensitive to attribute ordering, which it shouldn't be

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$(#[$meta:meta])* is greedy and there isn't a clean way to make it non-greedy so I need to put the #[repr(transparent)] at the top.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A different approach is to have the macro generate the repr but that's less obvious to the reader.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right. As currently written the macro does not add anything to the struct definition. It just echoes it back out. The only thing is does is add impls which it claims are safe due to the shape of the struct.

$vis:vis struct $outer:ident($inner:ty);
$(
impl ZeroFrom<&$inner_zf:ty> for &$outer_zf:ident;
)?
$(impl {
$(
@ref
$(#[$meta_ref:meta])*
$vis_ref:vis fn $fn_ref:ident(&$inner_ref:ty) -> &Self;
)?
$(
@slice
$(#[$meta_slice:meta])*
$vis_slice:vis fn $fn_slice:ident(&[$inner_slice:ty]) -> &[Self];
)?
$(
@box
$(#[$meta_box:meta])*
$vis_box:vis fn $fn_box:ident(Box<$inner_box:ty>) -> Box<Self>;
)?
$(
@rc
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's try to keep custom syntax to a minimum. it should suffice to match on the argument

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll try again, but if I match on the argument then every token up to the argument can't be itself a match. macro_rules doesn't do fancy lookahead matching.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's a simplified example if you want to see if you can get it to work:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=8931afd392ba47737907ee2fdb37a2fb

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussion with @robertbastian: if we remove the meta, vis, and function name, then we can match on the argument type. This seems fine.

$(#[$meta_rc:meta])*
$vis_rc:vis fn $fn_rc:ident(Rc<$inner_rc:ty>) -> Rc<Self>;
)?
})?
) => {
#[repr(transparent)]
$(#[$meta])*
$vis struct $outer($inner);
$(
impl<'zf> $crate::ZeroFrom<'zf, $inner_zf> for &'zf $outer {
fn zero_from(inner: &'zf $inner) -> Self {
unsafe { core::mem::transmute::<&$inner, &$outer>(inner) }
}
}
)?
$(impl $outer {
$(
$(#[$meta_ref])*
$vis_ref fn $fn_ref(inner: &$inner_ref) -> &Self {
unsafe { core::mem::transmute::<&$inner, &$outer>(inner) }
}
)?
$(
$(#[$meta_slice])*
$vis_slice fn $fn_slice(inner: &[$inner_slice]) -> &[Self] {
unsafe { core::mem::transmute::<&[$inner], &[$outer]>(inner) }
}
)?
$(
$(#[$meta_box])*
$vis_box fn $fn_box(inner: $crate::internal::Box<$inner_box>) -> $crate::internal::Box<Self> {
// Safety: $outer is repr(transparent) over $inner.
unsafe { $crate::internal::cast_transparent_box::<$inner, $outer>(inner) }
}
)?
$(
$(#[$meta_rc])*
$vis_rc fn $fn_rc(inner: $crate::internal::Rc<$inner_rc>) -> $crate::internal::Rc<Self> {
unsafe { core::mem::transmute(inner) }
}
)?
})?
};
}

/// Additional tests for failure modes.
///
/// ```compile_fail,E0053
/// zerofrom::transparent! {
/// #[repr(transparent)]
/// pub struct Foo(String);
/// // Wrong types in these positions!
/// impl ZeroFrom<&Foo> for &String;
/// };
/// ```
///
/// ```compile_fail,E0308
/// zerofrom::transparent! {
/// #[repr(transparent)]
/// pub struct Foo(String);
/// impl {
/// @ref
/// // Wrong type in this position!
/// pub fn from(&Foo) -> &Self;
/// }
/// };
/// ```
///
/// ```compile_fail,E0308
/// zerofrom::transparent! {
/// #[repr(transparent)]
/// pub struct Foo(String);
/// impl {
/// @slice
/// // Wrong type in this position!
/// pub fn from(&[Foo]) -> &[Self];
/// }
/// };
/// ```
///
/// TODO: Rc
mod _tests {}
29 changes: 29 additions & 0 deletions utils/zerofrom/tests/test_transparent.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use zerofrom::transparent;

transparent!(
#[repr(transparent)]
/// hello world
#[derive(Debug)]
pub(crate) struct Foo([u8; 3]);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like type declarations living inside macro invocations. From a call site it's not known that this code is passed through without modifications, the macro could do anything to it (change the repr, add fields, wrap fields, etc).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this is why I've overall been very lukewarm on #7607 so far. But I think this is the most maintainable and low-impact version.

We can document what the macro does, and it's pretty easy to verify it, which is why I think this is still a good idea overall.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't love this approach, either. It was not my first or second or third choice at solving the problem. But @Manishearth identified flaws in all the other approaches. My conclusion is that this is the least bad, and better than not solving the problem.

impl ZeroFrom<&[u8; 3]> for &Foo;
impl {
@ref
/// Cast a transparent ref!
#[inline]
fn from_transparent_ref(&[u8; 3]) -> &Self;
@slice
/// Cast a transparent slice!
pub fn from_transparent_slice(&[[u8; 3]]) -> &[Self];
@box
/// Cast a transparent box!
#[cfg(feature = "alloc")]
fn from_transparent_box(Box<[u8; 3]>) -> Box<Self>;
}
);

#[test]
fn test() {}
Loading