Skip to main content

qtbridge_gen/qt_gen_impl/qt_meta_gen/
qslot_info.rs

1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
3
4use proc_macro2::TokenStream;
5use quote::{ToTokens, quote};
6use syn::{spanned::Spanned, Ident, LitStr};
7use crate::utils::case_conv;
8use crate::function_with_attributes::{BlockOrSemi, FunctionWithAttributes};
9use crate::utils::parse_utils::{parse_name_value, partition_attr_by};
10use crate::utils::signature_utils::is_self_mut;
11use crate::meta_call_check::check_meta_call_signature;
12
13use crate::qt_gen_impl::qt_meta_gen;
14use crate::qt_gen_impl::qobject_macro_params::QObjectMacroParams;
15use qt_meta_gen::meta_call_bridge_generator;
16use meta_call_bridge_generator::MetaCallBridgeGenerator;
17use qt_meta_gen::traits::{ExpandTokens, QmlName};
18
19#[derive(Default)]
20struct QSlotMetaParams {
21    name: Option<syn::LitStr>,
22}
23
24pub struct QSlotInfo {
25    id: u32,                      // Id that will be used to identify a slot in the handler function.
26    meta_params: QSlotMetaParams, // Params extracted from qslot attribute
27    func: syn::ImplItemFn,        // Slot function
28    global_options: QObjectMacroParams,
29}
30
31impl QSlotInfo {
32    pub fn new(input: FunctionWithAttributes, id: u32, global_options: QObjectMacroParams) -> syn::Result<Self> {
33        Self::check_signature(&input.sig)?;
34
35        let (attrs, slot_attr) = partition_attr_by(input.attrs.clone(), Self::is_for_me);
36        let slot_attr = slot_attr
37            .ok_or_else(|| syn::Error::new(input.sig.span(), "qslot attribute was not found for the function"))?;
38
39        let BlockOrSemi::Block(block) = input.block else {
40            return Err(syn::Error::new(input.sig.span(), "qslot must contain brackets (with some code optionally)"));
41        };
42
43        let meta_params = get_qslot_meta_params(&slot_attr)?;
44
45        let func = syn::ImplItemFn {
46            attrs,
47            vis: input.vis,
48            defaultness: None,
49            sig: input.sig,
50            block,
51        };
52
53        Ok(QSlotInfo {
54            id,
55            meta_params,
56            func,
57            global_options,
58        })
59    }
60
61    pub fn is_for_me(attr: &syn::Attribute) -> bool {
62        attr.style == syn::AttrStyle::Outer && attr.path().is_ident("qslot")
63    }
64
65    pub fn is_mut(&self) -> bool {
66        is_self_mut(&self.func.sig)
67    }
68
69    pub fn id(&self) -> u32 {
70        self.id
71    }
72
73    /// Generate code for registration of the given slot in `DynamicMetaObjectBuilder`.
74    ///
75    /// For a slot defined as:
76    /// ```ignore
77    /// #[qslot]
78    /// pub fn do_something(&mut self, i: i32, s: &String) -> String {
79    ///     ...
80    /// }
81    /// ```
82    ///
83    /// the generated output would be:
84    /// ```ignore
85    /// meta_obj.as_mut().register_slot(
86    ///     "doSomething",
87    ///     &[<i32 as QMetaTypeCompatible>::compatible_qmetatype(), <String as QMetaTypeCompatible>::compatible_qmetatype()],
88    ///     &<String as QMetaTypeCompatible>::compatible_qmetatype());
89    /// ```
90    pub fn get_meta_registration_code(&self) -> syn::Result<TokenStream> {
91        let name = self.get_qml_name_span().0;
92        let id = &self.id;
93        let sig = &self.func.sig;
94
95        let bridge_generator = MetaCallBridgeGenerator::new(sig);
96        let input_meta_types = bridge_generator.get_input_metatypes()
97            .collect::<Vec<_>>();
98        let output_meta_types = bridge_generator.get_output_metatype();
99
100        let result_meta_type = output_meta_types
101            .map(|ty| quote!{ &<#ty as QMetaTypeCompatible>::compatible_qmetatype() })
102            .unwrap_or_else(|| quote! { &qtbridge::qtbridge_type_lib::QMetaType::default() });
103
104        let mutability = match self.is_mut() {
105            true => quote! { Mutable },
106            false => quote! { Immutable },
107        };
108
109        let register_slot = quote! {
110            meta_obj.as_mut().register_slot(
111                #name,
112                #id,
113                 &[#(<#input_meta_types as QMetaTypeCompatible>::compatible_qmetatype()),*],
114                #result_meta_type,
115                qtbridge::qtbridge_runtime::dynamicmetaobjectbuilder::Mutability::#mutability);
116        };
117
118        Ok(register_slot)
119    }
120
121    /// Generate code that goes to the dedicated arm of `match` operator in DispatchMetaCall::invoke_slot().
122    pub fn get_invoke_code(&self) -> syn::Result<TokenStream> {
123        let sig = &self.func.sig;
124        let method_ident = &sig.ident;
125
126        let bridge_generator = MetaCallBridgeGenerator::new(sig);
127
128        let fn_call = syn::parse_quote! {
129            self.#method_ident()
130        };
131        bridge_generator.generate_bridge_metacall_to_user_fn(fn_call)
132    }
133
134    fn check_signature(sign: &syn::Signature) -> syn::Result<()> {
135        check_meta_call_signature(sign)
136    }
137}
138
139fn get_qslot_meta_params(attr: &syn::Attribute) -> syn::Result<QSlotMetaParams> {
140    match &attr.meta {
141        syn::Meta::Path(_) => Ok(QSlotMetaParams::default()),
142        syn::Meta::List(meta_list) => match syn::parse2::<QSlotMetaParams>(meta_list.tokens.clone()) {
143            Ok(params) => Ok(params),
144            Err(err) => Err(syn::Error::new(err.span(),format!("Failed to parse qslot attribute parameters: {}", err))),
145        },
146        _ => Err(syn::Error::new(attr.meta.span(), "Unexpected format of qslot attributes"))
147    }
148}
149
150
151mod qslot_keywords {
152    syn::custom_keyword!(qml_name);
153}
154
155impl syn::parse::Parse for QSlotMetaParams {
156    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
157        let mut name = None;
158
159        while !input.is_empty() {
160            if input.peek(qslot_keywords::qml_name) {
161                name = Some(parse_name_value::<Ident, LitStr>(input)?.1);
162                // TODO: check charset of name?
163            }
164            else {
165                return Err(input.error("Unsupported qslot parameter attribute"));
166            }
167        }
168
169        Ok(Self{
170            name,
171        })
172    }
173}
174
175impl QmlName for QSlotInfo {
176    fn get_qml_name_span(&self) -> (String, proc_macro2::Span) {
177        if let Some(name) = self.meta_params.name.as_ref() {
178            (name.value(), name.span())
179        }
180        else if self.global_options.convert_to_camel_case {
181            let ident = &self.func.sig.ident;
182            (case_conv::snake_to_camel(&ident.to_string()), ident.span())
183        }
184        else {
185            (self.func.sig.ident.to_string(), self.func.sig.ident.span())
186        }
187    }
188}
189
190impl ExpandTokens for QSlotInfo {
191    fn expand_tokens(&self) -> syn::Result<TokenStream> {
192        Ok(self.func.to_token_stream())
193    }
194}