glib_macros/
shared_boxed_derive.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use proc_macro2::{Ident, TokenStream};
4use quote::quote;
5
6use crate::utils::{crate_ident_new, parse_nested_meta_items, NestedMetaItem};
7
8fn gen_impl_to_value_optional(name: &Ident, crate_ident: &TokenStream) -> TokenStream {
9    let refcounted_type_prefix = refcounted_type_prefix(name, crate_ident);
10
11    quote! {
12        impl #crate_ident::value::ToValueOptional for #name {
13            #[inline]
14            fn to_value_optional(s: ::core::option::Option<&Self>) -> #crate_ident::Value {
15                let mut value = #crate_ident::Value::for_value_type::<Self>();
16                unsafe {
17                    let ptr = match s {
18                        ::core::option::Option::Some(s) => #refcounted_type_prefix::into_raw(s.0.clone()),
19                        ::core::option::Option::None => ::std::ptr::null(),
20                    };
21
22                    #crate_ident::gobject_ffi::g_value_take_boxed(
23                        #crate_ident::translate::ToGlibPtrMut::to_glib_none_mut(&mut value).0,
24                        ptr as *mut _
25                    );
26                }
27
28                value
29            }
30        }
31
32        impl #crate_ident::value::ValueTypeOptional for #name { }
33    }
34}
35
36fn gen_impl_from_value_optional(name: &Ident, crate_ident: &TokenStream) -> TokenStream {
37    let refcounted_type_prefix = refcounted_type_prefix(name, crate_ident);
38
39    quote! {
40        unsafe impl<'a> #crate_ident::value::FromValue<'a> for #name {
41            type Checker = #crate_ident::value::GenericValueTypeOrNoneChecker<Self>;
42
43            #[inline]
44            unsafe fn from_value(value: &'a #crate_ident::Value) -> Self {
45                let ptr = #crate_ident::gobject_ffi::g_value_dup_boxed(#crate_ident::translate::ToGlibPtr::to_glib_none(value).0);
46                debug_assert!(!ptr.is_null());
47                #name(#refcounted_type_prefix::from_raw(ptr as *mut _))
48            }
49        }
50    }
51}
52
53fn gen_impl_from_value(name: &Ident, crate_ident: &TokenStream) -> TokenStream {
54    let refcounted_type_prefix = refcounted_type_prefix(name, crate_ident);
55
56    quote! {
57        unsafe impl<'a> #crate_ident::value::FromValue<'a> for #name {
58            type Checker = #crate_ident::value::GenericValueTypeChecker<Self>;
59
60            #[inline]
61            unsafe fn from_value(value: &'a #crate_ident::Value) -> Self {
62                let ptr = #crate_ident::gobject_ffi::g_value_dup_boxed(#crate_ident::translate::ToGlibPtr::to_glib_none(value).0);
63                debug_assert!(!ptr.is_null());
64                #name(#refcounted_type_prefix::from_raw(ptr as *mut _))
65            }
66        }
67    }
68}
69
70fn refcounted_type(input: &syn::DeriveInput) -> Option<&syn::TypePath> {
71    let fields = match &input.data {
72        syn::Data::Struct(s) => &s.fields,
73        _ => return None,
74    };
75
76    let unnamed = match fields {
77        syn::Fields::Unnamed(u) if u.unnamed.len() == 1 => &u.unnamed[0],
78        _ => return None,
79    };
80
81    let refcounted = match &unnamed.ty {
82        syn::Type::Path(p) => p,
83        _ => return None,
84    };
85
86    Some(refcounted)
87}
88
89fn refcounted_type_prefix(name: &Ident, crate_ident: &TokenStream) -> proc_macro2::TokenStream {
90    quote! {
91        <<#name as #crate_ident::subclass::shared::SharedType>::RefCountedType as #crate_ident::subclass::shared::RefCounted>
92    }
93}
94
95pub fn impl_shared_boxed(input: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
96    let name = &input.ident;
97
98    let Some(refcounted_type) = refcounted_type(input) else {
99        return Err(syn::Error::new_spanned(
100            input,
101            "#[derive(glib::SharedBoxed)] requires struct MyStruct(T: RefCounted)",
102        ));
103    };
104
105    let mut gtype_name = NestedMetaItem::<syn::LitStr>::new("name")
106        .required()
107        .value_required();
108    let mut nullable = NestedMetaItem::<syn::LitBool>::new("nullable").value_optional();
109    let mut allow_name_conflict =
110        NestedMetaItem::<syn::LitBool>::new("allow_name_conflict").value_optional();
111
112    let found = parse_nested_meta_items(
113        &input.attrs,
114        "shared_boxed_type",
115        &mut [&mut gtype_name, &mut nullable, &mut allow_name_conflict],
116    )?;
117
118    if found.is_none() {
119        return Err(syn::Error::new_spanned(input,
120            "#[derive(glib::SharedBoxed)] requires #[shared_boxed_type(name = \"SharedBoxedTypeName\")]"
121        ));
122    }
123
124    let gtype_name = gtype_name.value.unwrap();
125    let nullable = nullable.found || nullable.value.map(|b| b.value()).unwrap_or(false);
126    let allow_name_conflict = allow_name_conflict.found
127        || allow_name_conflict
128            .value
129            .map(|b| b.value())
130            .unwrap_or(false);
131
132    let crate_ident = crate_ident_new();
133    let refcounted_type_prefix = refcounted_type_prefix(name, &crate_ident);
134
135    let impl_from_value = if !nullable {
136        gen_impl_from_value(name, &crate_ident)
137    } else {
138        gen_impl_from_value_optional(name, &crate_ident)
139    };
140
141    let impl_to_value_optional = if nullable {
142        gen_impl_to_value_optional(name, &crate_ident)
143    } else {
144        quote! {}
145    };
146
147    Ok(quote! {
148        impl #crate_ident::subclass::shared::SharedType for #name {
149            const NAME: &'static ::core::primitive::str = #gtype_name;
150            const ALLOW_NAME_CONFLICT: bool = #allow_name_conflict;
151
152            type RefCountedType = #refcounted_type;
153
154            #[inline]
155            fn from_refcounted(this: Self::RefCountedType) -> Self {
156                Self(this)
157            }
158
159            #[inline]
160            fn into_refcounted(self) -> Self::RefCountedType {
161                self.0
162            }
163        }
164
165        impl #crate_ident::prelude::StaticType for #name {
166            #[inline]
167            fn static_type() -> #crate_ident::Type {
168                static TYPE: ::std::sync::OnceLock<#crate_ident::Type> = ::std::sync::OnceLock::new();
169                *TYPE.get_or_init(|| {
170                    #crate_ident::subclass::shared::register_shared_type::<#name>()
171                })
172            }
173        }
174
175        impl #crate_ident::value::ValueType for #name {
176            type Type = #name;
177        }
178
179        impl #crate_ident::value::ToValue for #name {
180            #[inline]
181            fn to_value(&self) -> #crate_ident::Value {
182                unsafe {
183                    let ptr = #refcounted_type_prefix::into_raw(self.0.clone());
184                    let mut value = #crate_ident::Value::from_type_unchecked(<#name as #crate_ident::prelude::StaticType>::static_type());
185                    #crate_ident::gobject_ffi::g_value_take_boxed(
186                        #crate_ident::translate::ToGlibPtrMut::to_glib_none_mut(&mut value).0,
187                        ptr as *mut _
188                    );
189                    value
190                }
191            }
192
193            #[inline]
194            fn value_type(&self) -> #crate_ident::Type {
195                <#name as #crate_ident::prelude::StaticType>::static_type()
196            }
197        }
198
199        impl ::std::convert::From<#name> for #crate_ident::Value {
200            #[inline]
201            fn from(v: #name) -> Self {
202                unsafe {
203                    let mut value = #crate_ident::Value::from_type_unchecked(<#name as #crate_ident::prelude::StaticType>::static_type());
204                    #crate_ident::gobject_ffi::g_value_take_boxed(
205                        #crate_ident::translate::ToGlibPtrMut::to_glib_none_mut(&mut value).0,
206                        #crate_ident::translate::IntoGlibPtr::<*mut #refcounted_type_prefix::InnerType>::into_glib_ptr(v) as *mut _,
207                    );
208                    value
209                }
210            }
211        }
212
213        #impl_to_value_optional
214
215        #impl_from_value
216
217        impl #crate_ident::translate::GlibPtrDefault for #name {
218            type GlibType = *mut #refcounted_type_prefix::InnerType;
219        }
220
221        impl #crate_ident::translate::FromGlibPtrBorrow<*const #refcounted_type_prefix::InnerType> for #name {
222            #[inline]
223            unsafe fn from_glib_borrow(ptr: *const #refcounted_type_prefix::InnerType) -> #crate_ident::translate::Borrowed<Self> {
224                debug_assert!(!ptr.is_null());
225
226                // from_raw is taking ownership of the raw pointer here, but wrapping its result
227                // in Borrowed::new ensures that it won't be deallocated when it will go out of
228                // scope, so the pointer will still be valid afterwards
229                #crate_ident::translate::Borrowed::new(#name(#refcounted_type_prefix::from_raw(ptr)))
230            }
231        }
232
233        impl #crate_ident::translate::FromGlibPtrBorrow<*mut #refcounted_type_prefix::InnerType> for #name {
234            #[inline]
235            unsafe fn from_glib_borrow(ptr: *mut #refcounted_type_prefix::InnerType) -> #crate_ident::translate::Borrowed<Self> {
236                #crate_ident::translate::FromGlibPtrBorrow::from_glib_borrow(ptr as *const _)
237            }
238        }
239
240
241        impl #crate_ident::translate::FromGlibPtrNone<*const #refcounted_type_prefix::InnerType> for #name {
242            #[inline]
243            unsafe fn from_glib_none(ptr: *const #refcounted_type_prefix::InnerType) -> Self {
244                let ptr = #refcounted_type_prefix::ref_(ptr);
245                #name(#refcounted_type_prefix::from_raw(ptr))
246            }
247        }
248
249        impl #crate_ident::translate::FromGlibPtrNone<*mut #refcounted_type_prefix::InnerType> for #name {
250            #[inline]
251            unsafe fn from_glib_none(ptr: *mut #refcounted_type_prefix::InnerType) -> Self {
252                #crate_ident::translate::FromGlibPtrNone::from_glib_none(ptr as *const _)
253            }
254        }
255
256        impl #crate_ident::translate::FromGlibPtrFull<*mut #refcounted_type_prefix::InnerType> for #name {
257            #[inline]
258            unsafe fn from_glib_full(ptr: *mut #refcounted_type_prefix::InnerType) -> Self {
259                #name(#refcounted_type_prefix::from_raw(ptr))
260            }
261        }
262
263        impl #crate_ident::translate::IntoGlibPtr<*mut #refcounted_type_prefix::InnerType> for #name {
264            #[inline]
265            unsafe fn into_glib_ptr(self) -> *mut #refcounted_type_prefix::InnerType {
266                let r = <Self as #crate_ident::subclass::shared::SharedType>::into_refcounted(self);
267                #refcounted_type_prefix::into_raw(r) as *mut _
268            }
269        }
270
271        impl<'a> #crate_ident::translate::ToGlibPtr<'a, *const #refcounted_type_prefix::InnerType> for #name {
272            type Storage = std::marker::PhantomData<&'a Self>;
273
274            #[inline]
275            fn to_glib_none(&'a self) -> #crate_ident::translate::Stash<'a, *const #refcounted_type_prefix::InnerType, Self> {
276                unsafe {
277                    #crate_ident::translate::Stash(#refcounted_type_prefix::as_ptr(&self.0), std::marker::PhantomData)
278                }
279            }
280
281            #[inline]
282            fn to_glib_full(&self) -> *const #refcounted_type_prefix::InnerType {
283                let r = <#name as #crate_ident::subclass::shared::SharedType>::into_refcounted(self.clone());
284                unsafe {
285                    #refcounted_type_prefix::into_raw(r)
286                }
287            }
288        }
289
290        impl<'a> #crate_ident::translate::ToGlibPtr<'a, *mut #refcounted_type_prefix::InnerType> for #name {
291            type Storage = std::marker::PhantomData<&'a Self>;
292
293            #[inline]
294            fn to_glib_none(&'a self) -> #crate_ident::translate::Stash<'a, *mut #refcounted_type_prefix::InnerType, Self> {
295                unsafe {
296                    #crate_ident::translate::Stash(#refcounted_type_prefix::as_ptr(&self.0) as *mut _, std::marker::PhantomData)
297                }
298            }
299
300            #[inline]
301            fn to_glib_full(&self) -> *mut #refcounted_type_prefix::InnerType {
302                let r = <#name as #crate_ident::subclass::shared::SharedType>::into_refcounted(self.clone());
303                unsafe {
304                    #refcounted_type_prefix::into_raw(r) as *mut _
305                }
306            }
307        }
308
309        impl #crate_ident::HasParamSpec for #name {
310            type ParamSpec = #crate_ident::ParamSpecBoxed;
311            type SetValue = Self;
312            type BuilderFn = fn(&::core::primitive::str) -> #crate_ident::ParamSpecBoxedBuilder<Self>;
313
314            fn param_spec_builder() -> Self::BuilderFn {
315                |name| Self::ParamSpec::builder(name)
316            }
317        }
318    })
319}