Debian Codegraph @

third_party/rust/uniffi_macros/src/export.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 proc_macro2::TokenStream;
6 use quote::{quote, quote_spanned};
7 use syn::{visit_mut::VisitMut, Item, Type};
8
9 mod attributes;
10 mod callback_interface;
11 mod item;
12 mod scaffolding;
13 mod trait_interface;
14 mod utrait;
15
16 use self::{
17 item::{ExportItem, ImplItem},
18 scaffolding::{
19 gen_constructor_scaffolding, gen_ffi_function, gen_fn_scaffolding, gen_method_scaffolding,
20 },
21 };
22 use crate::util::{create_metadata_items, ident_to_string, mod_path};
23 pub use attributes::{AsyncRuntime, DefaultMap, ExportFnArgs};
24 pub use callback_interface::ffi_converter_callback_interface_impl;
25
26 // TODO(jplatte): Ensure no generics, …
27 // TODO(jplatte): Aggregate errors instead of short-circuiting, wherever possible
28
29 pub(crate) fn expand_export(
30 mut item: Item,
31 all_args: proc_macro::TokenStream,
32 udl_mode: bool,
33 ) -> syn::Result<TokenStream> {
34 let mod_path = mod_path()?;
35 // If the input is an `impl` block, rewrite any uses of the `Self` type
36 // alias to the actual type, so we don't have to special-case it in the
37 // metadata collection or scaffolding code generation (which generates
38 // new functions outside of the `impl`).
39 rewrite_self_type(&mut item);
40
41 let metadata = ExportItem::new(item, all_args)?;
42
43 match metadata {
44 ExportItem::Function { sig, args } => {
45 gen_fn_scaffolding(sig, args.async_runtime.as_ref(), udl_mode)
46 }
47 ExportItem::Impl {
48 items,
49 self_ident,
50 args,
51 trait_,
52 } => {
53 if let Some(rt) = &args.async_runtime {
54 if items
55 .iter()
56 .all(|item| !matches!(item, ImplItem::Method(sig) if sig.is_async))
57 {
58 return Err(syn::Error::new_spanned(
59 rt,
60 "no async methods in this impl block",
61 ));
62 }
63 }
64
65 let item_tokens: TokenStream = items
66 .into_iter()
67 .map(|item| match item {
68 ImplItem::Constructor(sig) => {
69 let async_runtime =
70 sig.async_runtime.clone().or(args.async_runtime.clone());
71 gen_constructor_scaffolding(sig, async_runtime.as_ref(), udl_mode)
72 }
73 ImplItem::Method(sig) => {
74 let async_runtime =
75 sig.async_runtime.clone().or(args.async_runtime.clone());
76 gen_method_scaffolding(sig, async_runtime.as_ref(), udl_mode)
77 }
78 })
79 .collect::<syn::Result<_>>()?;
80 let trait_impl_tokens = trait_.map(|t| {
81 let object_name = ident_to_string(&self_ident);
82 // TODO: parse trait path?
83 let trait_name = ident_to_string(t.get_ident().expect("not a simple trait path"));
84 let trait_path = "";
85 let metadata_expr = quote! {
86 ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::OBJECT_TRAIT_IMPL)
87 .concat(::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::TYPE_INTERFACE))
88 .concat_str(#mod_path)
89 .concat_str(#object_name)
90 .concat_str(#trait_name)
91 .concat_str(#trait_path)
92 };
93 create_metadata_items(
94 "object_trait_impl",
95 &format!("{object_name}_{trait_name}"),
96 metadata_expr,
97 None,
98 )
99 });
100 Ok(quote_spanned! { self_ident.span() => #item_tokens #trait_impl_tokens })
101 }
102 ExportItem::Trait {
103 items,
104 self_ident,
105 with_foreign,
106 callback_interface_only: false,
107 docstring,
108 args,
109 } => trait_interface::gen_trait_scaffolding(
110 &mod_path,
111 args,
112 self_ident,
113 items,
114 udl_mode,
115 with_foreign,
116 docstring,
117 ),
118 ExportItem::Trait {
119 items,
120 self_ident,
121 callback_interface_only: true,
122 docstring,
123 ..
124 } => {
125 let trait_name = ident_to_string(&self_ident);
126 let trait_impl_ident = callback_interface::trait_impl_ident(&trait_name);
127 let trait_impl = callback_interface::trait_impl(&mod_path, &self_ident, &items)
128 .unwrap_or_else(|e| e.into_compile_error());
129 let metadata_items = (!udl_mode).then(|| {
130 let items =
131 callback_interface::metadata_items(&self_ident, &items, &mod_path, docstring)
132 .unwrap_or_else(|e| vec![e.into_compile_error()]);
133 quote! { #(#items)* }
134 });
135 let ffi_converter_tokens =
136 ffi_converter_callback_interface_impl(&self_ident, &trait_impl_ident);
137
138 Ok(quote! {
139 #trait_impl
140
141 #ffi_converter_tokens
142
143 #metadata_items
144 })
145 }
146 ExportItem::Struct {
147 self_ident,
148 uniffi_traits,
149 ..
150 } => {
151 assert!(!udl_mode);
152 utrait::expand_uniffi_trait_export(self_ident, uniffi_traits)
153 }
154 }
155 }
156
157 /// Rewrite Self type alias usage in an impl block to the type itself.
158 ///
159 /// For example,
160 ///
161 /// ```ignore
162 /// impl some::module::Foo {
163 /// fn method(
164 /// self: Arc<Self>,
165 /// arg: Option<Bar<(), Self>>,
166 /// ) -> Result<Self, Error> {
167 /// todo!()
168 /// }
169 /// }
170 /// ```
171 ///
172 /// will be rewritten to
173 ///
174 /// ```ignore
175 /// impl some::module::Foo {
176 /// fn method(
177 /// self: Arc<some::module::Foo>,
178 /// arg: Option<Bar<(), some::module::Foo>>,
179 /// ) -> Result<some::module::Foo, Error> {
180 /// todo!()
181 /// }
182 /// }
183 /// ```
184 pub fn rewrite_self_type(item: &mut Item) {
185 let item = match item {
186 Item::Impl(i) => i,
187 _ => return,
188 };
189
190 struct RewriteSelfVisitor<'a>(&'a Type);
191
192 impl VisitMut for RewriteSelfVisitor<'_> {
193 fn visit_type_mut(&mut self, i: &mut Type) {
194 match i {
195 Type::Path(p) if p.qself.is_none() && p.path.is_ident("Self") => {
196 *i = self.0.clone();
197 }
198 _ => syn::visit_mut::visit_type_mut(self, i),
199 }
200 }
201 }
202
203 let mut visitor = RewriteSelfVisitor(&item.self_ty);
204 for item in &mut item.items {
205 visitor.visit_impl_item_mut(item);
206 }
207 }