blueglyph / trait_gen

Trait implementation generator macro
Apache License 2.0
25 stars 1 forks source link

Specializing trait methods for given cases #1

Open vigoo opened 4 hours ago

vigoo commented 4 hours ago

Thank you for the nice crate!

I needed support for specializing some method implementations in the generated traits for each case, while having a single implementation for the rest of the trait. What I came up with is a #[when] attribute that can be used on methods within a #[trait_gen] trait, for example

#[trait_gen(DB -> sqlx::sqlite::Sqlite, sqlx::mysql::MySql, sqlx::postgres::Postgres)]
#[async_trait]
impl Repo for sqlx::Pool<DB> {
    // ...
    #[when(sqlx::sqlite::Sqlite -> update)]
    async fn update_sqlite(&self, id: u64, param: String) -> Result<(), String> {
        // SQLite specific implementation
        todo!()
    }

    #[when(sqlx::mysql::MySql -> update)]
    async fn update_mysql(&self, id: u64, param: String) -> Result<(), String> {
        // MySQL specific implementation
        todo!()
    }
   // ...

As I needed this quickly, I published it as a fork: https://github.com/vigoo/conditional_trait_gen

But if you are interested, I'm happy to open a PR with it upstream.

blueglyph commented 2 hours ago

Glad it was useful! It started as a proof-of-concept when I fancied writing an RFC for something similar in the language, but I don't think many would find it interesting.

That's a nice feature you added. Yes, I think I'd like to merge that, at some point.

I also need to upgrade the code to support syn version 2.0 (and other dependencies), or it won't be able to parse the new Rust syntax elements. I won't do that in the next coming weeks because I'm full-time on another project. So it's as you wish, but by default, I'll grab the modification from your fork when the time comes, before tackling the 2.0 upgrade. That way, if you still want to modify your code, you won't have to bother with this repository.

I'll update this issue when the time comes.

Thanks!

blueglyph commented 1 hour ago

I quickly went over the modifications. I'll definitely merge it on my own (and give all the due credits) because I see there's a lot of reformatting that'll make the merge a little tricky and dependencies for the tests that I won't integrate in order to keep the crate as independent as possible (tokio).