Skip to main content

mln_wire_derive/
lib.rs

1//! `#[derive(Wire)]` for `mln_wire`: a struct's fields in order, or an
2//! enum's variant index and then its fields.
3//!
4//! Attributes:
5//!
6//! - `#[wire(bound = "...")]` on the type replaces the `T: Wire` bound that
7//!   each type parameter gets otherwise.
8//! - `#[wire(crate = path)]` on the type names the `mln_wire` crate by
9//!   `path`, for a macro that derives `Wire` in a crate it doesn't know.
10//!   Without it, the impl names `mln_wire` through the first of the
11//!   deriving package's dependencies that reaches it: `mln-rs-wire` itself,
12//!   `mln-rs-engine` or `mln-rs`, under the name the package gives it.
13//! - `#[wire(default)]` on a struct that implements `Default` reads it into
14//!   its default, one field after another. A struct literal of the fields
15//!   read drops those read so far at each place reading can fail, which
16//!   for a struct of many fields compiles to much more code. Its skipped
17//!   fields keep the struct's default.
18//! - `#[wire(with = "path")]` on a field writes it with `path::write(&field,
19//!   writer)` and reads it with `path::read(reader)`.
20//! - `#[wire(skip)]` on a field leaves it out; it reads as its `Default`, or
21//!   with `#[wire(skip, default = "path")]` as what `path()` returns.
22
23use proc_macro::TokenStream;
24use proc_macro_crate::{FoundCrate, crate_name};
25use proc_macro2::{Span, TokenStream as TokenStream2};
26use quote::{format_ident, quote};
27use syn::{Data, DeriveInput, Fields, Index, LitStr, Path, WherePredicate, parse_macro_input, parse_quote};
28
29#[proc_macro_derive(Wire, attributes(wire))]
30pub fn derive_wire(input: TokenStream) -> TokenStream {
31    let input = parse_macro_input!(input as DeriveInput);
32    match expand(&input) {
33        Ok(tokens) => tokens.into(),
34        Err(error) => error.to_compile_error().into(),
35    }
36}
37
38#[derive(Default)]
39struct FieldAttrs {
40    with: Option<Path>,
41    skip: bool,
42    default: Option<Path>,
43}
44
45fn field_attrs(attrs: &[syn::Attribute]) -> syn::Result<FieldAttrs> {
46    let mut result = FieldAttrs::default();
47    for attr in attrs.iter().filter(|attr| attr.path().is_ident("wire")) {
48        attr.parse_nested_meta(|meta| {
49            if meta.path.is_ident("with") {
50                let path: LitStr = meta.value()?.parse()?;
51                result.with = Some(path.parse()?);
52                Ok(())
53            } else if meta.path.is_ident("skip") {
54                result.skip = true;
55                Ok(())
56            } else if meta.path.is_ident("default") {
57                let path: LitStr = meta.value()?.parse()?;
58                result.default = Some(path.parse()?);
59                Ok(())
60            } else {
61                Err(meta.error("expected `with`, `skip` or `default`"))
62            }
63        })?;
64    }
65    Ok(result)
66}
67
68#[derive(Default)]
69struct ContainerAttrs {
70    bound: Option<Vec<WherePredicate>>,
71    default: bool,
72    krate: Option<Path>,
73}
74
75fn container_attrs(attrs: &[syn::Attribute]) -> syn::Result<ContainerAttrs> {
76    let mut result = ContainerAttrs::default();
77    for attr in attrs.iter().filter(|attr| attr.path().is_ident("wire")) {
78        attr.parse_nested_meta(|meta| {
79            if meta.path.is_ident("default") {
80                result.default = true;
81                Ok(())
82            } else if meta.path.is_ident("crate") {
83                result.krate = Some(meta.value()?.parse()?);
84                Ok(())
85            } else if meta.path.is_ident("bound") {
86                let bound: LitStr = meta.value()?.parse()?;
87                let predicates = if bound.value().trim().is_empty() {
88                    Vec::new()
89                } else {
90                    bound
91                        .parse_with(syn::punctuated::Punctuated::<WherePredicate, syn::Token![,]>::parse_terminated)?
92                        .into_iter()
93                        .collect()
94                };
95                result.bound = Some(predicates);
96                Ok(())
97            } else {
98                Err(meta.error("expected `bound`, `crate` or `default`"))
99            }
100        })?;
101    }
102    Ok(result)
103}
104
105/// The path of `mln_wire` from the package that derives `Wire`: its own
106/// dependency on `mln-rs-wire`, or the re-export of `mln-rs-engine` or
107/// `mln-rs`. `::mln_wire` where it depends on none of them, which the
108/// compiler then reports as a missing crate.
109fn wire_path() -> syn::Result<TokenStream2> {
110    // Each package, its library's name and the path of `mln_wire` in it.
111    const PATHS: [(&str, &str, &str); 3] = [
112        ("mln-rs-wire", "mln_wire", ""),
113        ("mln-rs-engine", "mln_engine", "::__private::mln_wire"),
114        ("mln-rs", "mln_rs", "::mln_engine::__private::mln_wire"),
115    ];
116    for (package, library, rest) in PATHS {
117        let name = match crate_name(package) {
118            // Not `crate`, which the package's tests and examples can't
119            // name it by.
120            Ok(FoundCrate::Itself) => library.to_owned(),
121            Ok(FoundCrate::Name(name)) => name,
122            Err(_) => continue,
123        };
124        let path: Path = syn::parse_str(&format!("::{name}{rest}"))?;
125        return Ok(quote! { #path });
126    }
127    Ok(quote! { ::mln_wire })
128}
129
130/// How a field is written, given an expression that borrows it.
131fn write_field(wire: &TokenStream2, attrs: &FieldAttrs, field: &TokenStream2) -> TokenStream2 {
132    if attrs.skip {
133        return quote! {};
134    }
135    if let Some(path) = &attrs.with {
136        quote! { #path::write(#field, w); }
137    } else {
138        quote! { #wire::Wire::write(#field, w); }
139    }
140}
141
142/// How a field is read: an expression of its value.
143fn read_field(wire: &TokenStream2, attrs: &FieldAttrs) -> TokenStream2 {
144    if attrs.skip {
145        return if let Some(default) = &attrs.default {
146            quote! { #default() }
147        } else {
148            quote! { ::core::default::Default::default() }
149        };
150    }
151    if let Some(path) = &attrs.with {
152        quote! { #path::read(r)? }
153    } else {
154        quote! { #wire::Wire::read(r)? }
155    }
156}
157
158/// The write statements and the read constructor of `fields`, whose values
159/// the write statements borrow through `bindings`.
160fn fields_code(
161    wire: &TokenStream2,
162    fields: &Fields,
163    bindings: &[TokenStream2],
164) -> syn::Result<(TokenStream2, TokenStream2)> {
165    let mut writes = Vec::new();
166    let mut reads = Vec::new();
167    for (field, binding) in fields.iter().zip(bindings) {
168        let attrs = field_attrs(&field.attrs)?;
169        writes.push(write_field(wire, &attrs, binding));
170        let read = read_field(wire, &attrs);
171        reads.push(match &field.ident {
172            Some(name) => quote! { #name: #read },
173            None => read,
174        });
175    }
176    let read = match fields {
177        Fields::Named(_) => quote! { { #(#reads,)* } },
178        Fields::Unnamed(_) => quote! { ( #(#reads,)* ) },
179        Fields::Unit => quote! {},
180    };
181    Ok((quote! { #(#writes)* }, read))
182}
183
184fn bindings(fields: &Fields) -> Vec<syn::Ident> {
185    fields.iter().enumerate().map(|(i, field)| field.ident.clone().unwrap_or_else(|| format_ident!("f{i}"))).collect()
186}
187
188fn pattern(fields: &Fields, bindings: &[syn::Ident]) -> TokenStream2 {
189    match fields {
190        Fields::Named(_) => quote! { { #(#bindings,)* } },
191        Fields::Unnamed(_) => quote! { ( #(#bindings,)* ) },
192        Fields::Unit => quote! {},
193    }
194}
195
196fn expand(input: &DeriveInput) -> syn::Result<TokenStream2> {
197    let name = &input.ident;
198    let mut generics = input.generics.clone();
199    let container = container_attrs(&input.attrs)?;
200    let wire = match &container.krate {
201        Some(path) => quote! { #path },
202        None => wire_path()?,
203    };
204    if let Some(predicates) = container.bound {
205        generics.make_where_clause().predicates.extend(predicates);
206    } else {
207        let params: Vec<_> = generics.type_params().map(|param| param.ident.clone()).collect();
208        let where_clause = generics.make_where_clause();
209        for param in params {
210            where_clause.predicates.push(parse_quote! { #param: #wire::Wire });
211        }
212    }
213    let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
214
215    let (write, read) = match &input.data {
216        Data::Struct(data) => {
217            let bindings: Vec<TokenStream2> = data
218                .fields
219                .iter()
220                .enumerate()
221                .map(|(i, field)| {
222                    if let Some(name) = &field.ident {
223                        quote! { &self.#name }
224                    } else {
225                        let index = Index::from(i);
226                        quote! { &self.#index }
227                    }
228                })
229                .collect();
230            let (write, read) = fields_code(&wire, &data.fields, &bindings)?;
231            if container.default {
232                let mut reads = Vec::new();
233                for (i, field) in data.fields.iter().enumerate() {
234                    let attrs = field_attrs(&field.attrs)?;
235                    if attrs.skip {
236                        continue;
237                    }
238                    let member = if let Some(name) = &field.ident {
239                        quote! { #name }
240                    } else {
241                        let index = Index::from(i);
242                        quote! { #index }
243                    };
244                    reads.push(if attrs.with.is_some() {
245                        let read = read_field(&wire, &attrs);
246                        quote! { value.#member = #read; }
247                    } else {
248                        quote! { #wire::read_into(&mut value.#member, r)?; }
249                    });
250                }
251                let read = quote! {
252                    let mut value: Self = ::core::default::Default::default();
253                    #(#reads)*
254                    ::core::option::Option::Some(value)
255                };
256                (write, read)
257            } else {
258                (write, quote! { ::core::option::Option::Some(Self #read) })
259            }
260        }
261        Data::Enum(data) => {
262            let mut tag_arms = Vec::new();
263            let mut write_arms = Vec::new();
264            let mut read_arms = Vec::new();
265            let unit_only = data.variants.iter().all(|variant| matches!(variant.fields, Fields::Unit));
266            for (index, variant) in data.variants.iter().enumerate() {
267                let index =
268                    u32::try_from(index).map_err(|_| syn::Error::new(Span::call_site(), "too many variants"))?;
269                let variant_name = &variant.ident;
270                let names = bindings(&variant.fields);
271                let pattern = pattern(&variant.fields, &names);
272                let borrowed: Vec<TokenStream2> = names.iter().map(|name| quote! { #name }).collect();
273                let (write, read) = fields_code(&wire, &variant.fields, &borrowed)?;
274                let ignore = match &variant.fields {
275                    Fields::Named(_) => quote! { { .. } },
276                    Fields::Unnamed(_) => quote! { (..) },
277                    Fields::Unit => quote! {},
278                };
279                tag_arms.push(quote! { Self::#variant_name #ignore => #index, });
280                if !write.is_empty() {
281                    write_arms.push(quote! { Self::#variant_name #pattern => { #write } });
282                }
283                read_arms.push(quote! { #index => ::core::option::Option::Some(Self::#variant_name #read), });
284            }
285            // The tag is written once, after a match that only finds it.
286            let write = if data.variants.is_empty() {
287                quote! { match *self {} }
288            } else if write_arms.is_empty() {
289                quote! { #wire::write_tag(w, match self { #(#tag_arms)* }); }
290            } else {
291                quote! {
292                    #wire::write_tag(w, match self { #(#tag_arms)* });
293                    #[allow(unreachable_patterns)]
294                    match self { #(#write_arms)* _ => {} }
295                }
296            };
297            // A fieldless enum is read from a table of its variants.
298            let read = if unit_only && !data.variants.is_empty() && input.generics.params.is_empty() {
299                let variants = data.variants.iter().map(|variant| &variant.ident);
300                quote! {
301                    const VARIANTS: &[#name] = &[#(#name::#variants),*];
302                    match VARIANTS.get(r.tag()? as usize) {
303                        ::core::option::Option::Some(variant) => ::core::option::Option::Some(::core::clone::Clone::clone(variant)),
304                        ::core::option::Option::None => r.fail_tag(),
305                    }
306                }
307            } else {
308                quote! {
309                    match r.tag()? {
310                        #(#read_arms)*
311                        _ => r.fail_tag(),
312                    }
313                }
314            };
315            (write, read)
316        }
317        Data::Union(_) => return Err(syn::Error::new(Span::call_site(), "unions can't derive Wire")),
318    };
319
320    Ok(quote! {
321        #[automatically_derived]
322        impl #impl_generics #wire::Wire for #name #type_generics #where_clause {
323            #[allow(unused_variables)]
324            fn write(&self, w: &mut #wire::Writer) {
325                #write
326            }
327
328            #[allow(unused_variables)]
329            fn read(r: &mut #wire::Reader<'_>) -> ::core::option::Option<Self> {
330                #read
331            }
332        }
333    })
334}