ic-wire-derive 0.34.4

Strict Serde layout projection for IC Wire schemas
Documentation
//! Consumer-owned field mappings for fixed Serde inspection.
use quote::{format_ident, quote};
use syn::{Data, DeriveInput, Fields, Path};

#[derive(Default)]
pub(super) struct Layout {
    pub project: Option<Path>,
    source: Option<Path>,
    pub feature: Option<syn::LitStr>,
}

impl Layout {
    pub fn parse(input: &DeriveInput) -> syn::Result<Self> {
        let mut layout = Self::default();
        for attr in input
            .attrs
            .iter()
            .filter(|a| a.path().is_ident("wire_schema"))
        {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("feature") && layout.feature.is_none() {
                    layout.feature = Some(meta.value()?.parse()?);
                    return Ok(());
                }
                let slot = if meta.path.is_ident("project") {
                    &mut layout.project
                } else if meta.path.is_ident("source") {
                    &mut layout.source
                } else {
                    return Err(meta.error("unsupported or duplicate schema option"));
                };
                if slot.is_some() {
                    return Err(meta.error("duplicate schema option"));
                }
                *slot = Some(meta.value()?.parse::<syn::LitStr>()?.parse()?);
                Ok(())
            })?;
            if attr.meta.require_list()?.tokens.is_empty() {
                return Err(syn::Error::new_spanned(attr, "expected a field projection"));
            }
        }
        if (layout.source.is_some() || layout.feature.is_some()) && layout.project.is_none() {
            return Err(syn::Error::new_spanned(
                input,
                "source and feature require a project trait",
            ));
        }
        Ok(layout)
    }

    pub fn field_projection(&self) -> Option<&Path> {
        self.project.as_ref().filter(|_| self.source.is_none())
    }

    pub fn mapping(
        &self,
        input: &DeriveInput,
        generics: &syn::Generics,
        owner: &Path,
    ) -> syn::Result<proc_macro2::TokenStream> {
        let Some(project) = &self.project else {
            return Ok(quote!());
        };
        let (imp, args, bounds) = generics.split_for_impl();
        let name = &input.ident;
        let Some(source) = &self.source else {
            return Ok(quote! {
                impl #imp #project for #name #args #bounds { type Layout = Self; }
            });
        };
        if !input.generics.params.is_empty() {
            return Err(syn::Error::new_spanned(
                &input.generics,
                "checked source layouts require a concrete declaration",
            ));
        }
        let check = match &input.data {
            Data::Struct(record) => {
                let Fields::Named(fields) = &record.fields else {
                    return Err(syn::Error::new_spanned(
                        name,
                        "expected a named source record",
                    ));
                };
                let names = fields.named.iter().map(|f| &f.ident);
                let types = fields.named.iter().map(|f| &f.ty);
                let vars: Vec<_> = (0..fields.named.len())
                    .map(|i| format_ident!("__wire_field_{i}"))
                    .collect();
                quote! {
                    let #source { #(#names: #vars),* } = stored;
                    #(check::<#types, _>(#vars);)*
                }
            }
            Data::Enum(item) => {
                let arms = item
                    .variants
                    .iter()
                    .map(|variant| {
                        let tag = &variant.ident;
                        match &variant.fields {
                            Fields::Unit => Ok(quote!(#source::#tag => ())),
                            Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
                                let ty = &fields.unnamed[0].ty;
                                Ok(quote!(#source::#tag(value) => check::<#ty, _>(value)))
                            }
                            _ => Err(syn::Error::new_spanned(
                                variant,
                                "expected a unit or newtype source variant",
                            )),
                        }
                    })
                    .collect::<syn::Result<Vec<_>>>()?;
                quote!(match stored { #(#arms),* })
            }
            Data::Union(_) => {
                return Err(syn::Error::new_spanned(name, "expected a record or enum"));
            }
        };
        Ok(quote! {
            impl #project for #source { type Layout = #name; }
                const _: fn(&#source) = |stored| {
                    fn check<L: #owner::typescript::Wire, T: #project<Layout = L>>(_: &T) {}
                    #check
                };
        })
    }
}