Debian Codegraph @

third_party/rust/uniffi_macros/src/error.rs

raw
1 use proc_macro2::TokenStream;
2 use quote::quote;
3 use syn::{DeriveInput, Index};
4 use uniffi_meta::EnumShape;
5
6 use crate::{
7 enum_::{rich_error_ffi_converter_impl, variant_metadata, EnumItem},
8 ffiops,
9 util::{
10 chain, create_metadata_items, extract_docstring, ident_to_string, mod_path,
11 try_metadata_value_from_usize, AttributeSliceExt,
12 },
13 DeriveOptions,
14 };
15
16 pub fn expand_error(input: DeriveInput, options: DeriveOptions) -> syn::Result<TokenStream> {
17 let enum_item = EnumItem::new(input)?;
18 let ffi_converter_impl = error_ffi_converter_impl(&enum_item, &options)?;
19 let meta_static_var = options
20 .generate_metadata
21 .then(|| error_meta_static_var(&enum_item).unwrap_or_else(syn::Error::into_compile_error));
22
23 let variant_errors: TokenStream = enum_item
24 .enum_()
25 .variants
26 .iter()
27 .flat_map(|variant| {
28 chain(
29 variant.attrs.uniffi_attr_args_not_allowed_here(),
30 variant
31 .fields
32 .iter()
33 .flat_map(|field| field.attrs.uniffi_attr_args_not_allowed_here()),
34 )
35 })
36 .map(syn::Error::into_compile_error)
37 .collect();
38
39 Ok(quote! {
40 #ffi_converter_impl
41 #meta_static_var
42 #variant_errors
43 })
44 }
45
46 fn error_ffi_converter_impl(item: &EnumItem, options: &DeriveOptions) -> syn::Result<TokenStream> {
47 Ok(if item.is_flat_error() {
48 flat_error_ffi_converter_impl(item, options)
49 } else {
50 rich_error_ffi_converter_impl(item, options)
51 })
52 }
53
54 // FfiConverters for "flat errors"
55 //
56 // These are errors where we only lower the to_string() value, rather than any associated data.
57 // We lower the to_string() value unconditionally, whether the enum has associated data or not.
58 fn flat_error_ffi_converter_impl(item: &EnumItem, options: &DeriveOptions) -> TokenStream {
59 let name = item.name();
60 let ident = item.ident();
61 let lower_impl_spec = options.ffi_impl_header("Lower", ident);
62 let lift_impl_spec = options.ffi_impl_header("Lift", ident);
63 let type_id_impl_spec = options.ffi_impl_header("TypeId", ident);
64 let derive_ffi_traits = options.derive_ffi_traits(ident, &["LowerError", "ConvertError"]);
65 let mod_path = match mod_path() {
66 Ok(p) => p,
67 Err(e) => return e.into_compile_error(),
68 };
69
70 let lower_impl = {
71 let mut match_arms: Vec<_> = item
72 .enum_()
73 .variants
74 .iter()
75 .enumerate()
76 .map(|(i, v)| {
77 let v_ident = &v.ident;
78 let idx = Index::from(i + 1);
79 let write_string = ffiops::write(quote! { ::std::string::String });
80
81 quote! {
82 Self::#v_ident { .. } => {
83 ::uniffi::deps::bytes::BufMut::put_i32(buf, #idx);
84 #write_string(error_msg, buf);
85 }
86 }
87 })
88 .collect();
89 if item.is_non_exhaustive() {
90 match_arms.push(quote! {
91 _ => ::std::panic!("Unexpected variant in non-exhaustive enum"),
92 })
93 }
94
95 let lower = ffiops::lower_into_rust_buffer(quote! { Self });
96
97 quote! {
98 #[automatically_derived]
99 unsafe #lower_impl_spec {
100 type FfiType = ::uniffi::RustBuffer;
101
102 fn write(obj: Self, buf: &mut ::std::vec::Vec<u8>) {
103 let error_msg = ::std::string::ToString::to_string(&obj);
104 match obj { #(#match_arms)* }
105 }
106
107 fn lower(obj: Self) -> ::uniffi::RustBuffer {
108 #lower(obj)
109 }
110 }
111 }
112 };
113
114 let lift_impl = if item.generate_error_try_read() {
115 let match_arms = item.enum_().variants.iter().enumerate().map(|(i, v)| {
116 let v_ident = &v.ident;
117 let idx = Index::from(i + 1);
118
119 quote! {
120 #idx => Self::#v_ident,
121 }
122 });
123 let try_lift = ffiops::try_lift_from_rust_buffer(quote! { Self });
124 quote! {
125 #[automatically_derived]
126 unsafe #lift_impl_spec {
127 type FfiType = ::uniffi::RustBuffer;
128
129 fn try_read(buf: &mut &[::std::primitive::u8]) -> ::uniffi::deps::anyhow::Result<Self> {
130 ::std::result::Result::Ok(match ::uniffi::deps::bytes::Buf::get_i32(buf) {
131 #(#match_arms)*
132 v => ::uniffi::deps::anyhow::bail!("Invalid #ident enum value: {}", v),
133 })
134 }
135
136 fn try_lift(v: ::uniffi::RustBuffer) -> ::uniffi::deps::anyhow::Result<Self> {
137 #try_lift(v)
138 }
139 }
140 }
141 } else {
142 quote! {
143 // Lifting flat errors is not currently supported, but we still define the trait so
144 // that dicts containing flat errors don't cause compile errors (see ReturnOnlyDict in
145 // coverall.rs).
146 //
147 // Note: it would be better to not derive `Lift` for dictionaries containing flat
148 // errors, but getting the trait bounds and derived impls there would be much harder.
149 // For now, we just fail at runtime.
150 #[automatically_derived]
151 unsafe #lift_impl_spec {
152 type FfiType = ::uniffi::RustBuffer;
153
154 fn try_read(buf: &mut &[::std::primitive::u8]) -> ::uniffi::deps::anyhow::Result<Self> {
155 ::std::panic!("Can't lift flat errors")
156 }
157
158 fn try_lift(v: ::uniffi::RustBuffer) -> ::uniffi::deps::anyhow::Result<Self> {
159 ::std::panic!("Can't lift flat errors")
160 }
161 }
162 }
163 };
164
165 quote! {
166 #lower_impl
167 #lift_impl
168
169 #[automatically_derived]
170 #type_id_impl_spec {
171 const TYPE_ID_META: ::uniffi::MetadataBuffer = ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::TYPE_ENUM)
172 .concat_str(#mod_path)
173 .concat_str(#name);
174 }
175
176 #derive_ffi_traits
177 }
178 }
179
180 pub(crate) fn error_meta_static_var(item: &EnumItem) -> syn::Result<TokenStream> {
181 let name = item.name();
182 let module_path = mod_path()?;
183 let non_exhaustive = item.is_non_exhaustive();
184 let docstring = item.docstring();
185 let flat = item.is_flat_error();
186 let shape = EnumShape::Error { flat }.as_u8();
187 let mut metadata_expr = quote! {
188 ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::ENUM)
189 .concat_str(#module_path)
190 .concat_str(#name)
191 .concat_value(#shape)
192 .concat_bool(false) // discr_type: None
193 };
194 if flat {
195 metadata_expr.extend(flat_error_variant_metadata(item)?)
196 } else {
197 metadata_expr.extend(variant_metadata(item)?);
198 }
199 metadata_expr.extend(quote! {
200 .concat_bool(#non_exhaustive)
201 .concat_long_str(#docstring)
202 });
203 Ok(create_metadata_items("error", &name, metadata_expr, None))
204 }
205
206 pub fn flat_error_variant_metadata(item: &EnumItem) -> syn::Result<Vec<TokenStream>> {
207 let enum_ = item.enum_();
208 let variants_len =
209 try_metadata_value_from_usize(enum_.variants.len(), "UniFFI limits enums to 256 variants")?;
210 std::iter::once(Ok(quote! { .concat_value(#variants_len) }))
211 .chain(enum_.variants.iter().map(|v| {
212 let name = ident_to_string(&v.ident);
213 let docstring = extract_docstring(&v.attrs)?;
214 Ok(quote! {
215 .concat_str(#name)
216 .concat_long_str(#docstring)
217 })
218 }))
219 .collect()
220 }