summaryrefslogtreecommitdiffstats
path: root/third_party/rust/uniffi_macros/src/export/scaffolding.rs
blob: f66e8bf84466410ac288dfeb2bb3e1e8bb1f61ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote, ToTokens};
use syn::{parse_quote, FnArg, Pat};

use super::{FunctionReturn, Signature};

pub(super) fn gen_fn_scaffolding(
    sig: &Signature,
    mod_path: &[String],
    checksum: u16,
) -> TokenStream {
    let name = &sig.ident;
    let name_s = name.to_string();

    let ffi_ident = Ident::new(
        &uniffi_meta::fn_ffi_symbol_name(mod_path, &name_s, checksum),
        Span::call_site(),
    );

    const ERROR_MSG: &str =
        "uniffi::export must be used on the impl block, not its containing fn's";
    let (params, args): (Vec<_>, Vec<_>) = collect_params(&sig.inputs, ERROR_MSG).unzip();

    let fn_call = quote! {
        #name(#(#args),*)
    };

    gen_ffi_function(sig, ffi_ident, &params, fn_call)
}

pub(super) fn gen_method_scaffolding(
    sig: &Signature,
    mod_path: &[String],
    checksum: u16,
    self_ident: &Ident,
) -> TokenStream {
    let name = &sig.ident;
    let name_s = name.to_string();

    let ffi_name = format!("impl_{self_ident}_{name_s}");
    let ffi_ident = Ident::new(
        &uniffi_meta::fn_ffi_symbol_name(mod_path, &ffi_name, checksum),
        Span::call_site(),
    );

    let mut params_args = (Vec::new(), Vec::new());

    const RECEIVER_ERROR: &str = "unreachable: only first parameter can be method receiver";
    let mut assoc_fn_error = None;
    let fn_call_prefix = match sig.inputs.first() {
        Some(arg) if is_receiver(arg) => {
            let ffi_converter = quote! {
                <::std::sync::Arc<#self_ident> as ::uniffi::FfiConverter>
            };

            params_args.0.push(quote! { this: #ffi_converter::FfiType });

            let remaining_args = sig.inputs.iter().skip(1);
            params_args.extend(collect_params(remaining_args, RECEIVER_ERROR));

            quote! {
                #ffi_converter::try_lift(this).unwrap_or_else(|err| {
                    ::std::panic!("Failed to convert arg 'self': {}", err)
                }).
            }
        }
        _ => {
            assoc_fn_error = Some(
                syn::Error::new_spanned(
                    &sig.ident,
                    "associated functions are not currently supported",
                )
                .into_compile_error(),
            );
            params_args.extend(collect_params(&sig.inputs, RECEIVER_ERROR));
            quote! { #self_ident:: }
        }
    };

    let (params, args) = params_args;

    let fn_call = quote! {
        #assoc_fn_error
        #fn_call_prefix #name(#(#args),*)
    };

    gen_ffi_function(sig, ffi_ident, &params, fn_call)
}

fn is_receiver(fn_arg: &FnArg) -> bool {
    match fn_arg {
        FnArg::Receiver(_) => true,
        FnArg::Typed(pat_ty) => matches!(&*pat_ty.pat, Pat::Ident(i) if i.ident == "self"),
    }
}

fn collect_params<'a>(
    inputs: impl IntoIterator<Item = &'a FnArg> + 'a,
    receiver_error_msg: &'static str,
) -> impl Iterator<Item = (TokenStream, TokenStream)> + 'a {
    fn receiver_error(
        receiver: impl ToTokens,
        receiver_error_msg: &str,
    ) -> (TokenStream, TokenStream) {
        let param = quote! { &self };
        let arg = syn::Error::new_spanned(receiver, receiver_error_msg).into_compile_error();
        (param, arg)
    }

    inputs.into_iter().enumerate().map(|(i, arg)| {
        let (ty, name) = match arg {
            FnArg::Receiver(r) => {
                return receiver_error(r, receiver_error_msg);
            }
            FnArg::Typed(pat_ty) => {
                let name = match &*pat_ty.pat {
                    Pat::Ident(i) if i.ident == "self" => {
                        return receiver_error(i, receiver_error_msg);
                    }
                    Pat::Ident(i) => Some(i.ident.to_string()),
                    _ => None,
                };

                (&pat_ty.ty, name)
            }
        };

        let arg_n = format_ident!("arg{i}");
        let param = quote! { #arg_n: <#ty as ::uniffi::FfiConverter>::FfiType };

        // FIXME: With UDL, fallible functions use uniffi::lower_anyhow_error_or_panic instead of
        // panicking unconditionally. This seems cleaner though.
        let panic_fmt = match name {
            Some(name) => format!("Failed to convert arg '{name}': {{}}"),
            None => format!("Failed to convert arg #{i}: {{}}"),
        };
        let arg = quote! {
            <#ty as ::uniffi::FfiConverter>::try_lift(#arg_n).unwrap_or_else(|err| {
                ::std::panic!(#panic_fmt, err)
            })
        };

        (param, arg)
    })
}

fn gen_ffi_function(
    sig: &Signature,
    ffi_ident: Ident,
    params: &[TokenStream],
    rust_fn_call: TokenStream,
) -> TokenStream {
    let name = &sig.ident;
    let name_s = name.to_string();

    let unit_slot;
    let (ty, throws) = match &sig.output {
        Some(FunctionReturn { ty, throws }) => (ty, throws),
        None => {
            unit_slot = parse_quote! { () };
            (&unit_slot, &None)
        }
    };

    let return_expr = if let Some(error_ident) = throws {
        quote! {
            ::uniffi::call_with_result(call_status, || {
                let val = #rust_fn_call.map_err(|e| {
                    <#error_ident as ::uniffi::FfiConverter>::lower(
                        ::std::convert::Into::into(e),
                    )
                })?;
                Ok(<#ty as ::uniffi::FfiReturn>::lower(val))
            })
        }
    } else {
        quote! {
            ::uniffi::call_with_output(call_status, || {
                <#ty as ::uniffi::FfiReturn>::lower(#rust_fn_call)
            })
        }
    };

    quote! {
        #[doc(hidden)]
        #[no_mangle]
        pub extern "C" fn #ffi_ident(
            #(#params,)*
            call_status: &mut ::uniffi::RustCallStatus,
        ) -> <#ty as ::uniffi::FfiReturn>::FfiType {
            ::uniffi::deps::log::debug!(#name_s);
            #return_expr
        }
    }
}