Debian Codegraph @

third_party/rust/uniffi_macros/src/enum_.rs

raw
1 use proc_macro2::{Ident, Span, TokenStream};
2 use quote::quote;
3 use syn::{
4 parse::ParseStream, spanned::Spanned, Attribute, Data, DataEnum, DeriveInput, Expr, Index, Lit,
5 Variant,
6 };
7
8 use crate::{
9 ffiops,
10 util::{
11 create_metadata_items, either_attribute_arg, extract_docstring, ident_to_string, kw,
12 mod_path, try_metadata_value_from_usize, try_read_field, AttributeSliceExt,
13 UniffiAttributeArgs,
14 },
15 DeriveOptions,
16 };
17 use uniffi_meta::EnumShape;
18
19 /// Stores parsed data from the Derive Input for the enum.
20 pub struct EnumItem {
21 ident: Ident,
22 enum_: DataEnum,
23 docstring: String,
24 discr_type: Option<Ident>,
25 non_exhaustive: bool,
26 attr: EnumAttr,
27 }
28
29 impl EnumItem {
30 pub fn new(input: DeriveInput) -> syn::Result<Self> {
31 let enum_ = match input.data {
32 Data::Enum(e) => e,
33 _ => {
34 return Err(syn::Error::new(
35 Span::call_site(),
36 "This derive must only be used on enums",
37 ))
38 }
39 };
40 Ok(Self {
41 enum_,
42 ident: input.ident,
43 docstring: extract_docstring(&input.attrs)?,
44 discr_type: Self::extract_repr(&input.attrs)?,
45 non_exhaustive: Self::extract_non_exhaustive(&input.attrs),
46 attr: input.attrs.parse_uniffi_attr_args()?,
47 })
48 }
49
50 pub fn extract_repr(attrs: &[Attribute]) -> syn::Result<Option<Ident>> {
51 let mut result = None;
52 for attr in attrs {
53 if attr.path().is_ident("repr") {
54 attr.parse_nested_meta(|meta| {
55 result = match meta.path.get_ident() {
56 Some(i) => {
57 let s = i.to_string();
58 match s.as_str() {
59 "u8" | "u16" | "u32" | "u64" | "usize" | "i8" | "i16" | "i32"
60 | "i64" | "isize" => Some(i.clone()),
61 // while the default repr for an enum is `isize` we don't apply that default here.
62 _ => None,
63 }
64 }
65 _ => None,
66 };
67 Ok(())
68 })?
69 }
70 }
71 Ok(result)
72 }
73
74 pub fn extract_non_exhaustive(attrs: &[Attribute]) -> bool {
75 attrs.iter().any(|a| a.path().is_ident("non_exhaustive"))
76 }
77
78 pub fn check_attributes_valid_for_enum(&self) -> syn::Result<()> {
79 if let Some(flat_error) = &self.attr.flat_error {
80 return Err(syn::Error::new(
81 flat_error.span(),
82 "flat_error not allowed for non-error enums",
83 ));
84 }
85 if let Some(with_try_read) = &self.attr.with_try_read {
86 return Err(syn::Error::new(
87 with_try_read.span(),
88 "with_try_read not allowed for non-error enums",
89 ));
90 }
91 Ok(())
92 }
93
94 pub fn ident(&self) -> &Ident {
95 &self.ident
96 }
97
98 pub fn enum_(&self) -> &DataEnum {
99 &self.enum_
100 }
101
102 pub fn is_non_exhaustive(&self) -> bool {
103 self.non_exhaustive
104 }
105
106 pub fn docstring(&self) -> &str {
107 self.docstring.as_str()
108 }
109
110 pub fn discr_type(&self) -> Option<&Ident> {
111 self.discr_type.as_ref()
112 }
113
114 pub fn name(&self) -> String {
115 ident_to_string(&self.ident)
116 }
117
118 pub fn is_flat_error(&self) -> bool {
119 self.attr.flat_error.is_some()
120 }
121
122 pub fn generate_error_try_read(&self) -> bool {
123 self.attr.with_try_read.is_some()
124 }
125 }
126
127 pub fn expand_enum(input: DeriveInput, options: DeriveOptions) -> syn::Result<TokenStream> {
128 let item = EnumItem::new(input)?;
129 item.check_attributes_valid_for_enum()?;
130 let ffi_converter_impl = enum_ffi_converter_impl(&item, &options);
131
132 let meta_static_var = options
133 .generate_metadata
134 .then(|| enum_meta_static_var(&item).unwrap_or_else(syn::Error::into_compile_error));
135
136 Ok(quote! {
137 #ffi_converter_impl
138 #meta_static_var
139 })
140 }
141
142 pub(crate) fn enum_ffi_converter_impl(item: &EnumItem, options: &DeriveOptions) -> TokenStream {
143 enum_or_error_ffi_converter_impl(
144 item,
145 options,
146 quote! { ::uniffi::metadata::codes::TYPE_ENUM },
147 )
148 }
149
150 pub(crate) fn rich_error_ffi_converter_impl(
151 item: &EnumItem,
152 options: &DeriveOptions,
153 ) -> TokenStream {
154 enum_or_error_ffi_converter_impl(
155 item,
156 options,
157 quote! { ::uniffi::metadata::codes::TYPE_ENUM },
158 )
159 }
160
161 fn enum_or_error_ffi_converter_impl(
162 item: &EnumItem,
163 options: &DeriveOptions,
164 metadata_type_code: TokenStream,
165 ) -> TokenStream {
166 let name = item.name();
167 let ident = item.ident();
168 let impl_spec = options.ffi_impl_header("FfiConverter", ident);
169 let derive_ffi_traits = options.derive_all_ffi_traits(ident);
170 let mod_path = match mod_path() {
171 Ok(p) => p,
172 Err(e) => return e.into_compile_error(),
173 };
174 let mut write_match_arms: Vec<_> = item
175 .enum_()
176 .variants
177 .iter()
178 .enumerate()
179 .map(|(i, v)| {
180 let v_ident = &v.ident;
181 let field_idents = v
182 .fields
183 .iter()
184 .enumerate()
185 .map(|(i, f)| {
186 f.ident
187 .clone()
188 .unwrap_or_else(|| Ident::new(&format!("e{i}"), f.span()))
189 })
190 .collect::<Vec<Ident>>();
191 let idx = Index::from(i + 1);
192 let write_fields =
193 std::iter::zip(v.fields.iter(), field_idents.iter()).map(|(f, ident)| {
194 let write = ffiops::write(&f.ty);
195 quote! { #write(#ident, buf); }
196 });
197 let is_tuple = v.fields.iter().any(|f| f.ident.is_none());
198 let fields = if is_tuple {
199 quote! { ( #(#field_idents),* ) }
200 } else {
201 quote! { { #(#field_idents),* } }
202 };
203
204 quote! {
205 Self::#v_ident #fields => {
206 ::uniffi::deps::bytes::BufMut::put_i32(buf, #idx);
207 #(#write_fields)*
208 }
209 }
210 })
211 .collect();
212 if item.is_non_exhaustive() {
213 write_match_arms.push(quote! {
214 _ => ::std::panic!("Unexpected variant in non-exhaustive enum"),
215 })
216 }
217 let write_impl = quote! {
218 match obj { #(#write_match_arms)* }
219 };
220
221 let try_read_match_arms = item.enum_().variants.iter().enumerate().map(|(i, v)| {
222 let idx = Index::from(i + 1);
223 let v_ident = &v.ident;
224 let is_tuple = v.fields.iter().any(|f| f.ident.is_none());
225 let try_read_fields = v.fields.iter().map(try_read_field);
226
227 if is_tuple {
228 quote! {
229 #idx => Self::#v_ident ( #(#try_read_fields)* ),
230 }
231 } else {
232 quote! {
233 #idx => Self::#v_ident { #(#try_read_fields)* },
234 }
235 }
236 });
237 let error_format_string = format!("Invalid {name} enum value: {{}}");
238 let try_read_impl = quote! {
239 ::uniffi::check_remaining(buf, 4)?;
240
241 ::std::result::Result::Ok(match ::uniffi::deps::bytes::Buf::get_i32(buf) {
242 #(#try_read_match_arms)*
243 v => ::uniffi::deps::anyhow::bail!(#error_format_string, v),
244 })
245 };
246
247 quote! {
248 #[automatically_derived]
249 unsafe #impl_spec {
250 ::uniffi::ffi_converter_rust_buffer_lift_and_lower!(crate::UniFfiTag);
251
252 fn write(obj: Self, buf: &mut ::std::vec::Vec<u8>) {
253 #write_impl
254 }
255
256 fn try_read(buf: &mut &[::std::primitive::u8]) -> ::uniffi::deps::anyhow::Result<Self> {
257 #try_read_impl
258 }
259
260 const TYPE_ID_META: ::uniffi::MetadataBuffer = ::uniffi::MetadataBuffer::from_code(#metadata_type_code)
261 .concat_str(#mod_path)
262 .concat_str(#name);
263 }
264
265 #derive_ffi_traits
266 }
267 }
268
269 pub(crate) fn enum_meta_static_var(item: &EnumItem) -> syn::Result<TokenStream> {
270 let name = item.name();
271 let module_path = mod_path()?;
272 let non_exhaustive = item.is_non_exhaustive();
273 let docstring = item.docstring();
274 let shape = EnumShape::Enum.as_u8();
275
276 let mut metadata_expr = quote! {
277 ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::ENUM)
278 .concat_str(#module_path)
279 .concat_str(#name)
280 .concat_value(#shape)
281 };
282 metadata_expr.extend(match item.discr_type() {
283 None => quote! { .concat_bool(false) },
284 Some(t) => {
285 let type_id_meta = ffiops::type_id_meta(t);
286 quote! { .concat_bool(true).concat(#type_id_meta) }
287 }
288 });
289 metadata_expr.extend(variant_metadata(item)?);
290 metadata_expr.extend(quote! {
291 .concat_bool(#non_exhaustive)
292 .concat_long_str(#docstring)
293 });
294 Ok(create_metadata_items("enum", &name, metadata_expr, None))
295 }
296
297 fn variant_value(v: &Variant) -> syn::Result<TokenStream> {
298 let Some((_, e)) = &v.discriminant else {
299 return Ok(quote! { .concat_bool(false) });
300 };
301 // Attempting to expose an enum value which we don't understand is a hard-error
302 // rather than silently ignoring it. If we had the ability to emit a warning that
303 // might make more sense.
304
305 // We can't sanely handle most expressions other than literals, but we can handle
306 // negative literals.
307 let mut negate = false;
308 let lit = match e {
309 Expr::Lit(lit) => lit,
310 Expr::Unary(expr_unary) if matches!(expr_unary.op, syn::UnOp::Neg(_)) => {
311 negate = true;
312 match *expr_unary.expr {
313 Expr::Lit(ref lit) => lit,
314 _ => {
315 return Err(syn::Error::new_spanned(
316 e,
317 "UniFFI disciminant values must be a literal",
318 ));
319 }
320 }
321 }
322 _ => {
323 return Err(syn::Error::new_spanned(
324 e,
325 "UniFFI disciminant values must be a literal",
326 ));
327 }
328 };
329 let Lit::Int(ref intlit) = lit.lit else {
330 return Err(syn::Error::new_spanned(
331 v,
332 "UniFFI disciminant values must be a literal integer",
333 ));
334 };
335 if !intlit.suffix().is_empty() {
336 return Err(syn::Error::new_spanned(
337 intlit,
338 "integer literals with suffix not supported by UniFFI here",
339 ));
340 }
341 let digits = if negate {
342 format!("-{}", intlit.base10_digits())
343 } else {
344 intlit.base10_digits().to_string()
345 };
346 Ok(quote! {
347 .concat_bool(true)
348 .concat_value(::uniffi::metadata::codes::LIT_INT)
349 .concat_str(#digits)
350 })
351 }
352
353 pub fn variant_metadata(item: &EnumItem) -> syn::Result<Vec<TokenStream>> {
354 let enum_ = item.enum_();
355 let variants_len =
356 try_metadata_value_from_usize(enum_.variants.len(), "UniFFI limits enums to 256 variants")?;
357 std::iter::once(Ok(quote! { .concat_value(#variants_len) }))
358 .chain(enum_.variants.iter().map(|v| {
359 let fields_len = try_metadata_value_from_usize(
360 v.fields.len(),
361 "UniFFI limits enum variants to 256 fields",
362 )?;
363
364 let field_names = v
365 .fields
366 .iter()
367 .map(|f| f.ident.as_ref().map(ident_to_string).unwrap_or_default())
368 .collect::<Vec<_>>();
369
370 let name = ident_to_string(&v.ident);
371 let value_tokens = variant_value(v)?;
372 let docstring = extract_docstring(&v.attrs)?;
373 let field_docstrings = v
374 .fields
375 .iter()
376 .map(|f| extract_docstring(&f.attrs))
377 .collect::<syn::Result<Vec<_>>>()?;
378 let field_type_id_metas = v.fields.iter().map(|f| ffiops::type_id_meta(&f.ty));
379
380 Ok(quote! {
381 .concat_str(#name)
382 #value_tokens
383 .concat_value(#fields_len)
384 #(
385 .concat_str(#field_names)
386 .concat(#field_type_id_metas)
387 // field defaults not yet supported for enums
388 .concat_bool(false)
389 .concat_long_str(#field_docstrings)
390 )*
391 .concat_long_str(#docstring)
392 })
393 }))
394 .collect()
395 }
396
397 /// Handle #[uniffi(...)] attributes for enums
398 #[derive(Clone, Default)]
399 pub struct EnumAttr {
400 // All of these attributes are only relevant for errors, but they're defined here so that we
401 // can reuse EnumItem for errors.
402 pub flat_error: Option<kw::flat_error>,
403 pub with_try_read: Option<kw::with_try_read>,
404 }
405
406 impl UniffiAttributeArgs for EnumAttr {
407 fn parse_one(input: ParseStream<'_>) -> syn::Result<Self> {
408 let lookahead = input.lookahead1();
409 if lookahead.peek(kw::flat_error) {
410 Ok(Self {
411 flat_error: input.parse()?,
412 ..Self::default()
413 })
414 } else if lookahead.peek(kw::with_try_read) {
415 Ok(Self {
416 with_try_read: input.parse()?,
417 ..Self::default()
418 })
419 } else if lookahead.peek(kw::handle_unknown_callback_error) {
420 // Not used anymore, but still allowed
421 Ok(Self::default())
422 } else {
423 Err(lookahead.error())
424 }
425 }
426
427 fn merge(self, other: Self) -> syn::Result<Self> {
428 Ok(Self {
429 flat_error: either_attribute_arg(self.flat_error, other.flat_error)?,
430 with_try_read: either_attribute_arg(self.with_try_read, other.with_try_read)?,
431 })
432 }
433 }