Skip to main content

qtbridge_gen/qt_gen_impl/
generate_qobject_holder.rs

1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
3
4use quote::{format_ident, quote};
5
6use crate::utils::case_conv;
7
8/// Generate the implementation of the `QObjectHolder` trait.
9pub fn generate_qobject_holder(
10    struct_ident: &syn::Ident,     // Name of struct that implements the given trait.
11    iface_ident: &syn::Ident,      // The name of the Qt-interface the struct is implementing
12    impl_generics: &syn::Generics, // All the generics added to the implementation and their clauses
13) -> syn::Result<syn::ItemImpl> {
14
15    let iface_name = iface_ident;
16    let iface_module = format_ident!("{}", case_conv::camel_to_snake(&iface_name.to_string()));
17    let proxy_rust = format_ident!("{iface_name}ProxyRust");
18
19    let has_generics = !impl_generics.params.is_empty();
20    let (impl_generics, type_generics, where_clause) = impl_generics.split_for_impl();
21
22    // Per-type OnceLock overrides of the map-based defaults; generic types
23    // cannot have per-instantiation statics and keep the defaults.
24    let realization_overrides = if has_generics {
25        quote! {}
26    } else {
27        quote! {
28            fn get_shared_dynamic_meta_object_data() -> &'static qtbridge::qtbridge_runtime::DynamicMetaObjectData {
29                use std::sync::OnceLock;
30                thread_local! {
31                    static DYNAMIC_META_OBJECT: OnceLock<&'static qtbridge::qtbridge_runtime::DynamicMetaObjectData> = OnceLock::new();
32                }
33
34                DYNAMIC_META_OBJECT.with(|cell| {
35                    *cell.get_or_init(|| {
36                        let ptr = Self::create_dynamic_meta_object_data_for_type();
37                        unsafe { ptr.as_ref() }.unwrap()
38                    })
39                })
40            }
41
42            fn get_qobject_ptr_qmetatype() -> qtbridge::qtbridge_type_lib::QMetaType {
43                use std::sync::OnceLock;
44                static PTR_META_TYPE_INTERFACE: OnceLock<qtbridge::qtbridge_type_lib::QMetaTypeInterface> = OnceLock::new();
45                let iface = PTR_META_TYPE_INTERFACE.get_or_init(qtbridge::qtbridge_runtime::qmetatypeforqobject::init_ptr_interface_for::<Self>);
46                qtbridge::qtbridge_type_lib::QMetaType::new_with_interface(iface)
47            }
48        }
49    };
50
51    let code = quote! {
52        unsafe impl #impl_generics qtbridge::qtbridge_runtime::QObjectHolder for #struct_ident #type_generics #where_clause {
53            type ProxyRust = qtbridge::qtbridge_interfaces::#iface_module::#proxy_rust;
54
55            #realization_overrides
56        }
57    };
58    syn::parse2(code)
59}
60