Debian Codegraph @

third_party/rust/uniffi_macros/src/fnsig.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use crate::{
6 default::{default_value_metadata_calls, DefaultValue},
7 export::{AsyncRuntime, DefaultMap, ExportFnArgs},
8 ffiops,
9 util::{create_metadata_items, ident_to_string, mod_path, try_metadata_value_from_usize},
10 };
11 use proc_macro2::{Span, TokenStream};
12 use quote::quote;
13 use syn::{spanned::Spanned, FnArg, Ident, Pat, Receiver, ReturnType, Type};
14
15 pub(crate) struct FnSignature {
16 pub kind: FnKind,
17 pub span: Span,
18 pub mod_path: String,
19 // The identifier of the Rust function.
20 pub ident: Ident,
21 // The foreign name for this function, usually == ident.
22 pub name: String,
23 pub is_async: bool,
24 pub async_runtime: Option<AsyncRuntime>,
25 pub receiver: Option<ReceiverArg>,
26 pub args: Vec<NamedArg>,
27 pub return_ty: TokenStream,
28 // Does this the return type look like a result?
29 // Only use this in UDL mode.
30 // In general, it's not reliable because it fails for type aliases.
31 pub looks_like_result: bool,
32 pub docstring: String,
33 }
34
35 impl FnSignature {
36 pub(crate) fn new_function(
37 sig: syn::Signature,
38 args: ExportFnArgs,
39 docstring: String,
40 ) -> syn::Result<Self> {
41 Self::new(FnKind::Function, sig, args, docstring)
42 }
43
44 pub(crate) fn new_method(
45 self_ident: Ident,
46 sig: syn::Signature,
47 args: ExportFnArgs,
48 docstring: String,
49 ) -> syn::Result<Self> {
50 Self::new(FnKind::Method { self_ident }, sig, args, docstring)
51 }
52
53 pub(crate) fn new_constructor(
54 self_ident: Ident,
55 sig: syn::Signature,
56 args: ExportFnArgs,
57 docstring: String,
58 ) -> syn::Result<Self> {
59 Self::new(FnKind::Constructor { self_ident }, sig, args, docstring)
60 }
61
62 pub(crate) fn new_trait_method(
63 self_ident: Ident,
64 sig: syn::Signature,
65 args: ExportFnArgs,
66 index: u32,
67 docstring: String,
68 ) -> syn::Result<Self> {
69 Self::new(
70 FnKind::TraitMethod { self_ident, index },
71 sig,
72 args,
73 docstring,
74 )
75 }
76
77 pub(crate) fn new(
78 kind: FnKind,
79 sig: syn::Signature,
80 mut export_fn_args: ExportFnArgs,
81 docstring: String,
82 ) -> syn::Result<Self> {
83 let span = sig.span();
84 let ident = sig.ident;
85 let looks_like_result = looks_like_result(&sig.output);
86 let output = match sig.output {
87 ReturnType::Default => quote! { () },
88 ReturnType::Type(_, ty) => quote! { #ty },
89 };
90 let is_async = sig.asyncness.is_some();
91
92 let mut input_iter = sig
93 .inputs
94 .into_iter()
95 .map(|a| Arg::new(a, &mut export_fn_args.defaults))
96 .peekable();
97
98 let receiver = input_iter
99 .next_if(|a| matches!(a, Ok(a) if a.is_receiver()))
100 .map(|a| match a {
101 Ok(Arg {
102 kind: ArgKind::Receiver(r),
103 ..
104 }) => r,
105 _ => unreachable!(),
106 });
107 let args = input_iter
108 .map(|a| {
109 a.and_then(|a| match a.kind {
110 ArgKind::Named(named) => Ok(named),
111 ArgKind::Receiver(_) => {
112 Err(syn::Error::new(a.span, "Unexpected receiver argument"))
113 }
114 })
115 })
116 .collect::<syn::Result<Vec<_>>>()?;
117
118 if let Some(ident) = export_fn_args.defaults.idents().first() {
119 return Err(syn::Error::new(
120 ident.span(),
121 format!("Unknown default argument: {}", ident),
122 ));
123 }
124
125 if !is_async && export_fn_args.async_runtime.is_some() {
126 return Err(syn::Error::new(
127 export_fn_args.async_runtime.span(),
128 "Function not async".to_string(),
129 ));
130 }
131
132 Ok(Self {
133 kind,
134 span,
135 mod_path: mod_path()?,
136 name: export_fn_args
137 .name
138 .unwrap_or_else(|| ident_to_string(&ident)),
139 ident,
140 is_async,
141 async_runtime: export_fn_args.async_runtime,
142 receiver,
143 args,
144 return_ty: output,
145 looks_like_result,
146 docstring,
147 })
148 }
149
150 /// Generate a closure that tries to lift all arguments into a tuple.
151 ///
152 /// The closure moves all scaffolding arguments into itself and returns:
153 /// - The lifted argument tuple on success
154 /// - The field name and error on failure (`Err(&'static str, anyhow::Error>`)
155 pub fn lift_closure(&self, self_lift: Option<TokenStream>) -> TokenStream {
156 let arg_lifts = self.args.iter().map(|arg| {
157 let ident = &arg.ident;
158 let try_lift = ffiops::try_lift(&arg.ty);
159 let name = &arg.name;
160 quote! {
161 match #try_lift(#ident) {
162 ::std::result::Result::Ok(v) => v,
163 ::std::result::Result::Err(e) => {
164 return ::std::result::Result::Err((#name, e))
165 }
166 }
167 }
168 });
169 let all_lifts = self_lift.into_iter().chain(arg_lifts);
170 quote! {
171 move || ::std::result::Result::Ok((
172 #(#all_lifts,)*
173 ))
174 }
175 }
176
177 /// Call a Rust function from a [Self::lift_closure] success.
178 ///
179 /// This takes an Ok value returned by `lift_closure` with the name `uniffi_args` and generates
180 /// a series of parameters to pass to the Rust function.
181 pub fn rust_call_params(&self, self_lift: bool) -> TokenStream {
182 let start_idx = if self_lift { 1 } else { 0 };
183 let args = self.args.iter().enumerate().map(|(i, arg)| {
184 let idx = syn::Index::from(i + start_idx);
185 let ty = &arg.ty;
186 match &arg.ref_type {
187 None => quote! { uniffi_args.#idx },
188 Some(ref_type) => quote! {
189 <#ty as ::std::borrow::Borrow<#ref_type>>::borrow(&uniffi_args.#idx)
190 },
191 }
192 });
193 quote! { #(#args),* }
194 }
195
196 /// Parameters expressions for each of our arguments
197 pub fn params(&self) -> impl Iterator<Item = TokenStream> + '_ {
198 self.args.iter().map(NamedArg::param)
199 }
200
201 /// Name of the scaffolding function to generate for this function
202 pub fn scaffolding_fn_ident(&self) -> syn::Result<Ident> {
203 let name = &self.name;
204 let name = match &self.kind {
205 FnKind::Function => uniffi_meta::fn_symbol_name(&self.mod_path, name),
206 FnKind::Method { self_ident } | FnKind::TraitMethod { self_ident, .. } => {
207 uniffi_meta::method_symbol_name(&self.mod_path, &ident_to_string(self_ident), name)
208 }
209 FnKind::Constructor { self_ident } => uniffi_meta::constructor_symbol_name(
210 &self.mod_path,
211 &ident_to_string(self_ident),
212 name,
213 ),
214 };
215 Ok(Ident::new(&name, Span::call_site()))
216 }
217
218 /// Scaffolding parameters expressions for each of our arguments
219 pub fn scaffolding_param_names(&self) -> impl Iterator<Item = TokenStream> + '_ {
220 self.args.iter().map(|a| {
221 let ident = &a.ident;
222 quote! { #ident }
223 })
224 }
225
226 pub fn scaffolding_param_types(&self) -> impl Iterator<Item = TokenStream> + '_ {
227 self.args.iter().map(|a| ffiops::lift_type(&a.ty))
228 }
229
230 /// Generate metadata items for this function
231 pub(crate) fn metadata_expr(&self) -> syn::Result<TokenStream> {
232 let Self {
233 name,
234 return_ty,
235 is_async,
236 mod_path,
237 docstring,
238 ..
239 } = &self;
240 let args_len = try_metadata_value_from_usize(
241 // Use param_lifts to calculate this instead of sig.inputs to avoid counting any self
242 // params
243 self.args.len(),
244 "UniFFI limits functions to 256 arguments",
245 )?;
246 let arg_metadata_calls = self
247 .args
248 .iter()
249 .map(NamedArg::arg_metadata)
250 .collect::<syn::Result<Vec<_>>>()?;
251
252 let type_id_meta = ffiops::type_id_meta(return_ty);
253
254 match &self.kind {
255 FnKind::Function => Ok(quote! {
256 ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::FUNC)
257 .concat_str(#mod_path)
258 .concat_str(#name)
259 .concat_bool(#is_async)
260 .concat_value(#args_len)
261 #(#arg_metadata_calls)*
262 .concat(#type_id_meta)
263 .concat_long_str(#docstring)
264 }),
265
266 FnKind::Method { self_ident } => {
267 let object_name = ident_to_string(self_ident);
268 Ok(quote! {
269 ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::METHOD)
270 .concat_str(#mod_path)
271 .concat_str(#object_name)
272 .concat_str(#name)
273 .concat_bool(#is_async)
274 .concat_value(#args_len)
275 #(#arg_metadata_calls)*
276 .concat(#type_id_meta)
277 .concat_long_str(#docstring)
278 })
279 }
280
281 FnKind::TraitMethod { self_ident, index } => {
282 let object_name = ident_to_string(self_ident);
283 Ok(quote! {
284 ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::TRAIT_METHOD)
285 .concat_str(#mod_path)
286 .concat_str(#object_name)
287 .concat_u32(#index)
288 .concat_str(#name)
289 .concat_bool(#is_async)
290 .concat_value(#args_len)
291 #(#arg_metadata_calls)*
292 .concat(#type_id_meta)
293 .concat_long_str(#docstring)
294 })
295 }
296
297 FnKind::Constructor { self_ident } => {
298 let object_name = ident_to_string(self_ident);
299 Ok(quote! {
300 ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::CONSTRUCTOR)
301 .concat_str(#mod_path)
302 .concat_str(#object_name)
303 .concat_str(#name)
304 .concat_bool(#is_async)
305 .concat_value(#args_len)
306 #(#arg_metadata_calls)*
307 .concat(#type_id_meta)
308 .concat_long_str(#docstring)
309 })
310 }
311 }
312 }
313
314 pub(crate) fn metadata_items(&self) -> syn::Result<TokenStream> {
315 let Self { name, .. } = &self;
316 match &self.kind {
317 FnKind::Function => Ok(create_metadata_items(
318 "func",
319 name,
320 self.metadata_expr()?,
321 Some(self.checksum_symbol_name()),
322 )),
323
324 FnKind::Method { self_ident } => {
325 let object_name = ident_to_string(self_ident);
326 Ok(create_metadata_items(
327 "method",
328 &format!("{object_name}_{name}"),
329 self.metadata_expr()?,
330 Some(self.checksum_symbol_name()),
331 ))
332 }
333
334 FnKind::TraitMethod { self_ident, .. } => {
335 let object_name = ident_to_string(self_ident);
336 Ok(create_metadata_items(
337 "method",
338 &format!("{object_name}_{name}"),
339 self.metadata_expr()?,
340 Some(self.checksum_symbol_name()),
341 ))
342 }
343
344 FnKind::Constructor { self_ident } => {
345 let object_name = ident_to_string(self_ident);
346 Ok(create_metadata_items(
347 "constructor",
348 &format!("{object_name}_{name}"),
349 self.metadata_expr()?,
350 Some(self.checksum_symbol_name()),
351 ))
352 }
353 }
354 }
355
356 pub(crate) fn checksum_symbol_name(&self) -> String {
357 let name = &self.name;
358 match &self.kind {
359 FnKind::Function => uniffi_meta::fn_checksum_symbol_name(&self.mod_path, name),
360 FnKind::Method { self_ident } | FnKind::TraitMethod { self_ident, .. } => {
361 uniffi_meta::method_checksum_symbol_name(
362 &self.mod_path,
363 &ident_to_string(self_ident),
364 name,
365 )
366 }
367 FnKind::Constructor { self_ident } => uniffi_meta::constructor_checksum_symbol_name(
368 &self.mod_path,
369 &ident_to_string(self_ident),
370 name,
371 ),
372 }
373 }
374 }
375
376 pub(crate) struct Arg {
377 pub(crate) span: Span,
378 pub(crate) kind: ArgKind,
379 }
380
381 pub(crate) enum ArgKind {
382 Receiver(ReceiverArg),
383 Named(NamedArg),
384 }
385
386 impl Arg {
387 fn new(syn_arg: FnArg, defaults: &mut DefaultMap) -> syn::Result<Self> {
388 let span = syn_arg.span();
389 let kind = match syn_arg {
390 FnArg::Typed(p) => match *p.pat {
391 Pat::Ident(i) => Ok(ArgKind::Named(NamedArg::new(i.ident, &p.ty, defaults)?)),
392 _ => Err(syn::Error::new_spanned(p, "Argument name missing")),
393 },
394 FnArg::Receiver(receiver) => Ok(ArgKind::Receiver(ReceiverArg::from(receiver))),
395 }?;
396
397 Ok(Self { span, kind })
398 }
399
400 pub(crate) fn is_receiver(&self) -> bool {
401 matches!(self.kind, ArgKind::Receiver(_))
402 }
403 }
404
405 pub(crate) enum ReceiverArg {
406 Ref,
407 Arc,
408 }
409
410 impl From<Receiver> for ReceiverArg {
411 fn from(receiver: Receiver) -> Self {
412 if let Type::Path(p) = *receiver.ty {
413 if let Some(segment) = p.path.segments.last() {
414 // This comparison will fail if a user uses a typedef for Arc. Maybe we could
415 // implement some system like TYPE_ID_META to figure this out from the type system.
416 // However, this seems good enough for now.
417 if segment.ident == "Arc" {
418 return ReceiverArg::Arc;
419 }
420 }
421 }
422 Self::Ref
423 }
424 }
425
426 pub(crate) struct NamedArg {
427 pub(crate) ident: Ident,
428 pub(crate) name: String,
429 pub(crate) ty: TokenStream,
430 pub(crate) ref_type: Option<Type>,
431 pub(crate) default: Option<DefaultValue>,
432 }
433
434 impl NamedArg {
435 pub(crate) fn new(ident: Ident, ty: &Type, defaults: &mut DefaultMap) -> syn::Result<Self> {
436 Ok(match ty {
437 Type::Reference(r) => {
438 let inner = &r.elem;
439 Self {
440 name: ident_to_string(&ident),
441 ty: ffiops::lift_ref_type(inner),
442 ref_type: Some(*inner.clone()),
443 default: defaults.remove(&ident),
444 ident,
445 }
446 }
447 _ => Self {
448 name: ident_to_string(&ident),
449 ty: quote! { #ty },
450 ref_type: None,
451 default: defaults.remove(&ident),
452 ident,
453 },
454 })
455 }
456
457 /// Generate the parameter for this Arg
458 pub(crate) fn param(&self) -> TokenStream {
459 let ident = &self.ident;
460 let ty = &self.ty;
461 quote! { #ident: #ty }
462 }
463
464 pub(crate) fn arg_metadata(&self) -> syn::Result<TokenStream> {
465 let name = &self.name;
466 let type_id_meta = ffiops::type_id_meta(&self.ty);
467 let default_calls = default_value_metadata_calls(&self.default)?;
468 Ok(quote! {
469 .concat_str(#name)
470 .concat(#type_id_meta)
471 #default_calls
472 })
473 }
474 }
475
476 fn looks_like_result(return_type: &ReturnType) -> bool {
477 if let ReturnType::Type(_, ty) = return_type {
478 if let Type::Path(p) = &**ty {
479 if let Some(seg) = p.path.segments.last() {
480 if seg.ident == "Result" {
481 return true;
482 }
483 }
484 }
485 }
486
487 false
488 }
489
490 #[derive(Debug)]
491 pub(crate) enum FnKind {
492 Function,
493 Constructor { self_ident: Ident },
494 Method { self_ident: Ident },
495 TraitMethod { self_ident: Ident, index: u32 },
496 }