PoignardAzur / venial

"A very small syn"
MIT License
192 stars 9 forks source link

Replacement for split_for_impl() on Generics? #26

Closed MTRNord closed 8 months ago

MTRNord commented 2 years ago

Syn offers https://docs.rs/syn/latest/syn/struct.Generics.html#method.split_for_impl for their generics to easily add implementations. I couldn't find an obvious way how to do this with venial. Is there a way, and if so, what would be the correct way?

MTRNord commented 2 years ago

My best guess was this, however I am not sure if "as_inline_args" i actually the one I want here:

    let impl_generics = input.generic_params.unwrap().as_inline_args();
    let ty_generics = input.generic_params.unwrap().params.iter().filter_map(|(param, _)| {
        if param.is_ty() {
            Some(param.name)
        } else {
            None
        }
    });

Especially as InlineGenericArgs is not usable via the public interface as the module it is in seems to be private.

PoignardAzur commented 2 years ago

Especially as InlineGenericArgs is not usable via the public interface as the module it is in seems to be private.

Right, InlineGenericArgs should probably be exported. That's an oversight.

It doesn't matter too much, since you can't build the type directly anyway and the builder function is public.

Is there a way, and if so, what would be the correct way?

Given the syn use-case:

let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
quote! {
    impl #impl_generics MyTrait for #name #ty_generics #where_clause {
        // ...
    }
}

Venial doesn't have an "all-in-one" method.

Instead you'd have:

let impl_generics = input.generic_params().unwrap();
let ty_generics = input.generic_params().unwrap().as_inline_args();

Though the idiomatic solution would be to match the declaration on its type (struct, enum or union) before trying to manipulate its generic arguments:

let struct_input = input.as_struct().unwrap();
let impl_generics = struct_input.generic_params.unwrap();
let ty_generics = struct_input.generic_params.unwrap().as_inline_args();
let where_clause = struct_input.where_clause;

I haven't really documented that idiom, though.

PoignardAzur commented 8 months ago

Added documentation in #48. I'm closing this in the meantime.