Skip to main content

qtbridge_gen/qt_gen_impl/qt_meta_gen/
meta_call_bridge_generator.rs

1use proc_macro2::TokenStream;
2use quote::{ToTokens, format_ident, quote};
3use syn::parse_quote;
4use syn::spanned::Spanned;
5
6use crate::utils::signature_utils::{get_return_type, get_typed_arg_ident, get_typed_args, get_typed_args_types};
7use crate::utils::type_utils::{ValuePassBy, get_type_pass, is_ref, remove_ref, remove_refs};
8
9/// Generates code to connect a Rust function to a metacall (e.g. signal or slot).
10pub struct MetaCallBridgeGenerator<'a> {
11    sig: &'a syn::Signature,
12}
13
14impl<'a> MetaCallBridgeGenerator<'a> {
15    pub fn new(sig: &'a syn::Signature) -> Self {
16        Self { sig }
17    }
18
19    fn input_types(&self) -> impl Iterator<Item = &'a syn::Type> {
20        get_typed_args_types(self.sig)
21    }
22
23    fn output_type(&self) -> Option<&'a syn::Type> {
24        get_return_type(&self.sig.output)
25    }
26
27    /// Return an iterator over the user argument types (refs stripped) for meta-type registration.
28    pub fn get_input_metatypes(&self) -> impl Iterator<Item = &'a syn::Type> {
29        self.input_types().map(remove_refs)
30    }
31
32    /// Return the user return type (refs stripped) for meta-type registration.
33    pub fn get_output_metatype(&self) -> Option<&'a syn::Type> {
34        self.output_type().map(remove_refs)
35    }
36
37    /// Generates bridge code for invoking a user-defined function from a metacall (e.g., slot invocation).
38    /// Handles unpacking and conversion of arguments and return values.
39    /// `fn_call` is the expression representing the call to the user-defined function.
40    ///
41    /// Returns a code block that:
42    /// - Defines references to the arguments.
43    /// - Stores intermediate variables to be passed to the Rust function.
44    /// - Invokes the Rust function (`fn_call`).
45    /// - Stores the result in the metacall parameter array if needed.
46    pub fn generate_bridge_metacall_to_user_fn(&self, mut fn_call: syn::ExprMethodCall) -> syn::Result<TokenStream> {
47        // Generate code: Cast arguments to the proper compatible type
48        let input_refs: Vec<_> = self.input_types().enumerate()
49            .map(|(idx, ty)| gen_input_ref(ty, idx))
50            .collect();
51        // Generate code: Convert the compatible type to the proper type
52        let input_vars: Vec<_> = self.input_types().enumerate()
53            .map(|(idx, ty)| gen_input_var(ty, idx))
54            .collect();
55        // Generate code: Make a reference if required
56        let input_pass: Vec<_> = self.input_types().enumerate()
57            .map(|(idx, ty)| gen_pass_expr(ty, idx))
58            .collect::<syn::Result<_>>()?;
59
60        // Append user provided arguments (if any) with arguments taken from the input signature.
61        fn_call.args.extend(input_pass);
62
63        // Invoke the Rust function. Store its result in argv[0] if the function returns a value.
64        let invoke_and_maybe_write_result = match self.output_type() {
65            Some(output) => {
66                let result_var = format_ident!("result");
67                let result_conv_var = format_ident!("result_conv");
68                let result_conv = gen_to_compatible(output, &result_var, &result_conv_var);
69                let output_ptr = gen_output_ptr(output);
70                let write_output = gen_write_output(&result_conv_var);
71                quote! {
72                    let #result_var = #fn_call;
73                    #result_conv
74                    #output_ptr
75                    #write_output
76                }
77            },
78            None => fn_call.to_token_stream(),
79        };
80
81        Ok(quote! {
82            #(#input_refs)*
83            #(#input_vars)*
84            #invoke_and_maybe_write_result
85        })
86    }
87
88    /// Generates the argv array for signal emission, converting args to their compatible types.
89    /// The generated code lives inside the user's own signature, so the arguments must be
90    /// referenced by the parameter names the user wrote.
91    pub fn generate_argv_setup_for_signals(&self) -> syn::Result<TokenStream> {
92        let args: Vec<_> = get_typed_args(self.sig).collect();
93        let argv_size = args.len() + 1;
94        let mut arg_vars = Vec::new();
95        let mut argv_arr_init = Vec::with_capacity(argv_size);
96
97        for (idx, arg) in args.iter().enumerate() {
98            let var_ident = arg_var_ident(idx);
99            let arg_ident = get_typed_arg_ident(arg)?;
100            let user_type_no_ref = remove_refs(&arg.ty);
101            let arg_ref = match get_type_pass(&arg.ty) {
102                ValuePassBy::Value => quote! { &#arg_ident },
103                _ => quote! { #arg_ident },
104            };
105            arg_vars.push(quote! {
106                let #var_ident = <#user_type_no_ref as QMetaTypeCompatible>::to_compatible(#arg_ref);
107            });
108            argv_arr_init.push(quote! { std::ptr::from_ref(&#var_ident).cast() });
109        }
110
111        Ok(quote! {
112            #(#arg_vars)*
113            let argv: [*const u8; #argv_size] = [
114                std::ptr::null(),   // No value return.
115                #(#argv_arr_init),*
116            ];
117        })
118    }
119}
120
121fn gen_input_ref(user_type: &syn::Type, idx: usize) -> syn::Stmt {
122    let user_type_no_ref = remove_refs(user_type);
123    let ref_ident = input_ref_ident(idx);
124    let inputs = get_inputs_ident();
125    parse_quote! {
126        let #ref_ident = unsafe {
127            #inputs[#idx]
128                .cast::<<#user_type_no_ref as QMetaTypeCompatible>::CompatibleType>()
129                .as_ref()
130        }.expect("Argument reference is null");
131    }
132}
133
134fn gen_input_var(user_type: &syn::Type, idx: usize) -> syn::Stmt {
135    let var_ident = arg_var_ident(idx);
136    let ref_ident = input_ref_ident(idx);
137    let user_type_no_ref = remove_refs(user_type);
138    parse_quote! {
139        let #var_ident = unsafe { <#user_type_no_ref as QMetaTypeCompatible>::from_compatible(#ref_ident) };
140    }
141}
142
143fn gen_pass_expr(user_type: &syn::Type, idx: usize) -> syn::Result<syn::Expr> {
144    let var_ident = arg_var_ident(idx);
145    match get_type_pass(user_type) {
146        ValuePassBy::Value => Ok(parse_quote! { #var_ident }),
147        ValuePassBy::Ref => Ok(parse_quote! { &#var_ident }),
148        ValuePassBy::MutRef =>
149            Err(syn::Error::new(user_type.span(),
150                "Arguments passed by mutable references are not supported")),
151    }
152}
153
154fn gen_to_compatible(user_type: &syn::Type, from: &syn::Ident, to: &syn::Ident) -> syn::Stmt {
155    let user_type_no_ref = remove_ref(user_type);
156    let ref_from = match is_ref(user_type) {
157        true => quote! { #from },
158        false => quote! { &#from },
159    };
160    parse_quote! {
161        let #to = <#user_type_no_ref as QMetaTypeCompatible>::to_compatible(#ref_from);
162    }
163}
164
165fn gen_output_ptr(user_type: &syn::Type) -> syn::Stmt {
166    let user_type_no_ref = remove_ref(user_type);
167    let outputs = get_outputs_ident();
168    parse_quote! {
169        let output_ptr: *mut <#user_type_no_ref as QMetaTypeCompatible>::CompatibleType = #outputs[0].cast();
170    }
171}
172
173fn gen_write_output(var_ident: &syn::Ident) -> syn::Expr {
174    parse_quote! {
175        unsafe { std::ptr::write(output_ptr, #var_ident) }
176    }
177}
178
179pub fn get_inputs_ident() -> syn::Ident {
180    format_ident!("inputs")
181}
182
183pub fn get_outputs_ident() -> syn::Ident {
184    format_ident!("outputs")
185}
186
187fn input_ref_ident(idx: usize) -> syn::Ident {
188    format_ident!("arg_{idx}_ref")
189}
190
191fn arg_var_ident(idx: usize) -> syn::Ident {
192    format_ident!("arg_{idx}_var")
193}