Debian Codegraph @

third_party/rust/uniffi_macros/src/custom.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::util::{
6 create_metadata_items, either_attribute_arg, ident_to_string, kw, mod_path,
7 parse_comma_separated, UniffiAttributeArgs,
8 };
9 use proc_macro2::{Ident, TokenStream};
10 use quote::{quote, ToTokens};
11 use syn::{
12 braced,
13 parse::{Parse, ParseStream},
14 spanned::Spanned,
15 token::Brace,
16 Expr, ExprClosure, Pat, Token, Type,
17 };
18
19 pub struct CustomTypeArgs {
20 custom_type: Type,
21 uniffi_type: Type,
22 options: CustomTypeOptions,
23 }
24
25 impl Parse for CustomTypeArgs {
26 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
27 // Parse the custom / UniFFI type which are both required
28 let custom_type = input.parse()?;
29 input.parse::<Token![,]>()?;
30 let uniffi_type = input.parse()?;
31 let options = if input.peek(Token![,]) {
32 input.parse::<Token![,]>()?;
33
34 if input.peek(Brace) {
35 let content;
36 braced!(content in input);
37 content.parse()?
38 } else {
39 CustomTypeOptions::default()
40 }
41 } else {
42 CustomTypeOptions::default()
43 };
44 Ok(Self {
45 custom_type,
46 uniffi_type,
47 options,
48 })
49 }
50 }
51
52 /// Handle extra options for the custom type macro
53 #[derive(Default)]
54 pub struct CustomTypeOptions {
55 lower: Option<ConvertClosure>,
56 try_lift: Option<ConvertClosure>,
57 remote: Option<kw::remote>,
58 }
59
60 impl CustomTypeOptions {
61 fn is_remote(&self) -> bool {
62 self.remote.is_some()
63 }
64 }
65
66 impl Parse for CustomTypeOptions {
67 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
68 parse_comma_separated(input)
69 }
70 }
71
72 impl UniffiAttributeArgs for CustomTypeOptions {
73 fn parse_one(input: ParseStream<'_>) -> syn::Result<Self> {
74 let lookahead = input.lookahead1();
75 if lookahead.peek(kw::lower) {
76 input.parse::<kw::lower>()?;
77 input.parse::<Token![:]>()?;
78 Ok(Self {
79 lower: Some(input.parse()?),
80 ..Self::default()
81 })
82 } else if lookahead.peek(kw::try_lift) {
83 input.parse::<kw::try_lift>()?;
84 input.parse::<Token![:]>()?;
85 Ok(Self {
86 try_lift: Some(input.parse()?),
87 ..Self::default()
88 })
89 } else if lookahead.peek(kw::remote) {
90 Ok(Self {
91 remote: Some(input.parse()?),
92 ..Self::default()
93 })
94 } else {
95 Err(lookahead.error())
96 }
97 }
98
99 fn merge(self, other: Self) -> syn::Result<Self> {
100 Ok(Self {
101 lower: either_attribute_arg(self.lower, other.lower)?,
102 try_lift: either_attribute_arg(self.try_lift, other.try_lift)?,
103 remote: either_attribute_arg(self.remote, other.remote)?,
104 })
105 }
106 }
107
108 struct ConvertClosure {
109 closure: ExprClosure,
110 param_ident: Ident,
111 body: Expr,
112 }
113
114 impl ConvertClosure {
115 fn token_tuple(&self) -> (TokenStream, TokenStream) {
116 let ConvertClosure {
117 param_ident, body, ..
118 } = self;
119 (quote! { #param_ident }, quote! { #body })
120 }
121 }
122
123 impl Parse for ConvertClosure {
124 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
125 let closure: ExprClosure = input.parse()?;
126 if closure.inputs.len() != 1 {
127 return Err(syn::Error::new(
128 closure.inputs.span(),
129 "Expected exactly 1 argument",
130 ));
131 }
132 let param_ident = match closure.inputs.last().unwrap().clone() {
133 Pat::Ident(i) => Ok(i.ident),
134 Pat::Type(p) => match *p.pat {
135 Pat::Ident(i) => Ok(i.ident),
136 _ => Err(p.pat.span()),
137 },
138 input => Err(input.span()),
139 }
140 .map_err(|span| syn::Error::new(span, "Unexpected argument type"))?;
141 Ok(Self {
142 body: *closure.body.clone(),
143 closure,
144 param_ident,
145 })
146 }
147 }
148
149 impl ToTokens for ConvertClosure {
150 fn to_tokens(&self, tokens: &mut TokenStream) {
151 self.closure.to_tokens(tokens)
152 }
153 }
154
155 pub(crate) fn expand_custom_type(args: CustomTypeArgs) -> syn::Result<TokenStream> {
156 let CustomTypeArgs {
157 custom_type,
158 uniffi_type,
159 options,
160 } = args;
161
162 let name = match &custom_type {
163 Type::Path(p) => match p.path.get_ident() {
164 Some(i) => Ok(ident_to_string(i)),
165 None => Err("Custom types must only have one component"),
166 },
167 _ => Err("Custom types must be specified as simple idents"),
168 }
169 .map_err(|msg| syn::Error::new(custom_type.span(), msg))?;
170
171 let mod_path = mod_path()?;
172 let (impl_spec, derive_ffi_traits) = if options.is_remote() {
173 (
174 quote! { unsafe impl ::uniffi::FfiConverter<crate::UniFfiTag> for #custom_type },
175 quote! { ::uniffi::derive_ffi_traits!(local #custom_type); },
176 )
177 } else {
178 (
179 quote! { unsafe impl<UT> ::uniffi::FfiConverter<UT> for #custom_type },
180 quote! { ::uniffi::derive_ffi_traits!(blanket #custom_type); },
181 )
182 };
183
184 let (lower_param, lower_expr) = match options.lower {
185 Some(convert_closure) => convert_closure.token_tuple(),
186 None => (
187 quote! { val },
188 quote! { <#custom_type as Into<#uniffi_type>>::into(val) },
189 ),
190 };
191 let (try_lift, try_lift_expr) = match options.try_lift {
192 Some(convert_closure) => convert_closure.token_tuple(),
193 None => (
194 quote! { val },
195 quote! { Ok(<#uniffi_type as TryInto<#custom_type>>::try_into(val)?) },
196 ),
197 };
198
199 let docstring = ""; // todo...
200 let meta_static_var = custom_type_meta_static_var(&name, &uniffi_type, docstring)?;
201
202 Ok(quote! {
203 #[allow(non_camel_case_types)]
204 #impl_spec {
205 // Note: the UniFFI type needs to implement both `Lower` and `Lift'. We use the
206 // `Lower` trait to get the associated type `FfiType` and const `TYPE_ID_META`. These
207 // can't differ between `Lower` and `Lift`.
208 type FfiType = <#uniffi_type as ::uniffi::Lower<crate::UniFfiTag>>::FfiType;
209 fn lower(#lower_param: #custom_type ) -> Self::FfiType {
210 <#uniffi_type as ::uniffi::Lower<crate::UniFfiTag>>::lower(#lower_expr)
211 }
212
213 fn try_lift(v: Self::FfiType) -> ::uniffi::Result<#custom_type> {
214 let #try_lift = <#uniffi_type as ::uniffi::Lift<crate::UniFfiTag>>::try_lift(v)?;
215 #try_lift_expr
216 }
217
218 fn write(#lower_param: #custom_type, buf: &mut Vec<u8>) {
219 <#uniffi_type as ::uniffi::Lower<crate::UniFfiTag>>::write(#lower_expr, buf);
220 }
221
222 fn try_read(buf: &mut &[u8]) -> ::uniffi::Result<#custom_type> {
223 let #try_lift = <#uniffi_type as ::uniffi::Lift<crate::UniFfiTag>>::try_read(buf)?;
224 #try_lift_expr
225 }
226
227 const TYPE_ID_META: ::uniffi::MetadataBuffer = ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::TYPE_CUSTOM)
228 .concat_str(#mod_path)
229 .concat_str(#name)
230 .concat(<#uniffi_type as ::uniffi::TypeId<crate::UniFfiTag>>::TYPE_ID_META);
231 }
232
233 #derive_ffi_traits
234
235 #meta_static_var
236 })
237 }
238
239 pub struct CustomNewtypeArgs {
240 ident: Type,
241 uniffi_type: Type,
242 }
243
244 impl Parse for CustomNewtypeArgs {
245 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
246 let ident = input.parse()?;
247 input.parse::<Token![,]>()?;
248 let uniffi_type = input.parse()?;
249 Ok(Self { ident, uniffi_type })
250 }
251 }
252
253 // Generate TypeConverter implementation for a newtype
254 pub(crate) fn expand_custom_newtype(args: CustomNewtypeArgs) -> syn::Result<TokenStream> {
255 let CustomNewtypeArgs { ident, uniffi_type } = args;
256
257 Ok(quote! {
258 uniffi::custom_type!(#ident, #uniffi_type, {
259 lower: |obj| obj.0,
260 try_lift: |val| Ok(#ident(val)),
261 });
262 })
263 }
264
265 pub(crate) fn custom_type_meta_static_var(
266 name: &str,
267 builtin: &Type,
268 docstring: &str,
269 ) -> syn::Result<TokenStream> {
270 let module_path = mod_path()?;
271 let builtin = crate::ffiops::type_id_meta(builtin);
272 let metadata_expr = quote! {
273 ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::CUSTOM_TYPE)
274 .concat_str(#module_path)
275 .concat_str(#name)
276 .concat(#builtin)
277 .concat_long_str(#docstring)
278 };
279 Ok(create_metadata_items(
280 "custom_type",
281 name,
282 metadata_expr,
283 None,
284 ))
285 }