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