icedwright-probe-macros 0.1.3

Derives for icedwright-probe: typed test ids and the Messages variant table
Documentation
//! `#[derive(TestId)]`.

use std::collections::BTreeMap;

use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::{Data, DeriveInput, Fields, Ident, LitStr, Variant};

use crate::attrs::{crate_path, not_enum_span};
use crate::case::kebab;
use crate::format::{Piece, invalid_char, parse};

pub(crate) fn expand(input: &DeriveInput) -> syn::Result<TokenStream> {
    let Data::Enum(data) = &input.data else {
        return Err(syn::Error::new(
            not_enum_span(&input.data),
            "`TestId` can only be derived for an enum; give each id a variant",
        ));
    };
    let krate = crate_path(&input.attrs)?;
    let name = &input.ident;

    let mut seen: BTreeMap<String, Ident> = BTreeMap::new();
    let mut errors: Option<syn::Error> = None;
    let mut id_arms = Vec::new();
    let mut path_arms = Vec::new();
    let mut qualified_arms = Vec::new();
    for variant in &data.variants {
        match variant_arm(variant, &krate) {
            Ok((key, arm)) => {
                if let Some(first) = seen.get(&key) {
                    push(
                        &mut errors,
                        syn::Error::new_spanned(
                            &variant.ident,
                            format!("test id \"{key}\" is already used by `{first}`"),
                        ),
                    );
                }
                seen.entry(key).or_insert_with(|| variant.ident.clone());
                id_arms.push(arm);
            }
            Err(error) => push(&mut errors, error),
        }
        let ident = &variant.ident;
        let rust_path = format!("{name}::{ident}");
        path_arms.push(quote!(Self::#ident { .. } => #rust_path,));
        let suffix = format!("::{rust_path}");
        qualified_arms.push(quote! {
            Self::#ident { .. } => ::core::concat!(::core::module_path!(), #suffix),
        });
    }
    if let Some(error) = errors {
        return Err(error);
    }

    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
    Ok(quote! {
        #[automatically_derived]
        impl #impl_generics #krate::TestId for #name #ty_generics #where_clause {
            fn test_id(&self) -> #krate::__private::Cow<'static, str> {
                match *self {
                    #(#id_arms)*
                }
            }

            fn rust_path(&self) -> &'static str {
                match *self {
                    #(#path_arms)*
                }
            }

            fn qualified_path(&self) -> &'static str {
                match *self {
                    #(#qualified_arms)*
                }
            }
        }
    })
}

fn push(errors: &mut Option<syn::Error>, error: syn::Error) {
    match errors {
        Some(existing) => existing.combine(error),
        None => *errors = Some(error),
    }
}

/// The variant's id template, used to spot duplicates, and its match arm.
fn variant_arm(variant: &Variant, krate: &syn::Path) -> syn::Result<(String, TokenStream)> {
    let ident = &variant.ident;
    let attribute = template_attr(variant)?;

    let Some(template) = attribute else {
        if !matches!(variant.fields, Fields::Unit) {
            return Err(syn::Error::new_spanned(
                ident,
                format!(
                    "variant `{ident}` has fields, so it needs a format string such as \
                     `#[test_id(\"{}-{{0}}\")]`",
                    kebab(&ident.to_string())
                ),
            ));
        }
        let id = kebab(&ident.to_string());
        if let Some(bad) = invalid_char(&id) {
            return Err(syn::Error::new_spanned(
                ident,
                format!(
                    "the test id \"{id}\" from `{ident}` contains {bad:?}; set one with \
                     `#[test_id(\"...\")]`"
                ),
            ));
        }
        let arm = quote!(Self::#ident => #krate::__private::Cow::Borrowed(#id),);
        return Ok((id, arm));
    };

    let text = template.value();
    let pieces = parse(&text).map_err(|message| syn::Error::new(template.span(), message))?;
    if pieces.is_empty() {
        return Err(syn::Error::new(
            template.span(),
            "a test id cannot be empty",
        ));
    }
    for piece in &pieces {
        let Piece::Literal(literal) = piece else {
            continue;
        };
        if let Some(bad) = invalid_char(literal) {
            return Err(syn::Error::new(
                template.span(),
                format!("test ids may contain only `a-z`, `0-9`, `.`, `_` and `-`; found {bad:?}"),
            ));
        }
    }

    let fields = field_names(&variant.fields);
    let mut used = vec![false; fields.len()];
    let mut rewritten = String::new();
    for piece in &pieces {
        match piece {
            Piece::Literal(literal) => {
                rewritten.push_str(&literal.replace('{', "{{").replace('}', "}}"));
            }
            Piece::Field { name, spec } => {
                let Some(position) = fields.iter().position(|field| field == name) else {
                    return Err(syn::Error::new(
                        template.span(),
                        format!("`{{{name}}}` names no field of `{ident}`"),
                    ));
                };
                if let Some(flag) = used.get_mut(position) {
                    *flag = true;
                }
                rewritten.push('{');
                rewritten.push_str(&binding(position).to_string());
                if !spec.is_empty() {
                    rewritten.push(':');
                    rewritten.push_str(spec);
                }
                rewritten.push('}');
            }
        }
    }
    if let Some(unused) = used.iter().position(|flag| !flag) {
        let field = fields.get(unused).map_or("?", String::as_str);
        return Err(syn::Error::new(
            template.span(),
            format!("field `{field}` of `{ident}` is not used in its test id"),
        ));
    }

    if fields.is_empty() {
        let arm = quote!(Self::#ident => #krate::__private::Cow::Borrowed(#text),);
        return Ok((text, arm));
    }
    let bindings: Vec<Ident> = (0..fields.len()).map(binding).collect();
    let pattern = match &variant.fields {
        Fields::Named(named) => {
            let names = named.named.iter().filter_map(|f| f.ident.as_ref());
            quote!(Self::#ident { #(#names: ref #bindings),* })
        }
        Fields::Unnamed(_) => quote!(Self::#ident ( #(ref #bindings),* )),
        Fields::Unit => quote!(Self::#ident),
    };
    let format = LitStr::new(&rewritten, Span::call_site());
    let arm = quote! {
        #pattern => #krate::__private::Cow::Owned(::std::format!(#format)),
    };
    Ok((text, arm))
}

fn template_attr(variant: &Variant) -> syn::Result<Option<LitStr>> {
    let mut found = None;
    for attr in variant
        .attrs
        .iter()
        .filter(|a| a.path().is_ident("test_id"))
    {
        if found.is_some() {
            return Err(syn::Error::new_spanned(
                attr,
                "`#[test_id]` is set more than once",
            ));
        }
        found = Some(attr.parse_args::<LitStr>()?);
    }
    Ok(found)
}

/// Field names as a template refers to them: `0`, `1` for a tuple, the names otherwise.
fn field_names(fields: &Fields) -> Vec<String> {
    match fields {
        Fields::Named(named) => named
            .named
            .iter()
            .filter_map(|f| f.ident.as_ref().map(ToString::to_string))
            .collect(),
        Fields::Unnamed(unnamed) => (0..unnamed.unnamed.len()).map(|i| i.to_string()).collect(),
        Fields::Unit => Vec::new(),
    }
}

fn binding(position: usize) -> Ident {
    format_ident!("__icedwright_field_{position}")
}

#[cfg(test)]
mod tests {
    use super::*;
    use syn::parse_quote;

    fn expanded(input: DeriveInput) -> String {
        match expand(&input) {
            Ok(tokens) => tokens.to_string(),
            Err(error) => format!("error: {error}"),
        }
    }

    #[test]
    fn unit_variants_become_kebab_case_literals() {
        let out = expanded(parse_quote! {
            enum Ids { TodoList, NewItem }
        });
        assert!(out.contains("Self :: TodoList => :: icedwright_probe :: __private :: Cow :: Borrowed (\"todo-list\")"), "{out}");
        assert!(out.contains("\"new-item\""), "{out}");
        assert!(out.contains("\"Ids::NewItem\""), "{out}");
    }

    #[test]
    fn qualified_paths_start_at_the_calling_module() {
        let out = expanded(parse_quote! {
            enum Ids { Save, #[test_id("row-{0}")] Row(u32) }
        });
        assert!(
            out.contains("fn qualified_path (& self) -> & 'static str"),
            "{out}"
        );
        assert!(
            out.contains(
                "Self :: Save { .. } => :: core :: concat ! (:: core :: module_path ! () , \"::Ids::Save\")"
            ),
            "{out}"
        );
        assert!(
            out.contains(
                "Self :: Row { .. } => :: core :: concat ! (:: core :: module_path ! () , \"::Ids::Row\")"
            ),
            "{out}"
        );
    }

    #[test]
    fn the_attribute_overrides_and_formats_fields() {
        let out = expanded(parse_quote! {
            enum Ids {
                #[test_id("search")] SearchBox,
                #[test_id("delete-{0}")] Delete(u32),
                #[test_id("cell-{row}.{col}")] Cell { row: u32, col: u32 },
            }
        });
        assert!(out.contains("Cow :: Borrowed (\"search\")"), "{out}");
        assert!(
            out.contains("Self :: Delete (ref __icedwright_field_0)"),
            "{out}"
        );
        assert!(out.contains("\"delete-{__icedwright_field_0}\""), "{out}");
        assert!(
            out.contains("\"cell-{__icedwright_field_0}.{__icedwright_field_1}\""),
            "{out}"
        );
    }

    #[test]
    fn the_crate_attribute_changes_every_path() {
        let out = expanded(parse_quote! {
            #[icedwright_probe(crate = crate::shim)]
            enum Ids { Save }
        });
        assert!(out.contains("crate :: shim :: TestId"), "{out}");
        assert!(!out.contains("icedwright_probe"), "{out}");
    }

    #[test]
    fn generics_carry_into_the_impl() {
        let out = expanded(parse_quote! {
            enum Ids<T: Copy> where T: Default { #[test_id("row-{0}")] Row(T) }
        });
        assert!(
            out.contains(
                "impl < T : Copy > :: icedwright_probe :: TestId for Ids < T > where T : Default"
            ),
            "{out}"
        );
    }

    #[test]
    fn rejects_what_it_cannot_honour() {
        let cases: Vec<(DeriveInput, &str)> = vec![
            (
                parse_quote!(
                    struct S;
                ),
                "only be derived for an enum",
            ),
            (
                parse_quote!(
                    enum I {
                        A,
                        #[test_id("a")]
                        B,
                    }
                ),
                "already used by `A`",
            ),
            (
                parse_quote!(
                    enum I {
                        #[test_id("Upper")]
                        A,
                    }
                ),
                "found 'U'",
            ),
            (
                parse_quote!(
                    enum I {
                        #[test_id("a b")]
                        A,
                    }
                ),
                "found ' '",
            ),
            (
                parse_quote!(
                    enum I {
                        A(u32),
                    }
                ),
                "needs a format string",
            ),
            (
                parse_quote!(
                    enum I {
                        #[test_id("a-{1}")]
                        A(u32),
                    }
                ),
                "names no field",
            ),
            (
                parse_quote!(
                    enum I {
                        #[test_id("a-{0}")]
                        A(u32, u32),
                    }
                ),
                "field `1`",
            ),
            (
                parse_quote!(
                    enum I {
                        #[test_id("")]
                        A,
                    }
                ),
                "cannot be empty",
            ),
        ];
        for (input, wanted) in cases {
            let out = expanded(input);
            assert!(
                out.starts_with("error:") && out.contains(wanted),
                "{wanted}: {out}"
            );
        }
    }
}