ic-wire-derive 0.34.9

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

// Only an unconditional, symmetric skip can describe a fixed positional record.
pub(super) fn skipped(field: &Field) -> bool {
    let mut attrs = field.attrs.iter().filter(|a| {
        let p = a.path();
        p.is_ident("serde") || p.is_ident("wire") || p.is_ident("wire_schema")
    });
    attrs.next().is_some_and(|a| {
        a.path().is_ident("serde") && a.parse_args::<syn::Ident>().is_ok_and(|id| id == "skip")
    }) && attrs.next().is_none()
}

fn serialized_fields(fields: &FieldsNamed, owner: &Path) -> syn::Result<Vec<(String, String)>> {
    fields
        .named
        .iter()
        .filter(|f| !skipped(f))
        .map(|field| {
            let rust = field
                .ident
                .as_ref()
                .expect("named field")
                .unraw()
                .to_string();
            let (rename, _) = super::member_attributes(&field.attrs, true, Some(owner))?;
            Ok((rust.clone(), rename.unwrap_or(rust)))
        })
        .collect()
}

pub(super) fn attest(
    input: &DeriveInput,
    fields: &FieldsNamed,
    owner: &Path,
) -> syn::Result<proc_macro2::TokenStream> {
    let fields = serialized_fields(fields, owner)?;
    let pairs = fields
        .iter()
        .map(|(rust, serialized)| quote!((#rust, #serialized)));
    let name = &input.ident;
    let (imp, args, bounds) = input.generics.split_for_impl();
    Ok(quote! {
        impl #imp #owner::WireFieldOrder for #name #args #bounds {
            const FIELDS: &'static [(&'static str, &'static str)] = &[#(#pairs),*];
        }
    })
}

fn check_order(
    fields: &FieldsNamed,
    source: &Path,
    owner: &Path,
) -> syn::Result<proc_macro2::TokenStream> {
    let fields = serialized_fields(fields, owner)?;
    let count = fields.len();
    let name_span = proc_macro2::Span::call_site();
    let support = quote!(#owner::typescript::__private);
    let checks = fields.iter().enumerate().map(|(i, (rust, serialized))| {
        let message = format!("source mirror field order mismatch at position {}: mirror field `{rust}` serialized as `{serialized}`", i + 1);
        let rust = syn::LitByteStr::new(rust.as_bytes(), name_span);
        let serialized = syn::LitByteStr::new(serialized.as_bytes(), name_span);
        quote! {
            const _: () = if let ::core::option::Option::Some(order) = ORDER {
                if #i >= order.len() || !::core::matches!(order[#i].0.as_bytes(), #rust) || !::core::matches!(order[#i].1.as_bytes(), #serialized) {
                    ::core::panic!("{}", #message);
                }
            };
        }
    });
    Ok(quote! {
        const _: () = {
            #[allow(unused_imports)]
            use #support::Unattested as _;
            const ORDER: ::core::option::Option<&[(&str, &str)]> = #support::SourceOrder::<#source>::ORDER;
            const _: () = if let ::core::option::Option::Some(order) = ORDER {
                assert!(order.len() == #count, "source mirror serialized field count mismatch");
            };
            #(#checks)*
        };
    })
}

#[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 mut order = quote!();
        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",
                    ));
                };
                order = check_order(fields, source, owner)?;
                let names = fields.named.iter().map(|f| &f.ident);
                let active = fields.named.iter().enumerate().filter(|(_, f)| !skipped(f));
                let vars: Vec<_> = (0..fields.named.len())
                    .map(|i| format_ident!("__wire_field_{i}"))
                    .collect();
                let checks = active.map(|(i, f)| {
                    let ty = &f.ty;
                    let var = &vars[i];
                    quote!(check::<#ty, _>(#var);)
                });
                quote! {
                    let #source { #(#names: #vars),* } = stored;
                    #(#checks)*
                }
            }
            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! {
            #order
            impl #project for #source { type Layout = #name; }
                const _: fn(&#source) = |stored| {
                    fn check<L: #owner::typescript::Wire, T: #project<Layout = L>>(_: &T) {}
                    #check
                };
        })
    }
}