ref_cast_impl/
lib.rs

1#![allow(
2    clippy::blocks_in_conditions,
3    clippy::needless_pass_by_value,
4    clippy::if_not_else
5)]
6
7extern crate proc_macro;
8
9use proc_macro::TokenStream;
10use proc_macro2::{Ident, Span, TokenStream as TokenStream2, TokenTree};
11use quote::{quote, quote_spanned, ToTokens, TokenStreamExt as _};
12use syn::parse::{Nothing, ParseStream, Parser};
13use syn::punctuated::Punctuated;
14use syn::{
15    parenthesized, parse_macro_input, token, Abi, Attribute, Data, DeriveInput, Error, Expr, Field,
16    Generics, Path, Result, Token, Type, Visibility,
17};
18
19/// Derive the `RefCast` trait.
20///
21/// See the [crate-level documentation](./index.html) for usage examples!
22///
23/// # Attributes
24///
25/// Use the `#[trivial]` attribute to mark any zero-sized fields that are *not*
26/// the one that references are going to be converted from.
27///
28/// ```
29/// use ref_cast::RefCast;
30/// use std::marker::PhantomData;
31///
32/// #[derive(RefCast)]
33/// #[repr(transparent)]
34/// pub struct Generic<T, U> {
35///     raw: Vec<U>,
36///     #[trivial]
37///     aux: Variance<T, U>,
38/// }
39///
40/// type Variance<T, U> = PhantomData<fn(T) -> U>;
41/// ```
42///
43/// Fields with a type named `PhantomData` or `PhantomPinned` are automatically
44/// recognized and do not need to be marked with this attribute.
45///
46/// ```
47/// use ref_cast::RefCast;
48/// use std::marker::{PhantomData, PhantomPinned};
49///
50/// #[derive(RefCast)]  // generates a conversion from &[u8] to &Bytes<'_>
51/// #[repr(transparent)]
52/// pub struct Bytes<'arena> {
53///     lifetime: PhantomData<&'arena ()>,
54///     pin: PhantomPinned,
55///     bytes: [u8],
56/// }
57/// ```
58#[proc_macro_derive(RefCast, attributes(trivial))]
59pub fn derive_ref_cast(input: TokenStream) -> TokenStream {
60    let input = match ::syn::parse::<DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}parse_macro_input!(input as DeriveInput);
61    expand_ref_cast(&input)
62        .unwrap_or_else(Error::into_compile_error)
63        .into()
64}
65
66/// Derive that makes the `ref_cast_custom` attribute able to generate
67/// freestanding reference casting functions for a type.
68///
69/// Please refer to the documentation of
70/// [`#[ref_cast_custom]`][macro@ref_cast_custom] where these two macros are
71/// documented together.
72#[proc_macro_derive(RefCastCustom, attributes(trivial))]
73pub fn derive_ref_cast_custom(input: TokenStream) -> TokenStream {
74    let input = match ::syn::parse::<DeriveInput>(input) {
    ::syn::__private::Ok(data) => data,
    ::syn::__private::Err(err) => {
        return ::syn::__private::TokenStream::from(err.to_compile_error());
    }
}parse_macro_input!(input as DeriveInput);
75    expand_ref_cast_custom(&input)
76        .unwrap_or_else(Error::into_compile_error)
77        .into()
78}
79
80/// Create a function for a RefCast-style reference cast. Call site gets control
81/// of the visibility, function name, argument name, `const`ness, unsafety, and
82/// documentation.
83///
84/// The `derive(RefCast)` macro produces a trait impl, which means the function
85/// names are predefined, and public if your type is public, and not callable in
86/// `const` (at least today on stable Rust). As an alternative to that,
87/// `derive(RefCastCustom)` exposes greater flexibility so that instead of a
88/// trait impl, the casting functions can be made associated functions or free
89/// functions, can be named what you want, documented, `const` or `unsafe` if
90/// you want, and have your exact choice of visibility.
91///
92/// ```rust
93/// use ref_cast::{ref_cast_custom, RefCastCustom};
94///
95/// #[derive(RefCastCustom)]  // does not generate any public API by itself
96/// #[repr(transparent)]
97/// pub struct Frame([u8]);
98///
99/// impl Frame {
100///     #[ref_cast_custom]  // requires derive(RefCastCustom) on the return type
101///     pub(crate) const fn new(bytes: &[u8]) -> &Self;
102///
103///     #[ref_cast_custom]
104///     pub(crate) fn new_mut(bytes: &mut [u8]) -> &mut Self;
105/// }
106///
107/// // example use of the const fn
108/// const FRAME: &Frame = Frame::new(b"...");
109/// ```
110///
111/// The above shows associated functions, but you might alternatively want to
112/// generate free functions:
113///
114/// ```rust
115/// # use ref_cast::{ref_cast_custom, RefCastCustom};
116/// #
117/// # #[derive(RefCastCustom)]
118/// # #[repr(transparent)]
119/// # pub struct Frame([u8]);
120/// #
121/// impl Frame {
122///     pub fn new<T: AsRef<[u8]>>(bytes: &T) -> &Self {
123///         #[ref_cast_custom]
124///         fn ref_cast(bytes: &[u8]) -> &Frame;
125///
126///         ref_cast(bytes.as_ref())
127///     }
128/// }
129/// ```
130#[proc_macro_attribute]
131pub fn ref_cast_custom(args: TokenStream, input: TokenStream) -> TokenStream {
132    let input = TokenStream2::from(input);
133    let expanded = match (|input: ParseStream| {
134        let attrs = input.call(Attribute::parse_outer)?;
135        let vis: Visibility = input.parse()?;
136        let constness: Option<Token![const]> = input.parse()?;
137        let asyncness: Option<Token![async]> = input.parse()?;
138        let unsafety: Option<Token![unsafe]> = input.parse()?;
139        let abi: Option<Abi> = input.parse()?;
140        let fn_token: Token![fn] = input.parse()?;
141        let ident: Ident = input.parse()?;
142        let mut generics: Generics = input.parse()?;
143
144        let content;
145        let paren_token = match ::syn::__private::parse_parens(&input) {
    ::syn::__private::Ok(parens) => { content = parens.content; parens.token }
    ::syn::__private::Err(error) => { return ::syn::__private::Err(error); }
}parenthesized!(content in input);
146        let arg: Ident = content.parse()?;
147        let colon_token: Token![:] = content.parse()?;
148        let from_type: Type = content.parse()?;
149        let _trailing_comma: Option<Token![,]> = content.parse()?;
150        if !content.is_empty() {
151            let rest: TokenStream2 = content.parse()?;
152            return Err(Error::new_spanned(
153                rest,
154                "ref_cast_custom function is required to have a single argument",
155            ));
156        }
157
158        let arrow_token: Token![->] = input.parse()?;
159        let to_type: Type = input.parse()?;
160        generics.where_clause = input.parse()?;
161        let semi_token: Token![;] = input.parse()?;
162
163        let _: Nothing = syn::parse::<Nothing>(args)?;
164
165        Ok(Function {
166            attrs,
167            vis,
168            constness,
169            asyncness,
170            unsafety,
171            abi,
172            fn_token,
173            ident,
174            generics,
175            paren_token,
176            arg,
177            colon_token,
178            from_type,
179            arrow_token,
180            to_type,
181            semi_token,
182        })
183    })
184    .parse2(input.clone())
185    {
186        Ok(function) => expand_function_body(function),
187        Err(parse_error) => {
188            let compile_error = parse_error.to_compile_error();
189            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&compile_error, &mut _s);
    ::quote::ToTokens::to_tokens(&input, &mut _s);
    _s
}quote!(#compile_error #input)
190        }
191    };
192    TokenStream::from(expanded)
193}
194
195#[allow(non_camel_case_types)]
196struct private;
197
198impl ToTokens for private {
199    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
200        tokens.append(Ident::new(
201            "__private25"concat!("__private", env!("CARGO_PKG_VERSION_PATCH")),
202            Span::call_site(),
203        ));
204    }
205}
206
207struct Function {
208    attrs: Vec<Attribute>,
209    vis: Visibility,
210    constness: Option<Token![const]>,
211    asyncness: Option<Token![async]>,
212    unsafety: Option<Token![unsafe]>,
213    abi: Option<Abi>,
214    fn_token: Token![fn],
215    ident: Ident,
216    generics: Generics,
217    paren_token: token::Paren,
218    arg: Ident,
219    colon_token: Token![:],
220    from_type: Type,
221    arrow_token: Token![->],
222    to_type: Type,
223    semi_token: Token![;],
224}
225
226fn expand_ref_cast(input: &DeriveInput) -> Result<TokenStream2> {
227    check_repr(input)?;
228
229    let name = &input.ident;
230    let name_str = name.to_string();
231    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
232
233    let fields = fields(input)?;
234    let from = only_field_ty(fields)?;
235    let trivial = trivial_fields(fields)?;
236    let private2 = private;
237
238    let assert_trivial_fields = if !trivial.is_empty() {
239        Some({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "if");
    ::quote::__private::push_ident(&mut _s, "false");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            {
                use ::quote::__private::ext::*;
                let has_iter =
                    ::quote::__private::ThereIsNoIteratorInRepetition;
                #[allow(unused_mut)]
                let (mut private2, i) = private2.quote_into_iter();
                let has_iter = has_iter | i;
                #[allow(unused_mut)]
                let (mut trivial, i) = trivial.quote_into_iter();
                let has_iter = has_iter | i;
                let _: ::quote::__private::HasIterator = has_iter;
                while true {
                    let private2 =
                        match private2.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    let trivial =
                        match trivial.next() {
                            Some(_x) => ::quote::__private::RepInterp(_x),
                            None => break,
                        };
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "ref_cast");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::ToTokens::to_tokens(&private2, &mut _s);
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "assert_trivial");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_lt(&mut _s);
                    ::quote::ToTokens::to_tokens(&trivial, &mut _s);
                    ::quote::__private::push_gt(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Parenthesis,
                        ::quote::__private::TokenStream::new());
                    ::quote::__private::push_semi(&mut _s);
                }
            }
            _s
        });
    _s
}quote! {
240            if false {
241                #(
242                    ::ref_cast::#private2::assert_trivial::<#trivial>();
243                )*
244            }
245        })
246    } else {
247        None
248    };
249
250    Ok({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "impl");
    ::quote::ToTokens::to_tokens(&impl_generics, &mut _s);
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "ref_cast");
    ::quote::__private::push_colon2(&mut _s);
    ::quote::__private::push_ident(&mut _s, "RefCast");
    ::quote::__private::push_ident(&mut _s, "for");
    ::quote::ToTokens::to_tokens(&name, &mut _s);
    ::quote::ToTokens::to_tokens(&ty_generics, &mut _s);
    ::quote::ToTokens::to_tokens(&where_clause, &mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "type");
            ::quote::__private::push_ident(&mut _s, "From");
            ::quote::__private::push_eq(&mut _s);
            ::quote::ToTokens::to_tokens(&from, &mut _s);
            ::quote::__private::push_semi(&mut _s);
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "inline");
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "fn");
            ::quote::__private::push_ident(&mut _s, "ref_cast");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "_from");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::__private::push_and(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "Self");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "From");
                    _s
                });
            ::quote::__private::push_rarrow(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_ident(&mut _s, "Self");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::ToTokens::to_tokens(&assert_trivial_fields,
                        &mut _s);
                    ::quote::__private::push_pound(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Bracket,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "cfg");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s, "debug_assertions");
                                    _s
                                });
                            _s
                        });
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_pound(&mut _s);
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Bracket,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s, "allow");
                                    ::quote::__private::push_group(&mut _s,
                                        ::quote::__private::Delimiter::Parenthesis,
                                        {
                                            let mut _s = ::quote::__private::TokenStream::new();
                                            ::quote::__private::push_ident(&mut _s, "unused_imports");
                                            _s
                                        });
                                    _s
                                });
                            ::quote::__private::push_ident(&mut _s, "use");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "ref_cast");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::ToTokens::to_tokens(&private, &mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "LayoutUnsized");
                            ::quote::__private::push_semi(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "ref_cast");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::ToTokens::to_tokens(&private, &mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "assert_layout");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_lt(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Self");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Self");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "From");
                            ::quote::__private::push_gt(&mut _s);
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::ToTokens::to_tokens(&name_str, &mut _s);
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ref_cast");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::ToTokens::to_tokens(&private, &mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Layout");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    ::quote::__private::push_gt(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "SIZE");
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ref_cast");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::ToTokens::to_tokens(&private, &mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Layout");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "From");
                                    ::quote::__private::push_gt(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "SIZE");
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ref_cast");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::ToTokens::to_tokens(&private, &mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Layout");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    ::quote::__private::push_gt(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ALIGN");
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ref_cast");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::ToTokens::to_tokens(&private, &mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Layout");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "From");
                                    ::quote::__private::push_gt(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ALIGN");
                                    ::quote::__private::push_comma(&mut _s);
                                    _s
                                });
                            ::quote::__private::push_semi(&mut _s);
                            _s
                        });
                    ::quote::__private::push_ident(&mut _s, "unsafe");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_and(&mut _s);
                            ::quote::__private::push_star(&mut _s);
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s, "_from");
                                    ::quote::__private::push_ident(&mut _s, "as");
                                    ::quote::__private::push_star(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "const");
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "From");
                                    ::quote::__private::push_ident(&mut _s, "as");
                                    ::quote::__private::push_star(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "const");
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    _s
                                });
                            _s
                        });
                    _s
                });
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "inline");
                    _s
                });
            ::quote::__private::push_ident(&mut _s, "fn");
            ::quote::__private::push_ident(&mut _s, "ref_cast_mut");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "_from");
                    ::quote::__private::push_colon(&mut _s);
                    ::quote::__private::push_and(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "mut");
                    ::quote::__private::push_ident(&mut _s, "Self");
                    ::quote::__private::push_colon2(&mut _s);
                    ::quote::__private::push_ident(&mut _s, "From");
                    _s
                });
            ::quote::__private::push_rarrow(&mut _s);
            ::quote::__private::push_and(&mut _s);
            ::quote::__private::push_ident(&mut _s, "mut");
            ::quote::__private::push_ident(&mut _s, "Self");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_pound(&mut _s);
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Bracket,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_ident(&mut _s, "cfg");
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s, "debug_assertions");
                                    _s
                                });
                            _s
                        });
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_pound(&mut _s);
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Bracket,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s, "allow");
                                    ::quote::__private::push_group(&mut _s,
                                        ::quote::__private::Delimiter::Parenthesis,
                                        {
                                            let mut _s = ::quote::__private::TokenStream::new();
                                            ::quote::__private::push_ident(&mut _s, "unused_imports");
                                            _s
                                        });
                                    _s
                                });
                            ::quote::__private::push_ident(&mut _s, "use");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "ref_cast");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::ToTokens::to_tokens(&private, &mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "LayoutUnsized");
                            ::quote::__private::push_semi(&mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "ref_cast");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::ToTokens::to_tokens(&private, &mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "assert_layout");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_lt(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Self");
                            ::quote::__private::push_comma(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "Self");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "From");
                            ::quote::__private::push_gt(&mut _s);
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::ToTokens::to_tokens(&name_str, &mut _s);
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ref_cast");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::ToTokens::to_tokens(&private, &mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Layout");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    ::quote::__private::push_gt(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "SIZE");
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ref_cast");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::ToTokens::to_tokens(&private, &mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Layout");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "From");
                                    ::quote::__private::push_gt(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "SIZE");
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ref_cast");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::ToTokens::to_tokens(&private, &mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Layout");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    ::quote::__private::push_gt(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ALIGN");
                                    ::quote::__private::push_comma(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ref_cast");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::ToTokens::to_tokens(&private, &mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Layout");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_lt(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "From");
                                    ::quote::__private::push_gt(&mut _s);
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "ALIGN");
                                    ::quote::__private::push_comma(&mut _s);
                                    _s
                                });
                            ::quote::__private::push_semi(&mut _s);
                            _s
                        });
                    ::quote::__private::push_ident(&mut _s, "unsafe");
                    ::quote::__private::push_group(&mut _s,
                        ::quote::__private::Delimiter::Brace,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            ::quote::__private::push_and(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "mut");
                            ::quote::__private::push_star(&mut _s);
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                {
                                    let mut _s = ::quote::__private::TokenStream::new();
                                    ::quote::__private::push_ident(&mut _s, "_from");
                                    ::quote::__private::push_ident(&mut _s, "as");
                                    ::quote::__private::push_star(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "mut");
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    ::quote::__private::push_colon2(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "From");
                                    ::quote::__private::push_ident(&mut _s, "as");
                                    ::quote::__private::push_star(&mut _s);
                                    ::quote::__private::push_ident(&mut _s, "mut");
                                    ::quote::__private::push_ident(&mut _s, "Self");
                                    _s
                                });
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote! {
251        impl #impl_generics ::ref_cast::RefCast for #name #ty_generics #where_clause {
252            type From = #from;
253
254            #[inline]
255            fn ref_cast(_from: &Self::From) -> &Self {
256                #assert_trivial_fields
257                #[cfg(debug_assertions)]
258                {
259                    #[allow(unused_imports)]
260                    use ::ref_cast::#private::LayoutUnsized;
261                    ::ref_cast::#private::assert_layout::<Self, Self::From>(
262                        #name_str,
263                        ::ref_cast::#private::Layout::<Self>::SIZE,
264                        ::ref_cast::#private::Layout::<Self::From>::SIZE,
265                        ::ref_cast::#private::Layout::<Self>::ALIGN,
266                        ::ref_cast::#private::Layout::<Self::From>::ALIGN,
267                    );
268                }
269                unsafe {
270                    &*(_from as *const Self::From as *const Self)
271                }
272            }
273
274            #[inline]
275            fn ref_cast_mut(_from: &mut Self::From) -> &mut Self {
276                #[cfg(debug_assertions)]
277                {
278                    #[allow(unused_imports)]
279                    use ::ref_cast::#private::LayoutUnsized;
280                    ::ref_cast::#private::assert_layout::<Self, Self::From>(
281                        #name_str,
282                        ::ref_cast::#private::Layout::<Self>::SIZE,
283                        ::ref_cast::#private::Layout::<Self::From>::SIZE,
284                        ::ref_cast::#private::Layout::<Self>::ALIGN,
285                        ::ref_cast::#private::Layout::<Self::From>::ALIGN,
286                    );
287                }
288                unsafe {
289                    &mut *(_from as *mut Self::From as *mut Self)
290                }
291            }
292        }
293    })
294}
295
296fn expand_ref_cast_custom(input: &DeriveInput) -> Result<TokenStream2> {
297    check_repr(input)?;
298
299    let vis = &input.vis;
300    let name = &input.ident;
301    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
302
303    let fields = fields(input)?;
304    let from = only_field_ty(fields)?;
305    let trivial = trivial_fields(fields)?;
306    let private2 = private;
307
308    let assert_trivial_fields = if !trivial.is_empty() {
309        Some({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "fn");
    ::quote::__private::push_ident(&mut _s, "__static_assert");
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "if");
            ::quote::__private::push_ident(&mut _s, "false");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    {
                        use ::quote::__private::ext::*;
                        let has_iter =
                            ::quote::__private::ThereIsNoIteratorInRepetition;
                        #[allow(unused_mut)]
                        let (mut private2, i) = private2.quote_into_iter();
                        let has_iter = has_iter | i;
                        #[allow(unused_mut)]
                        let (mut trivial, i) = trivial.quote_into_iter();
                        let has_iter = has_iter | i;
                        let _: ::quote::__private::HasIterator = has_iter;
                        while true {
                            let private2 =
                                match private2.next() {
                                    Some(_x) => ::quote::__private::RepInterp(_x),
                                    None => break,
                                };
                            let trivial =
                                match trivial.next() {
                                    Some(_x) => ::quote::__private::RepInterp(_x),
                                    None => break,
                                };
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "ref_cast");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::ToTokens::to_tokens(&private2, &mut _s);
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_ident(&mut _s, "assert_trivial");
                            ::quote::__private::push_colon2(&mut _s);
                            ::quote::__private::push_lt(&mut _s);
                            ::quote::ToTokens::to_tokens(&trivial, &mut _s);
                            ::quote::__private::push_gt(&mut _s);
                            ::quote::__private::push_group(&mut _s,
                                ::quote::__private::Delimiter::Parenthesis,
                                ::quote::__private::TokenStream::new());
                            ::quote::__private::push_semi(&mut _s);
                        }
                    }
                    _s
                });
            _s
        });
    _s
}quote! {
310            fn __static_assert() {
311                if false {
312                    #(
313                        ::ref_cast::#private2::assert_trivial::<#trivial>();
314                    )*
315                }
316            }
317        })
318    } else {
319        None
320    };
321
322    Ok({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "const");
    ::quote::__private::push_underscore(&mut _s);
    ::quote::__private::push_colon(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Parenthesis,
        ::quote::__private::TokenStream::new());
    ::quote::__private::push_eq(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_pound(&mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "non_exhaustive");
                    _s
                });
            ::quote::ToTokens::to_tokens(&vis, &mut _s);
            ::quote::__private::push_ident(&mut _s, "struct");
            ::quote::__private::push_ident(&mut _s, "RefCastCurrentCrate");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                ::quote::__private::TokenStream::new());
            ::quote::__private::push_ident(&mut _s, "unsafe");
            ::quote::__private::push_ident(&mut _s, "impl");
            ::quote::ToTokens::to_tokens(&impl_generics, &mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "ref_cast");
            ::quote::__private::push_colon2(&mut _s);
            ::quote::ToTokens::to_tokens(&private, &mut _s);
            ::quote::__private::push_colon2(&mut _s);
            ::quote::__private::push_ident(&mut _s, "RefCastCustom");
            ::quote::__private::push_lt(&mut _s);
            ::quote::ToTokens::to_tokens(&from, &mut _s);
            ::quote::__private::push_gt(&mut _s);
            ::quote::__private::push_ident(&mut _s, "for");
            ::quote::ToTokens::to_tokens(&name, &mut _s);
            ::quote::ToTokens::to_tokens(&ty_generics, &mut _s);
            ::quote::ToTokens::to_tokens(&where_clause, &mut _s);
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "type");
                    ::quote::__private::push_ident(&mut _s, "CurrentCrate");
                    ::quote::__private::push_eq(&mut _s);
                    ::quote::__private::push_ident(&mut _s,
                        "RefCastCurrentCrate");
                    ::quote::__private::push_semi(&mut _s);
                    ::quote::ToTokens::to_tokens(&assert_trivial_fields,
                        &mut _s);
                    _s
                });
            _s
        });
    ::quote::__private::push_semi(&mut _s);
    _s
}quote! {
323        const _: () = {
324            #[non_exhaustive]
325            #vis struct RefCastCurrentCrate {}
326
327            unsafe impl #impl_generics ::ref_cast::#private::RefCastCustom<#from> for #name #ty_generics #where_clause {
328                type CurrentCrate = RefCastCurrentCrate;
329                #assert_trivial_fields
330            }
331        };
332    })
333}
334
335fn expand_function_body(function: Function) -> TokenStream2 {
336    let Function {
337        attrs,
338        vis,
339        constness,
340        asyncness,
341        unsafety,
342        abi,
343        fn_token,
344        ident,
345        generics,
346        paren_token,
347        arg,
348        colon_token,
349        from_type,
350        arrow_token,
351        to_type,
352        semi_token,
353    } = function;
354
355    let args = {
    let mut _s = ::quote::__private::TokenStream::new();
    let _span: ::quote::__private::Span =
        ::quote::__private::get_span(paren_token.span).__into_span();
    ::quote::__private::push_group_spanned(&mut _s, _span,
        ::quote::__private::Delimiter::Parenthesis,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            let _span: ::quote::__private::Span =
                ::quote::__private::get_span(_span).__into_span();
            ::quote::ToTokens::to_tokens(&arg, &mut _s);
            ::quote::ToTokens::to_tokens(&colon_token, &mut _s);
            ::quote::ToTokens::to_tokens(&from_type, &mut _s);
            _s
        });
    _s
}quote_spanned! {paren_token.span=>
356        (#arg #colon_token #from_type)
357    };
358
359    let allow_unused_unsafe = if unsafety.is_some() {
360        Some({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "allow");
            ::quote::__private::push_group(&mut _s,
                ::quote::__private::Delimiter::Parenthesis,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    ::quote::__private::push_ident(&mut _s, "unused_unsafe");
                    _s
                });
            _s
        });
    _s
}quote!(#[allow(unused_unsafe)]))
361    } else {
362        None
363    };
364
365    let mut inline_attr = Some({
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_pound(&mut _s);
    ::quote::__private::push_group(&mut _s,
        ::quote::__private::Delimiter::Bracket,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            ::quote::__private::push_ident(&mut _s, "inline");
            _s
        });
    _s
}quote!(#[inline]));
366    for attr in &attrs {
367        if attr.path().is_ident("inline") {
368            inline_attr = None;
369            break;
370        }
371    }
372
373    // Apply a macro-generated span to the "unsafe" token for the unsafe block.
374    // This is instead of reusing the caller's function signature's #unsafety
375    // across both the generated function signature and generated unsafe block,
376    // and instead of using `semi_token.span` like for the rest of the generated
377    // code below, both of which would cause `forbid(unsafe_code)` located in
378    // the caller to reject the expanded code.
379    let macro_generated_unsafe = {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::__private::push_ident(&mut _s, "unsafe");
    _s
}quote!(unsafe);
380
381    {
    let mut _s = ::quote::__private::TokenStream::new();
    let _span: ::quote::__private::Span =
        ::quote::__private::get_span(semi_token.span).__into_span();
    {
        use ::quote::__private::ext::*;
        let has_iter = ::quote::__private::ThereIsNoIteratorInRepetition;
        #[allow(unused_mut)]
        let (mut attrs, i) = attrs.quote_into_iter();
        let has_iter = has_iter | i;
        let _: ::quote::__private::HasIterator = has_iter;
        while true {
            let attrs =
                match attrs.next() {
                    Some(_x) => ::quote::__private::RepInterp(_x),
                    None => break,
                };
            ::quote::ToTokens::to_tokens(&attrs, &mut _s);
        }
    }
    ::quote::ToTokens::to_tokens(&inline_attr, &mut _s);
    ::quote::ToTokens::to_tokens(&vis, &mut _s);
    ::quote::ToTokens::to_tokens(&constness, &mut _s);
    ::quote::ToTokens::to_tokens(&asyncness, &mut _s);
    ::quote::ToTokens::to_tokens(&unsafety, &mut _s);
    ::quote::ToTokens::to_tokens(&abi, &mut _s);
    ::quote::ToTokens::to_tokens(&fn_token, &mut _s);
    ::quote::ToTokens::to_tokens(&ident, &mut _s);
    ::quote::ToTokens::to_tokens(&generics, &mut _s);
    ::quote::ToTokens::to_tokens(&args, &mut _s);
    ::quote::ToTokens::to_tokens(&arrow_token, &mut _s);
    ::quote::ToTokens::to_tokens(&to_type, &mut _s);
    ::quote::__private::push_group_spanned(&mut _s, _span,
        ::quote::__private::Delimiter::Brace,
        {
            let mut _s = ::quote::__private::TokenStream::new();
            let _span: ::quote::__private::Span =
                ::quote::__private::get_span(_span).__into_span();
            ::quote::__private::push_ident_spanned(&mut _s, _span, "let");
            ::quote::__private::push_underscore_spanned(&mut _s, _span);
            ::quote::__private::push_eq_spanned(&mut _s, _span);
            ::quote::__private::push_or_or_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    let _span: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::push_colon2_spanned(&mut _s, _span);
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "ref_cast");
                    ::quote::__private::push_colon2_spanned(&mut _s, _span);
                    ::quote::ToTokens::to_tokens(&private, &mut _s);
                    ::quote::__private::push_colon2_spanned(&mut _s, _span);
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "ref_cast_custom");
                    ::quote::__private::push_colon2_spanned(&mut _s, _span);
                    ::quote::__private::push_lt_spanned(&mut _s, _span);
                    ::quote::ToTokens::to_tokens(&from_type, &mut _s);
                    ::quote::__private::push_comma_spanned(&mut _s, _span);
                    ::quote::ToTokens::to_tokens(&to_type, &mut _s);
                    ::quote::__private::push_gt_spanned(&mut _s, _span);
                    ::quote::__private::push_group_spanned(&mut _s, _span,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            let _: ::quote::__private::Span =
                                ::quote::__private::get_span(_span).__into_span();
                            ::quote::ToTokens::to_tokens(&arg, &mut _s);
                            _s
                        });
                    ::quote::__private::push_semi_spanned(&mut _s, _span);
                    _s
                });
            ::quote::__private::push_semi_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span, "let");
            ::quote::__private::push_underscore_spanned(&mut _s, _span);
            ::quote::__private::push_eq_spanned(&mut _s, _span);
            ::quote::__private::push_colon2_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span,
                "ref_cast");
            ::quote::__private::push_colon2_spanned(&mut _s, _span);
            ::quote::ToTokens::to_tokens(&private, &mut _s);
            ::quote::__private::push_colon2_spanned(&mut _s, _span);
            ::quote::__private::push_ident_spanned(&mut _s, _span,
                "CurrentCrate");
            ::quote::__private::push_colon2_spanned(&mut _s, _span);
            ::quote::__private::push_lt_spanned(&mut _s, _span);
            ::quote::ToTokens::to_tokens(&from_type, &mut _s);
            ::quote::__private::push_comma_spanned(&mut _s, _span);
            ::quote::ToTokens::to_tokens(&to_type, &mut _s);
            ::quote::__private::push_gt_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Brace,
                {
                    let _: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::TokenStream::new()
                });
            ::quote::__private::push_semi_spanned(&mut _s, _span);
            ::quote::ToTokens::to_tokens(&allow_unused_unsafe, &mut _s);
            ::quote::__private::push_pound_spanned(&mut _s, _span);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Bracket,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    let _span: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "allow");
                    ::quote::__private::push_group_spanned(&mut _s, _span,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            let _span: ::quote::__private::Span =
                                ::quote::__private::get_span(_span).__into_span();
                            ::quote::__private::push_ident_spanned(&mut _s, _span,
                                "clippy");
                            ::quote::__private::push_colon2_spanned(&mut _s, _span);
                            ::quote::__private::push_ident_spanned(&mut _s, _span,
                                "transmute_ptr_to_ptr");
                            _s
                        });
                    _s
                });
            ::quote::ToTokens::to_tokens(&macro_generated_unsafe, &mut _s);
            ::quote::__private::push_group_spanned(&mut _s, _span,
                ::quote::__private::Delimiter::Brace,
                {
                    let mut _s = ::quote::__private::TokenStream::new();
                    let _span: ::quote::__private::Span =
                        ::quote::__private::get_span(_span).__into_span();
                    ::quote::__private::push_colon2_spanned(&mut _s, _span);
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "ref_cast");
                    ::quote::__private::push_colon2_spanned(&mut _s, _span);
                    ::quote::ToTokens::to_tokens(&private, &mut _s);
                    ::quote::__private::push_colon2_spanned(&mut _s, _span);
                    ::quote::__private::push_ident_spanned(&mut _s, _span,
                        "transmute");
                    ::quote::__private::push_colon2_spanned(&mut _s, _span);
                    ::quote::__private::push_lt_spanned(&mut _s, _span);
                    ::quote::ToTokens::to_tokens(&from_type, &mut _s);
                    ::quote::__private::push_comma_spanned(&mut _s, _span);
                    ::quote::ToTokens::to_tokens(&to_type, &mut _s);
                    ::quote::__private::push_gt_spanned(&mut _s, _span);
                    ::quote::__private::push_group_spanned(&mut _s, _span,
                        ::quote::__private::Delimiter::Parenthesis,
                        {
                            let mut _s = ::quote::__private::TokenStream::new();
                            let _: ::quote::__private::Span =
                                ::quote::__private::get_span(_span).__into_span();
                            ::quote::ToTokens::to_tokens(&arg, &mut _s);
                            _s
                        });
                    _s
                });
            _s
        });
    _s
}quote_spanned! {semi_token.span=>
382        #(#attrs)*
383        #inline_attr
384        #vis #constness #asyncness #unsafety #abi
385        #fn_token #ident #generics #args #arrow_token #to_type {
386            // check lifetime
387            let _ = || {
388                ::ref_cast::#private::ref_cast_custom::<#from_type, #to_type>(#arg);
389            };
390
391            // check same crate
392            let _ = ::ref_cast::#private::CurrentCrate::<#from_type, #to_type> {};
393
394            #allow_unused_unsafe // in case they are building with deny(unsafe_op_in_unsafe_fn)
395            #[allow(clippy::transmute_ptr_to_ptr)]
396            #macro_generated_unsafe {
397                ::ref_cast::#private::transmute::<#from_type, #to_type>(#arg)
398            }
399        }
400    }
401}
402
403fn check_repr(input: &DeriveInput) -> Result<()> {
404    let mut has_repr = false;
405    let mut errors = None;
406    let mut push_error = |error| match &mut errors {
407        Some(errors) => Error::combine(errors, error),
408        None => errors = Some(error),
409    };
410
411    for attr in &input.attrs {
412        if attr.path().is_ident("repr") {
413            if let Err(error) = attr.parse_args_with(|input: ParseStream| {
414                while !input.is_empty() {
415                    let path = input.call(Path::parse_mod_style)?;
416                    if path.is_ident("transparent") || path.is_ident("C") {
417                        has_repr = true;
418                    } else if path.is_ident("packed") {
419                        // ignore
420                    } else {
421                        let meta_item_span = if input.peek(token::Paren) {
422                            let group: TokenTree = input.parse()?;
423                            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&path, &mut _s);
    ::quote::ToTokens::to_tokens(&group, &mut _s);
    _s
}quote!(#path #group)
424                        } else if input.peek(::syn::token::EqToken![=]) {
425                            let eq_token: Token![=] = input.parse()?;
426                            let value: Expr = input.parse()?;
427                            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&path, &mut _s);
    ::quote::ToTokens::to_tokens(&eq_token, &mut _s);
    ::quote::ToTokens::to_tokens(&value, &mut _s);
    _s
}quote!(#path #eq_token #value)
428                        } else {
429                            {
    let mut _s = ::quote::__private::TokenStream::new();
    ::quote::ToTokens::to_tokens(&path, &mut _s);
    _s
}quote!(#path)
430                        };
431                        let msg = if path.is_ident("align") {
432                            "aligned repr on struct that implements RefCast is not supported"
433                        } else {
434                            "unrecognized repr on struct that implements RefCast"
435                        };
436                        push_error(Error::new_spanned(meta_item_span, msg));
437                    }
438                    if !input.is_empty() {
439                        input.parse::<Token![,]>()?;
440                    }
441                }
442                Ok(())
443            }) {
444                push_error(error);
445            }
446        }
447    }
448
449    if !has_repr {
450        let mut requires_repr = Error::new(
451            Span::call_site(),
452            "RefCast trait requires #[repr(transparent)]",
453        );
454        if let Some(errors) = errors {
455            requires_repr.combine(errors);
456        }
457        errors = Some(requires_repr);
458    }
459
460    match errors {
461        None => Ok(()),
462        Some(errors) => Err(errors),
463    }
464}
465
466type Fields = Punctuated<Field, Token![,]>;
467
468fn fields(input: &DeriveInput) -> Result<&Fields> {
469    use syn::Fields;
470
471    match &input.data {
472        Data::Struct(data) => match &data.fields {
473            Fields::Named(fields) => Ok(&fields.named),
474            Fields::Unnamed(fields) => Ok(&fields.unnamed),
475            Fields::Unit => Err(Error::new(
476                Span::call_site(),
477                "RefCast does not support unit structs",
478            )),
479        },
480        Data::Enum(_) => Err(Error::new(
481            Span::call_site(),
482            "RefCast does not support enums",
483        )),
484        Data::Union(_) => Err(Error::new(
485            Span::call_site(),
486            "RefCast does not support unions",
487        )),
488    }
489}
490
491fn only_field_ty(fields: &Fields) -> Result<&Type> {
492    let is_trivial = decide_trivial(fields)?;
493    let mut only_field = None;
494
495    for field in fields {
496        if !is_trivial(field)? {
497            if only_field.take().is_some() {
498                break;
499            }
500            only_field = Some(&field.ty);
501        }
502    }
503
504    only_field.ok_or_else(|| {
505        Error::new(
506            Span::call_site(),
507            "RefCast requires a struct with a single field",
508        )
509    })
510}
511
512fn trivial_fields(fields: &Fields) -> Result<Vec<&Type>> {
513    let is_trivial = decide_trivial(fields)?;
514    let mut trivial = Vec::new();
515
516    for field in fields {
517        if is_trivial(field)? {
518            trivial.push(&field.ty);
519        }
520    }
521
522    Ok(trivial)
523}
524
525fn decide_trivial(fields: &Fields) -> Result<fn(&Field) -> Result<bool>> {
526    for field in fields {
527        if is_explicit_trivial(field)? {
528            return Ok(is_explicit_trivial);
529        }
530    }
531    Ok(is_implicit_trivial)
532}
533
534#[allow(clippy::unnecessary_wraps)] // match signature of is_explicit_trivial
535fn is_implicit_trivial(field: &Field) -> Result<bool> {
536    match &field.ty {
537        Type::Tuple(ty) => Ok(ty.elems.is_empty()),
538        Type::Path(ty) => {
539            let ident = &ty.path.segments.last().unwrap().ident;
540            Ok(ident == "PhantomData" || ident == "PhantomPinned")
541        }
542        _ => Ok(false),
543    }
544}
545
546fn is_explicit_trivial(field: &Field) -> Result<bool> {
547    for attr in &field.attrs {
548        if attr.path().is_ident("trivial") {
549            attr.meta.require_path_only()?;
550            return Ok(true);
551        }
552    }
553    Ok(false)
554}