22 releases (1 stable)

new 1.0.0 Feb 11, 2025
0.14.6 Feb 10, 2025
0.14.2 Jul 17, 2024
0.10.1 Mar 29, 2024

#53 in Procedural macros

Download history 4557/week @ 2024-10-28 4132/week @ 2024-11-04 3407/week @ 2024-11-11 3470/week @ 2024-11-18 3573/week @ 2024-11-25 3562/week @ 2024-12-02 4505/week @ 2024-12-09 3070/week @ 2024-12-16 1208/week @ 2024-12-23 1512/week @ 2024-12-30 3702/week @ 2025-01-06 4358/week @ 2025-01-13 3206/week @ 2025-01-20 3919/week @ 2025-01-27 5160/week @ 2025-02-03 5838/week @ 2025-02-10

18,404 downloads per month
Used in 73 crates (29 directly)

MIT license

130KB
814 lines

derive-deftly: An ergonomic replacement for many proc macros

derive-deftly allows you to write macros which are driven by Rust data structures, just like proc macro derive macros, but without having to wrestle with the proc macro system.

Overview

You can write an ad-hoc template, which can speak about the fields and types in the data structure. You can also define named templates and apply them to multiple structures: effectively, you can define your own derive macro.

You don't need to make a separate proc macro crate, write to the syn and proc_macro APIs. take care to properly propagate compile errors, or, generally, do any of the things that make writing proc macros so complicated.

The template language resembles the "expander" part of a macro_rules macro, but you don't have to write the "matcher" part: derive-deftly parses the input data structure for you, and makes the pieces available via predefined expansion variables.

Full documentation is available in the doc_ module(s), the docs for the individual proc macros, and the Guide.

Simple example - providing Vec containing enum variant names

use derive_deftly::{define_derive_deftly, Deftly};

define_derive_deftly! {
    ListVariants:

    impl $ttype {
        fn list_variants() -> Vec<&'static str> {
            vec![ $( stringify!( $vname ) , ) ]
        }
    }
}

#[derive(Deftly)]
#[derive_deftly(ListVariants)]
enum Enum {
    UnitVariant,
    StructVariant { a: u8, b: u16 },
    TupleVariant(u8, u16),
}

assert_eq!(
    Enum::list_variants(),
    ["UnitVariant", "StructVariant", "TupleVariant"],
);

Next steps

Why not have a look at our friendly user guide? It will walk you through derive-deftly's most important features, with a number of worked examples.

Alternatively, there is comprehensive reference documentation.

Dependencies

~1.8–2.7MB
~51K SLoC