18 releases

0.0.18 Nov 8, 2024
0.0.17 Jun 14, 2024
0.0.16 Jan 16, 2024
0.0.15 Oct 17, 2023
0.0.3 Dec 14, 2021

#107 in Rust patterns

Download history 42869/week @ 2024-07-27 45287/week @ 2024-08-03 35681/week @ 2024-08-10 41574/week @ 2024-08-17 46066/week @ 2024-08-24 47131/week @ 2024-08-31 41530/week @ 2024-09-07 43184/week @ 2024-09-14 50462/week @ 2024-09-21 40536/week @ 2024-09-28 47327/week @ 2024-10-05 49777/week @ 2024-10-12 52048/week @ 2024-10-19 46415/week @ 2024-10-26 53564/week @ 2024-11-02 52025/week @ 2024-11-09

214,120 downloads per month
Used in 47 crates (9 directly)

MIT license

190KB
3.5K SLoC

Virtue, a sinless derive macro helper

Goals

  • Zero dependencies, so fast compile times
  • No other dependencies needed
  • Declarative code generation
  • As much typesystem checking as possible
  • Build for modern rust: 1.57 and up
  • Build with popular crates in mind:
  • Will always respect semver. Minor releases will never have:
    • Breaking API changes
    • MSRV changes

Example

use virtue::prelude::*;

#[proc_macro_derive(YourDerive, attributes(some, attributes, go, here))]
pub fn derive_your_derive(input: TokenStream) -> TokenStream {
    derive_your_derive_inner(input)
        .unwrap_or_else(|error| error.into_token_stream())
}

fn derive_your_derive_inner(input: TokenStream) -> Result<TokenStream> {
    // Parse the struct or enum you want to implement a derive for
    let parse = Parse::new(input)?;
    // Get a reference to the generator
    let (mut generator, body) = parse.into_generator();
    match body {
        Body::Struct(body) => {
            // Implement your struct body here
            // See `Generator` for more information
            generator.impl_for("YourTrait")?
                    .generate_fn("your_fn")
                    .with_self_arg(FnSelfArg::RefSelf)
                    .body(|fn_body| {
                        fn_body.push_parsed("println!(\"Hello world\");");
                    })?;
        },
        Body::Enum(body) => {
            // Implement your enum body here
            // See `Generator` for more information
            generator.impl_for("YourTrait")?
                    .generate_fn("your_fn")
                    .with_self_arg(FnSelfArg::RefSelf)
                    .body(|fn_body| {
                        fn_body.push_parsed("println!(\"Hello world\");");
                    })?;
        },
    }
    generator.finish()
}

Will generate

impl YourTrait for <Struct or Enum> {
    fn your_fn(&self) { // .generate_fn("your_fn").with_self_arg(FnSelfArg::RefSelf)
        println!("Hello world"); // fn_body.push_parsed(...)
    }
}

Dependencies